aoc-toolkit 0.1.0-alpha.4

A toolkit for solving Advent of Code problems
Documentation
use crate::client::http::AocHttpClient;
use crate::client::session::SessionStore;
use crate::client::session::resolve_session;

pub use crate::client::error::ClientError;

pub use crate::client::session::SessionSource;

#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum AuthStatus {
    Authenticated(SessionSource),
    Expired(SessionSource),
    Missing,
}

/// Verifies and securely stores an Advent of Code session.
///
/// # Errors
///
/// Returns an error if the session cannot be verified
/// or stored in the credential store.
pub fn login(token: &str) -> Result<(), ClientError> {
    let account_id = AocHttpClient::new()?.verify_session(token)?;

    SessionStore::remember_account(token, account_id)?;

    SessionStore::save(token)
}

/// Verifies the effective Advent of Code session.
///
/// # Errors
///
/// Returns an error if session configuration,
/// identity verification or credential access fails.
pub fn status() -> Result<AuthStatus, ClientError> {
    let Some((token, source)) = resolve_session()? else {
        return Ok(AuthStatus::Missing);
    };

    match AocHttpClient::new()?.verify_session(&token) {
        Ok(account_id) => {
            SessionStore::remember_account(&token, account_id)?;

            Ok(AuthStatus::Authenticated(source))
        }

        Err(ClientError::Unauthorized) => Ok(AuthStatus::Expired(source)),

        Err(error) => Err(error),
    }
}

/// Removes the stored session.
///
/// # Errors
///
/// Returns an error if the credential cannot be removed.
pub fn logout() -> Result<(), ClientError> {
    SessionStore::delete()
}