smbpndk-cli 0.3.7

Command line tool for creating and managing SmbPndk resources.
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
use crate::account::{
    forgot::{Param, UserUpdatePassword},
    lib::{authorize_github, save_token, ErrorCode, GithubInfo, SmbAuthorization},
    model::{Data, Status, User},
    signup::{
        do_signup, GithubEmail, Provider, SignupGithubParams, SignupMethod, SignupUserGithub,
    },
};
use anyhow::{anyhow, Result};
use console::{style, Term};
use dialoguer::{theme::ColorfulTheme, Confirm, Input, Password, Select};
use log::debug;
use reqwest::{Client, StatusCode};
use serde::{Deserialize, Serialize};
use smbpndk_model::CommandResult;
use smbpndk_networking::{get_smb_token, smb_base_url_builder, smb_token_file_path};
use smbpndk_utils::email_validation;
use spinners::Spinner;
use std::fs::{self};

pub struct LoginArgs {
    pub username: String,
    pub password: String,
}

#[derive(Debug, Serialize)]
struct LoginParams {
    user: UserParam,
}

#[derive(Debug, Serialize)]
struct UserParam {
    email: String,
    password: String,
}

#[derive(Debug, Serialize, Deserialize)]
struct LoginResult {
    status: Status,
    data: Data,
}

pub async fn process_login() -> Result<CommandResult> {
    // Check if token file exists
    if smb_token_file_path().is_some() {
        return Ok(CommandResult {
            spinner: Spinner::new(
                spinners::Spinners::SimpleDotsScrolling,
                style("Loading...").green().bold().to_string(),
            ),
            symbol: "".to_owned(),
            msg: "You are already logged in. Please logout first.".to_owned(),
        });
    }

    let signup_methods = vec![SignupMethod::Email, SignupMethod::GitHub];
    let selection = Select::with_theme(&ColorfulTheme::default())
        .items(&signup_methods)
        .default(0)
        .interact_on_opt(&Term::stderr())
        .map(|i| signup_methods[i.unwrap()])
        .unwrap();

    match selection {
        SignupMethod::Email => login_with_email().await,
        SignupMethod::GitHub => login_with_github().await,
    }
}

pub async fn process_logout() -> Result<CommandResult> {
    // Logout if user confirms
    if let Some(token_path) = smb_token_file_path() {
        let confirm = Confirm::with_theme(&ColorfulTheme::default())
            .with_prompt("Do you want to logout? y/n")
            .interact()
            .unwrap();
        if !confirm {
            return Ok(CommandResult {
                spinner: Spinner::new(
                    spinners::Spinners::SimpleDotsScrolling,
                    style("Cancel operation.").green().bold().to_string(),
                ),
                symbol: "".to_owned(),
                msg: "Doing nothing.".to_owned(),
            });
        }

        let mut spinner = Spinner::new(
            spinners::Spinners::SimpleDotsScrolling,
            style("Logging you out...").green().bold().to_string(),
        );

        // Call backend
        match do_process_logout().await {
            Ok(_) => {
                spinner.stop_and_persist("", "Done.".to_owned());
                fs::remove_file(token_path)?;
                Ok(CommandResult {
                    spinner: Spinner::new(
                        spinners::Spinners::SimpleDotsScrolling,
                        style("Loading...").green().bold().to_string(),
                    ),
                    symbol: "".to_owned(),
                    msg: "You are now logged out!".to_owned(),
                })
            }
            Err(e) => Err(anyhow!("{e}")),
        }
    } else {
        Ok(CommandResult {
            spinner: Spinner::new(
                spinners::Spinners::SimpleDotsScrolling,
                style("Loading...").green().bold().to_string(),
            ),
            symbol: "😏".to_owned(),
            msg: "You are not logged in.".to_owned(),
        })
    }
}

// Private functions

async fn login_with_github() -> Result<CommandResult> {
    match authorize_github().await {
        Ok(result) => process_authorization(result).await,
        Err(err) => {
            let error = anyhow!("Failed to authorize your GitHub account. {}", err);
            Err(error)
        }
    }
}

async fn process_authorization(auth: SmbAuthorization) -> Result<CommandResult> {
    // What to do if not logged in with GitHub?
    // Check error_code first
    if let Some(error_code) = auth.error_code {
        debug!("{}", error_code);
        match error_code {
            ErrorCode::EmailNotFound => {
                return create_new_account(auth.user_email, auth.user_info).await
            }
            ErrorCode::EmailUnverified => return send_email_verification(auth.user).await,
            ErrorCode::PasswordNotSet => {
                // Only for email and password login
                let error = anyhow!("Password not set.");
                return Err(error);
            }
            ErrorCode::GithubNotLinked => return connect_github_account(auth).await,
        }
    }

    // Logged in with GitHub!
    // Token handling is in the lib.rs account module.
    if let Some(user) = auth.user {
        let spinner = Spinner::new(
            spinners::Spinners::SimpleDotsScrolling,
            style("Logging you in...").green().bold().to_string(),
        );
        // We're logged in with GitHub.
        return Ok(CommandResult {
            spinner,
            symbol: "".to_owned(),
            msg: format!("You are logged in with GitHub as {}.", user.email),
        });
    }

    let error: anyhow::Error = anyhow!("Failed to login with GitHub.");
    Err(error)
}

async fn create_new_account(
    user_email: Option<GithubEmail>,
    user_info: Option<GithubInfo>,
) -> Result<CommandResult> {
    let confirm = Confirm::with_theme(&ColorfulTheme::default())
        .with_prompt("Do you want to create a new account?")
        .interact()
        .unwrap();

    // Create account if user confirms
    if !confirm {
        let spinner = Spinner::new(
            spinners::Spinners::SimpleDotsScrolling,
            style("Logging you in...").green().bold().to_string(),
        );
        return Ok(CommandResult {
            spinner,
            symbol: "".to_owned(),
            msg: "Please accept to link your GitHub account.".to_owned(),
        });
    }

    if let (Some(email), Some(info)) = (user_email, user_info) {
        let params = SignupGithubParams {
            user: SignupUserGithub {
                email: email.email,
                authorizations_attributes: vec![Provider {
                    uid: info.id.to_string(),
                    provider: 0,
                }],
            },
        };

        return do_signup(&params).await;
    }

    Err(anyhow!("Shouldn't be here."))
}

async fn send_email_verification(user: Option<User>) -> Result<CommandResult> {
    // Return early if user is null
    if let Some(user) = user {
        let confirm = Confirm::with_theme(&ColorfulTheme::default())
            .with_prompt("Do you want to send a new verification email?")
            .interact()
            .unwrap();

        // Send verification email if user confirms
        if !confirm {
            let spinner = Spinner::new(
                spinners::Spinners::SimpleDotsScrolling,
                style("Cancel operation.").green().bold().to_string(),
            );
            return Ok(CommandResult {
                spinner,
                symbol: "".to_owned(),
                msg: "Doing nothing.".to_owned(),
            });
        }
        resend_email_verification(user).await
    } else {
        let error = anyhow!("Failed to get user.");
        Err(error)
    }
}

async fn resend_email_verification(user: User) -> Result<CommandResult> {
    let spinner = Spinner::new(
        spinners::Spinners::SimpleDotsScrolling,
        style("Sending verification email...")
            .green()
            .bold()
            .to_string(),
    );

    let response = Client::new()
        .post(build_smb_resend_email_verification_url())
        .body(format!("id={}", user.id))
        .header("Accept", "application/json")
        .header("Content-Type", "application/x-www-form-urlencoded")
        .send()
        .await?;

    match response.status() {
        reqwest::StatusCode::OK => Ok(CommandResult {
            spinner,
            symbol: "".to_owned(),
            msg: "Verification email sent!".to_owned(),
        }),
        _ => {
            let error = anyhow!("Failed to send verification email.");
            Err(error)
        }
    }
}

async fn connect_github_account(auth: SmbAuthorization) -> Result<CommandResult> {
    let confirm = Confirm::with_theme(&ColorfulTheme::default())
        .with_prompt("Do you want to link your GitHub account?")
        .interact()
        .unwrap();

    // Link GitHub account if user confirms
    if !confirm {
        let spinner = Spinner::new(
            spinners::Spinners::SimpleDotsScrolling,
            style("Cancel operation.").green().bold().to_string(),
        );
        return Ok(CommandResult {
            spinner,
            symbol: "".to_owned(),
            msg: "Doing nothing.".to_owned(),
        });
    }

    let spinner = Spinner::new(
        spinners::Spinners::SimpleDotsScrolling,
        style("Linking your GitHub account...")
            .green()
            .bold()
            .to_string(),
    );

    let response = Client::new()
        .post(build_smb_connect_github_url())
        .json(&auth)
        .header("Accept", "application/json")
        .header("Content-Type", "application/x-www-form-urlencoded")
        .send()
        .await?;

    match response.status() {
        reqwest::StatusCode::OK => Ok(CommandResult {
            spinner,
            symbol: "".to_owned(),
            msg: "GitHub account linked!".to_owned(),
        }),
        _ => {
            let error = anyhow!("Failed to link GitHub account.");
            Err(error)
        }
    }
}

async fn login_with_email() -> Result<CommandResult> {
    println!("Provide your login credentials.");
    let username = Input::<String>::with_theme(&ColorfulTheme::default())
        .with_prompt("Email")
        .validate_with(|email: &String| email_validation(email))
        .interact()
        .unwrap();
    let password = Password::with_theme(&ColorfulTheme::default())
        .with_prompt("Password")
        .interact()
        .unwrap();
    do_process_login(LoginArgs { username, password }).await
}

async fn do_process_login(args: LoginArgs) -> Result<CommandResult> {
    let login_params = LoginParams {
        user: UserParam {
            email: args.username,
            password: args.password,
        },
    };

    let response = Client::new()
        .post(build_smb_login_url())
        .json(&login_params)
        .send()
        .await?;

    match response.status() {
        StatusCode::OK => {
            // Login successful
            save_token(&response).await?;
            Ok(CommandResult {
                spinner: Spinner::new(
                    spinners::Spinners::SimpleDotsScrolling,
                    style("Loading...").green().bold().to_string(),
                ),
                symbol: "".to_owned(),
                msg: "You are now logged in!".to_owned(),
            })
        }
        StatusCode::NOT_FOUND => {
            // Account not found and we show signup option
            Ok(CommandResult {
                spinner: Spinner::new(
                    spinners::Spinners::SimpleDotsScrolling,
                    style("Account not found.").green().bold().to_string(),
                ),
                symbol: "".to_owned(),
                msg: "Please signup!".to_owned(),
            })
        }
        StatusCode::UNPROCESSABLE_ENTITY => {
            // Account found but email not verified / password not set
            let result: SmbAuthorization = response.json().await?;
            // println!("Result: {:#?}", &result);
            verify_or_set_password(result).await
        }
        _ => Err(anyhow!("Login failed. Check your username and password.")),
    }
}

async fn verify_or_set_password(result: SmbAuthorization) -> Result<CommandResult> {
    match result.error_code {
        Some(error_code) => {
            debug!("{}", error_code);
            match error_code {
                ErrorCode::EmailUnverified => send_email_verification(result.user).await,
                ErrorCode::PasswordNotSet => send_reset_password(result.user).await,
                _ => Err(anyhow!("Shouldn't be here.")),
            }
        }
        None => Err(anyhow!("Shouldn't be here.")),
    }
}

async fn send_reset_password(user: Option<User>) -> Result<CommandResult> {
    // Return early if user is null
    if let Some(user) = user {
        let confirm = Confirm::with_theme(&ColorfulTheme::default())
            .with_prompt("Do you want to reset your password?")
            .interact()
            .unwrap();

        // Send verification email if user confirms
        if !confirm {
            let spinner = Spinner::new(
                spinners::Spinners::SimpleDotsScrolling,
                style("Cancel operation.").green().bold().to_string(),
            );
            return Ok(CommandResult {
                spinner,
                symbol: "".to_owned(),
                msg: "Doing nothing.".to_owned(),
            });
        }
        resend_reset_password_instruction(user).await
    } else {
        let error = anyhow!("Failed to get user.");
        Err(error)
    }
}

async fn resend_reset_password_instruction(user: User) -> Result<CommandResult> {
    let mut spinner = Spinner::new(
        spinners::Spinners::SimpleDotsScrolling,
        style("Sending reset password instruction...")
            .green()
            .bold()
            .to_string(),
    );
    let response = Client::new()
        .post(build_smb_resend_reset_password_instructions_url())
        .body(format!("id={}", user.id))
        .header("Accept", "application/json")
        .header("Content-Type", "application/x-www-form-urlencoded")
        .send()
        .await?;

    match response.status() {
        StatusCode::OK => {
            spinner.stop_and_persist(
                "",
                "Reset password instruction sent! Please check your email.".to_owned(),
            );
            input_reset_password_token().await
        }
        _ => {
            let error = anyhow!("Failed to send reset password instruction.");
            Err(error)
        }
    }
}

async fn input_reset_password_token() -> Result<CommandResult> {
    let token = Input::<String>::with_theme(&ColorfulTheme::default())
        .with_prompt("Input reset password token")
        .interact()
        .unwrap();
    let password = Password::with_theme(&ColorfulTheme::default())
        .with_prompt("New password.")
        .with_confirmation("Repeat password.", "Error: the passwords don't match.")
        .interact()
        .unwrap();

    let spinner = Spinner::new(
        spinners::Spinners::SimpleDotsScrolling,
        style("Resetting password...").green().bold().to_string(),
    );

    let password_confirmation = password.clone();

    let params = Param {
        user: UserUpdatePassword {
            reset_password_token: token,
            password,
            password_confirmation,
        },
    };

    let response = Client::new()
        .put(build_smb_reset_password_url())
        .json(&params)
        .header("Accept", "application/json")
        .header("Content-Type", "application/x-www-form-urlencoded")
        .send()
        .await?;

    match response.status() {
        StatusCode::OK => Ok(CommandResult {
            spinner,
            symbol: "".to_owned(),
            msg: "Password reset!".to_owned(),
        }),
        _ => {
            let error = anyhow!("Failed to reset password.");
            Err(error)
        }
    }
}

async fn do_process_logout() -> Result<()> {
    let token = get_smb_token().await?;

    let response = Client::new()
        .delete(build_smb_logout_url())
        .header("Authorization", token)
        .header("Accept", "application/json")
        .header("Content-Type", "application/x-www-form-urlencoded")
        .send()
        .await?;

    match response.status() {
        StatusCode::OK => Ok(()),
        _ => Err(anyhow!("Failed to logout.")),
    }
}

fn build_smb_login_url() -> String {
    let mut url_builder = smb_base_url_builder();
    url_builder.add_route("v1/users/sign_in");
    url_builder.build()
}

fn build_smb_logout_url() -> String {
    let mut url_builder = smb_base_url_builder();
    url_builder.add_route("v1/users/sign_out");
    url_builder.build()
}

fn build_smb_resend_email_verification_url() -> String {
    let mut url_builder = smb_base_url_builder();
    url_builder.add_route("v1/resend_confirmation");
    url_builder.build()
}

fn build_smb_resend_reset_password_instructions_url() -> String {
    let mut url_builder = smb_base_url_builder();
    url_builder.add_route("v1/resend_reset_password_instructions");
    url_builder.build()
}

fn build_smb_reset_password_url() -> String {
    let mut url_builder = smb_base_url_builder();
    url_builder.add_route("v1/users/password");
    url_builder.build()
}

fn build_smb_connect_github_url() -> String {
    let mut url_builder = smb_base_url_builder();
    url_builder.add_route("v1/link_github_account");
    url_builder.build()
}