Skip to main content

socorro_cli/commands/
auth.rs

1// This Source Code Form is subject to the terms of the Mozilla Public
2// License, v. 2.0. If a copy of the MPL was not distributed with this
3// file, You can obtain one at http://mozilla.org/MPL/2.0/.
4
5use crate::{auth, Result};
6use std::io::{self, Write};
7
8pub fn login() -> Result<()> {
9    if auth::has_token() {
10        print!("A token is already stored. Replace it? [y/N] ");
11        io::stdout().flush().unwrap();
12        let mut input = String::new();
13        io::stdin().read_line(&mut input).unwrap();
14        if !input.trim().eq_ignore_ascii_case("y") {
15            println!("Cancelled.");
16            return Ok(());
17        }
18    }
19
20    print!("Enter your Socorro API token: ");
21    io::stdout().flush().unwrap();
22
23    let token = rpassword::read_password().unwrap_or_default();
24
25    if token.is_empty() {
26        println!("No token provided. Cancelled.");
27        return Ok(());
28    }
29
30    auth::store_token(&token)?;
31    println!("Token stored in system keychain.");
32    Ok(())
33}
34
35pub fn logout() -> Result<()> {
36    if !auth::has_token() {
37        println!("No token stored.");
38        return Ok(());
39    }
40
41    auth::delete_token()?;
42    println!("Token removed from system keychain.");
43    Ok(())
44}
45
46fn check_token_path_fallback() {
47    if let Ok(path) = std::env::var("SOCORRO_API_TOKEN_PATH") {
48        if std::path::Path::new(&path).exists() {
49            println!("SOCORRO_API_TOKEN_PATH is set and file exists (CI fallback).");
50        } else {
51            println!(
52                "SOCORRO_API_TOKEN_PATH is set but file does not exist: {}",
53                path
54            );
55        }
56    }
57}
58
59pub fn status() -> Result<()> {
60    match auth::get_keychain_status() {
61        auth::KeychainStatus::HasToken => {
62            println!("Token is stored in system keychain.");
63        }
64        auth::KeychainStatus::NoToken => {
65            println!("No token stored in keychain.");
66            check_token_path_fallback();
67        }
68        auth::KeychainStatus::Error(e) => {
69            println!("Keychain error: {}", e);
70            check_token_path_fallback();
71        }
72    }
73    Ok(())
74}