Skip to main content

aoc_toolkit/application/
auth.rs

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