wapm_cli/commands/
login.rs1use crate::config::{Config, UpdateRegistry};
2use crate::graphql::execute_query;
3use rpassword_wasi as rpassword;
4use std::io::prelude::*;
5use std::io::{stdin, stdout};
6use structopt::StructOpt;
7
8use graphql_client::*;
9
10#[derive(StructOpt, Debug)]
11pub struct LoginOpt {
12 token: Option<String>,
14 #[structopt(long = "quiet")]
16 quiet: bool,
17 #[structopt(long)]
19 user: Option<String>,
20 #[structopt(long)]
22 password: Option<String>,
23}
24
25#[derive(GraphQLQuery)]
26#[graphql(
27 schema_path = "graphql/schema.graphql",
28 query_path = "graphql/queries/login.graphql",
29 response_derives = "Debug"
30)]
31struct LoginMutation;
32
33pub fn login(login_options: LoginOpt) -> anyhow::Result<()> {
34 if let Some(token) = login_options.token {
35 let mut config = Config::from_file()?;
36 config.registry.set_login_token_for_registry(
37 &config.registry.get_current_registry(),
38 &token,
39 UpdateRegistry::Update,
40 );
41 config.save()?;
42 if !login_options.quiet {
43 if let Some(s) = crate::util::get_username().ok().and_then(|o| o) {
44 println!("Login for WAPM user {:?} saved", s);
45 } else {
46 println!("Login for WAPM user saved");
47 }
48 }
49 return Ok(());
50 }
51
52 let username = if let Some(u) = login_options.user.as_ref() {
53 u.to_string()
54 } else {
55 print!("Username: ");
56 stdout().flush().expect("Could not flush stdout");
57
58 let buffer = &mut String::new();
59 stdin().read_line(buffer)?;
60 buffer.trim_end().to_string()
61 };
62
63 let password = if let Some(p) = login_options.password.as_ref() {
64 p.to_string()
65 } else {
66 rpassword::prompt_password("Password: ").expect("Can't get password")
67 };
68
69 let q = LoginMutation::build_query(login_mutation::Variables { username, password });
70 let response: login_mutation::ResponseData = execute_query(&q)?;
71 let token = match response.token_auth {
72 Some(token_auth) => Some(token_auth.refresh_token),
73 None => None,
74 };
75 if let Some(token) = token {
76 let mut config = Config::from_file()?;
78 config.registry.set_login_token_for_registry(
79 &config.registry.get_current_registry(),
80 &token,
81 UpdateRegistry::Update,
82 );
83 config.save()?;
84
85 if !login_options.quiet {
86 if let Some(u) = crate::util::get_username().ok().and_then(|o| o) {
87 println!(
88 "Successfully logged into registry {:?} as user {:?}",
89 config.registry.get_current_registry(),
90 u
91 );
92 }
93 }
94 }
95 Ok(())
96}