aoc-toolkit 0.1.0-alpha.2

A toolkit for solving Advent of Code problems
Documentation
use crate::adapters::browser::SystemBrowser;
use crate::application::auth::{self, AuthStatus};
use crate::cli::error::CliError;
use clap::{Args, Subcommand};

#[derive(Debug, Args)]
pub struct AuthArgs {
    #[command(subcommand)]
    command: AuthCommand,
}

#[derive(Debug, Subcommand)]
enum AuthCommand {
    /// Authenticate with Advent of Code
    #[command(after_help = MANUAL_LOGIN_HELP)]
    Login {
        /// Enter a session token without opening the browser
        #[arg(long)]
        manual: bool,
    },

    /// Check whether a session is stored
    Status,

    /// Remove the stored session
    Logout,
}

pub(crate) fn execute(args: &AuthArgs) -> Result<(), CliError> {
    match args.command {
        AuthCommand::Login { manual } => {
            login(manual)?;
        }

        AuthCommand::Status => {
            match auth::status()? {
                AuthStatus::Authenticated => {
                    println!("✓ Authenticated with Advent of Code.");
                }

                AuthStatus::Expired => {
                    println!("✗ Stored session is no longer valid.");
                    println!("Run `aoc auth login`.");
                }

                AuthStatus::Missing => {
                    println!("No stored session.");
                    println!("Run `aoc auth login`.");
                }
            }

            println!("SESSION_ID overrides the stored session.");
        }

        AuthCommand::Logout => {
            auth::logout()?;

            println!("✓ Stored session removed.");
            println!("SESSION_ID overrides are not affected.");
        }
    }

    Ok(())
}

pub(super) fn login(manual: bool) -> Result<(), CliError> {
    if !manual {
        SystemBrowser::open_login()?;
    }

    println!("{MANUAL_LOGIN_HELP}");
    println!();

    let token =
        rpassword::prompt_password("Advent of Code session: ").map_err(CliError::ReadSession)?;

    auth::login(token.trim())?;

    println!("✓ Session stored securely.");

    Ok(())
}

pub(super) const MANUAL_LOGIN_HELP: &str = "\
Manual authentication:
  1. Open https://adventofcode.com and sign in to your account.
  2. Open your browser's developer tools.
  3. Locate cookies for adventofcode.com
     (Application in Chromium, Storage in Firefox).
  4. Copy the value of your own session cookie.
  5. Paste it into the secure terminal prompt.

Never share your session token or commit it to version control.
The token is stored in your system credential store.";