Skip to main content

aoc_toolkit/application/
auth.rs

1use crate::client::http::AocHttpClient;
2use crate::client::session::SessionStore;
3use crate::client::session::resolve_session;
4
5pub use crate::client::error::ClientError;
6
7pub use crate::client::session::SessionSource;
8
9#[derive(Debug, Clone, Copy, PartialEq, Eq)]
10pub enum AuthStatus {
11    Authenticated(SessionSource),
12    Expired(SessionSource),
13    Missing,
14}
15
16/// Verifies and securely stores an Advent of Code session.
17///
18/// # Errors
19///
20/// Returns an error if the session cannot be verified
21/// or stored in the credential store.
22pub fn login(token: &str) -> Result<(), ClientError> {
23    let account_id = AocHttpClient::new()?.verify_session(token)?;
24
25    SessionStore::remember_account(token, account_id)?;
26
27    SessionStore::save(token)
28}
29
30/// Verifies the effective Advent of Code session.
31///
32/// # Errors
33///
34/// Returns an error if session configuration,
35/// identity verification or credential access fails.
36pub fn status() -> Result<AuthStatus, ClientError> {
37    let Some((token, source)) = resolve_session()? else {
38        return Ok(AuthStatus::Missing);
39    };
40
41    match AocHttpClient::new()?.verify_session(&token) {
42        Ok(account_id) => {
43            SessionStore::remember_account(&token, account_id)?;
44
45            Ok(AuthStatus::Authenticated(source))
46        }
47
48        Err(ClientError::Unauthorized) => Ok(AuthStatus::Expired(source)),
49
50        Err(error) => Err(error),
51    }
52}
53
54/// Removes the stored session.
55///
56/// # Errors
57///
58/// Returns an error if the credential cannot be removed.
59pub fn logout() -> Result<(), ClientError> {
60    SessionStore::delete()
61}