novel_cli/utils/
login.rs

1use color_eyre::eyre::Result;
2use fluent_templates::Loader;
3use novel_api::{Client, Keyring};
4
5use crate::cmd::Source;
6use crate::{LANG_ID, LOCALES};
7
8pub async fn log_in<T>(client: &T, source: &Source, ignore_keyring: bool) -> Result<()>
9where
10    T: Client,
11{
12    match client.logged_in().await {
13        Ok(false) | Err(_) => {
14            let user_name = get_user_name()?;
15
16            if ignore_keyring {
17                let password = get_password()?;
18                client.log_in(user_name, Some(password)).await?;
19            } else {
20                let keyring = Keyring::new(source, &user_name)?;
21                let password = keyring.get_password();
22
23                if let Ok(password) = password {
24                    tracing::info!("Successfully obtained password from Keyring");
25
26                    client.log_in(user_name, Some(password)).await?;
27                } else {
28                    tracing::info!("Unable to get password from Keyring");
29
30                    let password = get_password()?;
31                    client.log_in(user_name, Some(password.clone())).await?;
32
33                    keyring.set_password(password)?;
34                }
35            }
36        }
37        _ => (),
38    }
39
40    Ok(())
41}
42
43pub async fn log_in_without_password<T>(client: &T) -> Result<()>
44where
45    T: Client,
46{
47    match client.logged_in().await {
48        Ok(false) | Err(_) => {
49            let user_name = get_user_name()?;
50            client.log_in(user_name, None).await?;
51        }
52        _ => (),
53    }
54
55    Ok(())
56}
57
58fn get_user_name() -> Result<String> {
59    Ok(novel_api::input(
60        LOCALES.lookup(&LANG_ID, "enter_user_name"),
61    )?)
62}
63
64fn get_password() -> Result<String> {
65    Ok(novel_api::password(
66        LOCALES.lookup(&LANG_ID, "enter_password"),
67    )?)
68}