5.0 KiB · text History bbb2a48
//! Signing in, signing out, and finding out who you are.
//!
//! `login` verifies before it saves: `GET /api/0/` names the token's user
//! (and answers `"user": null` without a valid token), so a typo'd token
//! is caught here rather than on the next command.

use anyhow::{Context, Result, bail};
use std::io::{IsTerminal, Read, Write};

use crate::api::Client;
use crate::cli::LoginArgs;
use crate::commands::Ctx;
use crate::config::{self, Config, Flags};
use crate::output::{Tone, bold, field, heading, note, paint};

pub fn login(args: &LoginArgs, flags: &Flags, json: bool) -> Result<()> {
    let mut cfg = Config::load()?;

    let url = match flags
        .url
        .clone()
        .or_else(|| config::process_env(config::ENV_URL))
    {
        Some(url) => url,
        None => match &cfg.url {
            Some(url) if !std::io::stdin().is_terminal() || args.token_stdin => url.clone(),
            saved => prompt("Server URL", saved.as_deref())?,
        },
    };
    let url = config::normalize_url(&url);

    let token = if args.token_stdin {
        let mut buf = String::new();
        std::io::stdin()
            .read_to_string(&mut buf)
            .context("reading the token from stdin")?;
        buf
    } else if let Some(token) = flags
        .token
        .clone()
        .or_else(|| config::process_env(config::ENV_TOKEN))
    {
        token
    } else {
        if !std::io::stdin().is_terminal() {
            bail!("no API token: pass --token-stdin (or --token, or set VIGIL_TOKEN)");
        }
        rpassword::prompt_password("API token: ").context("reading the token")?
    };
    let token = token.trim().to_string();
    if token.is_empty() {
        bail!("no API token given");
    }

    let client = Client::new(&url, &token)?;
    let root = client
        .root()
        .with_context(|| format!("checking the token against {url}"))?;
    let Some(user) = &root.user else {
        bail!("{url} didn't accept the token (is it a Vigil or Sentry server?)");
    };

    cfg.url = Some(url.clone());
    cfg.token = Some(token);
    if let Some(org) = &flags.org {
        cfg.org = Some(org.clone());
    }
    if let Some(project) = &flags.project {
        cfg.project = Some(project.clone());
    }
    // One organization: make it the default, so nothing needs --org.
    if cfg.org.is_none()
        && let Ok(orgs) = client.organizations()
        && let [only] = orgs.data.as_slice()
    {
        cfg.org = Some(only.slug.clone());
    }
    let path = cfg.save()?;

    if json {
        return crate::output::print_json(&root.raw);
    }

    println!(
        "{} as {} on {url}",
        paint("Signed in", Tone::Good),
        bold(user.email.as_deref().unwrap_or(&user.id))
    );
    if let Some(org) = &cfg.org {
        note(&format!("organization: {org}"));
    }
    note(&format!("credentials saved to {}", path.display()));
    Ok(())
}

pub fn logout(json: bool) -> Result<()> {
    let mut cfg = Config::load()?;
    let had = cfg.token.is_some();
    cfg.clear_credentials();
    let path = cfg.save()?;

    if json {
        return crate::output::print_json(&serde_json::json!({
            "signedOut": had,
            "config": path.display().to_string(),
        }));
    }
    if had {
        println!(
            "Signed out. The token itself still works until it is revoked in the web UI (Settings → API tokens)."
        );
    } else {
        note("Nothing to sign out of.");
    }
    Ok(())
}

pub fn whoami(ctx: &Ctx) -> Result<()> {
    let root = ctx.api.root()?;
    if ctx.emitted(&root.raw)? {
        return Ok(());
    }
    let Some(user) = &root.user else {
        bail!("the server doesn't recognise this token");
    };

    heading(
        user.name
            .as_deref()
            .or(user.email.as_deref())
            .unwrap_or(&user.id),
    );
    if let Some(email) = &user.email {
        field("email", email);
    }
    field("server", &ctx.settings.url);
    if let Some(org) = &ctx.settings.org {
        field("org", org);
    }
    if let Some(project) = &ctx.settings.project {
        field("project", project);
    }
    if let Some(auth) = &root.auth {
        if let Some(label) = &auth.label {
            field("token", label);
        }
        field(
            "scopes",
            &if auth.scopes.is_empty() {
                "(none)".to_string()
            } else {
                auth.scopes.join(" ")
            },
        );
    }
    Ok(())
}

fn prompt(label: &str, default: Option<&str>) -> Result<String> {
    if !std::io::stdin().is_terminal() {
        bail!("no {label}: pass --url (or set VIGIL_URL) when running non-interactively");
    }
    match default {
        Some(d) => print!("{label} [{d}]: "),
        None => print!("{label}: "),
    }
    std::io::stdout().flush()?;
    let mut line = String::new();
    std::io::stdin().read_line(&mut line)?;
    let line = line.trim();
    match (line.is_empty(), default) {
        (true, Some(d)) => Ok(d.to_string()),
        (true, None) => bail!("no {label} given"),
        (false, _) => Ok(line.to_string()),
    }
}