spacetimedb-cli 0.7.1

A command line interface for SpacetimeDB
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
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
use crate::{
    config::{Config, IdentityConfig},
    util::{init_default, y_or_n, IdentityTokenJson, InitDefaultResultType},
};
use std::io::Write;

use crate::util::{is_hex_identity, print_identity_config};
use anyhow::Context;
use clap::{Arg, ArgAction, ArgMatches, Command};
use email_address::EmailAddress;
use reqwest::{StatusCode, Url};
use serde::Deserialize;
use spacetimedb::auth::identity::decode_token;
use spacetimedb_lib::recovery::RecoveryCodeResponse;
use tabled::{object::Columns, Alignment, Modify, Style, Table, Tabled};

pub fn cli() -> Command {
    Command::new("identity")
        .args_conflicts_with_subcommands(true)
        .subcommand_required(true)
        .subcommands(get_subcommands())
        .about("Manage identities stored by the command line tool")
}

fn get_subcommands() -> Vec<Command> {
    vec![
        Command::new("list").about("List saved identities which apply to a server")
            .arg(
                Arg::new("server")
                    .help("The nickname, host name or URL of the server to list identities for")
                    .conflicts_with("all")
            )
            .arg(
                Arg::new("all")
                    .short('a')
                    .long("all")
                    .help("List all stored identities, regardless of server")
                    .action(ArgAction::SetTrue)
                    .conflicts_with("server")
            )
            // TODO: project flag?
            ,
        Command::new("set-default").about("Set the default identity for a server")
            .arg(
                Arg::new("identity")
                    .help("The identity string or name that should become the new default identity")
                    .required(true),
            )
            .arg(
                Arg::new("server")
                    .long("server")
                    .short('s')
                    .help("The server nickname, host name or URL of the server which should use this identity as a default")
            )
            // TODO: project flag?
            ,
        Command::new("set-email")
            .about("Associates an email address with an identity")
            .arg(
                Arg::new("identity")
                    .help("The identity string or name that should be associated with the email")
                    .required(true),
            )
            .arg(
                Arg::new("email")
                    .help("The email that should be assigned to the provided identity")
                    .required(true),
            )
            .arg(
                Arg::new("server")
                    .long("server")
                    .short('s')
                    .help("The server that should be informed of the email change")
                    .conflicts_with("all-servers")
            )
            .arg(
                Arg::new("all-servers")
                    .long("all-servers")
                    .short('a')
                    .action(ArgAction::SetTrue)
                    .help("Inform all known servers of the email change")
                    .conflicts_with("server")
            ),
        Command::new("init-default")
            .about("Initialize a new default identity if it is missing from a server's config")
            .arg(
                Arg::new("server")
                    .long("server")
                    .short('s')
                    .help("The nickname, host name or URL of the server for which to set the default identity"),
            )
            .arg(
                Arg::new("name")
                    .long("name")
                    .short('n')
                    .help("The name of the identity that should become the new default identity"),
            )
            .arg(
                Arg::new("quiet")
                    .long("quiet")
                    .short('q')
                    .action(ArgAction::SetTrue)
                    .help("Runs command in silent mode"),
            ),
        Command::new("new")
            .about("Creates a new identity")
            .arg(
                Arg::new("server")
                    .long("server")
                    .short('s')
                    .help("The nickname, host name or URL of the server from which to request the identity"),
            )
            .arg(
                Arg::new("no-save")
                    .help("Don't save save to local config, just create a new identity")
                    .long("no-save")
                    .action(ArgAction::SetTrue),
            )
            .arg(
                Arg::new("name")
                    .long("name")
                    .short('n')
                    .help("Nickname for this identity")
                    .conflicts_with("no-save"),
            )
            .arg(
                Arg::new("email")
                    .long("email")
                    .short('e')
                    .help("Recovery email for this identity")
                    .conflicts_with("no-email"),
            )
            .arg(
                Arg::new("no-email")
                    .long("no-email")
                    .help("Creates an identity without a recovery email")
                    .conflicts_with("email")
                    .action(ArgAction::SetTrue),
            )
            .arg(
                Arg::new("default")
                    .help("Make the new identity the default for the server")
                    .long("default")
                    .short('d')
                    .conflicts_with("no-save")
                    .action(ArgAction::SetTrue),
            ),
        Command::new("remove")
            .about("Removes a saved identity from your spacetime config")
            .arg(Arg::new("identity")
                .help("The identity string or name to delete")
            )
            .arg(
                Arg::new("all-server")
                    .long("all-server")
                    .short('s')
                    .help("Remove all identities associated with a particular server")
                    .conflicts_with_all(["identity", "all"])
            )
            .arg(
                Arg::new("all")
                    .long("all")
                    .short('a')
                    .help("Remove all identities from your spacetime config")
                    .action(ArgAction::SetTrue)
                    .conflicts_with_all(["identity", "all-server"])
            ).arg(
                Arg::new("force")
                    .long("force")
                    .help("Removes all identities without prompting (for CI usage)")
                    .action(ArgAction::SetTrue)
                    .conflicts_with("identity")
            )
            // TODO: project flag?
            ,
        Command::new("token").about("Print the token for an identity").arg(
            Arg::new("identity")
                .help("The identity string or name that we should print the token for")
                .required(true),
        ),
        Command::new("set-name").about("Set the name of an identity or rename an existing identity nickname").arg(
            Arg::new("identity")
                .help("The identity string or name to be named. If a name is supplied, the corresponding identity will be renamed.")
                .required(true))
            .arg(Arg::new("name")
                .help("The new name for the identity")
                .required(true)
        ),
        Command::new("import")
            .about("Import an existing identity into your spacetime config")
            .arg(
                Arg::new("identity")
                    .required(true)
                    .help("The identity string associated with the provided token"),
            )
            .arg(
                Arg::new("token")
                    .required(true)
                    .help("The identity token to import. This is used for authenticating with SpacetimeDB"),
            )
            .arg(
                Arg::new("name")
                    .long("name")
                    .short('n')
                    .help("A name for the newly imported identity"),
            )
            // TODO: project flag?
            ,
        Command::new("find").about("Find an identity for an email")
            .arg(
                Arg::new("email")
                    .required(true)
                    .help("The email associated with the identity that you would like to find"),
            )
            .arg(
                Arg::new("server")
                    .long("server")
                    .short('s')
                    .help("The server to search for identities matching the email"),
            ),
        Command::new("recover")
            .about("Recover an existing identity and import it into your local config")
            .arg(
                Arg::new("email")
                    .required(true)
                    .help("The email associated with the identity that you would like to recover."),
            )
            .arg(Arg::new("identity").required(true).help(
                "The identity you would like to recover. This identity must be associated with the email provided.",
            ))
            .arg(
                Arg::new("server")
                    .long("server")
                    .short('s')
                    .help("The server from which to request recovery codes"),
            )
            // TODO: project flag?
            ,
    ]
}

pub async fn exec(config: Config, args: &ArgMatches) -> Result<(), anyhow::Error> {
    let (cmd, subcommand_args) = args.subcommand().expect("Subcommand required");
    exec_subcommand(config, cmd, subcommand_args).await
}

async fn exec_subcommand(config: Config, cmd: &str, args: &ArgMatches) -> Result<(), anyhow::Error> {
    match cmd {
        "list" => exec_list(config, args).await,
        "set-default" => exec_set_default(config, args).await,
        "init-default" => exec_init_default(config, args).await,
        "new" => exec_new(config, args).await,
        "remove" => exec_remove(config, args).await,
        "set-name" => exec_set_name(config, args).await,
        "import" => exec_import(config, args).await,
        "set-email" => exec_set_email(config, args).await,
        "find" => exec_find(config, args).await,
        "token" => exec_token(config, args).await,
        "recover" => exec_recover(config, args).await,
        unknown => Err(anyhow::anyhow!("Invalid subcommand: {}", unknown)),
    }
}

/// Executes the `identity set-default` command which sets the default identity.
async fn exec_set_default(mut config: Config, args: &ArgMatches) -> Result<(), anyhow::Error> {
    let identity = config
        .resolve_name_to_identity(args.get_one::<String>("identity").map(|s| s.as_ref()))?
        .unwrap();
    config.set_default_identity(identity, args.get_one::<String>("server").map(|s| s.as_ref()))?;
    config.save();
    Ok(())
}

// TODO(cloutiertyler): Realistically this should just be run before every
//  single command, but I'm separating it out into its own command for now for
//  simplicity.
/// Executes the `identity init-default` command which initializes the default identity.
async fn exec_init_default(mut config: Config, args: &ArgMatches) -> Result<(), anyhow::Error> {
    let nickname = args.get_one::<String>("name").map(|s| s.to_owned());
    let quiet = args.get_flag("quiet");

    let init_default_result = init_default(
        &mut config,
        nickname,
        args.get_one::<String>("server").map(|s| s.as_ref()),
    )
    .await?;
    let identity_config = init_default_result.identity_config;
    let result_type = init_default_result.result_type;

    if !quiet {
        match result_type {
            InitDefaultResultType::Existing => {
                println!(" Existing default identity");
                print_identity_config(&identity_config);
                return Ok(());
            }
            InitDefaultResultType::SavedNew => {
                println!(" Saved new identity");
                print_identity_config(&identity_config);
            }
        }
    }

    Ok(())
}

/// Executes the `identity remove` command which removes an identity from the config.
async fn exec_remove(mut config: Config, args: &ArgMatches) -> Result<(), anyhow::Error> {
    let identity_or_name = args.get_one::<String>("identity");
    let force = args.get_flag("force");
    let all = args.get_flag("all");
    let all_server = args.get_one::<String>("all-server").map(|s| s.as_str());

    if !all && identity_or_name.is_none() && all_server.is_none() {
        return Err(anyhow::anyhow!("Must provide an identity or name to remove"));
    }

    if force && !(all || all_server.is_some()) {
        return Err(anyhow::anyhow!(
            "The --force flag can only be used with --all or --all-server"
        ));
    }

    fn should_continue(force: bool, prompt: &str) -> anyhow::Result<bool> {
        Ok(force || y_or_n(&format!("Are you sure you want to remove all identities{}?", prompt))?)
    }

    if let Some(identity_or_name) = identity_or_name {
        let ic = if is_hex_identity(identity_or_name) {
            config.delete_identity_config_by_identity(identity_or_name.as_str())
        } else {
            config.delete_identity_config_by_name(identity_or_name.as_str())
        }
        .ok_or(anyhow::anyhow!("No such identity or name: {}", identity_or_name))?;
        config.update_all_default_identities();
        println!(" Removed identity");
        print_identity_config(&ic);
    } else if let Some(server) = all_server {
        if !should_continue(force, &format!(" which apply to server {}", server))? {
            println!(" Aborted");
            return Ok(());
        }
        let removed = config.remove_identities_for_server(Some(server))?;
        let count = removed.len();
        println!(
            " {} {} removed:",
            count,
            if count == 1 { "identity" } else { "identities" }
        );
        for identity_config in removed {
            println!("{}", identity_config.identity);
        }
    } else {
        if config.identity_configs().is_empty() {
            println!(" No identities to remove");
            return Ok(());
        }

        if !should_continue(force, "")? {
            println!(" Aborted");
            return Ok(());
        }

        let identity_count = config.identity_configs().len();
        config.delete_all_identity_configs();
        println!(
            " {} {} removed.",
            identity_count,
            if identity_count == 1 { "identity" } else { "identities" }
        );
    }
    config.save();
    Ok(())
}

/// Executes the `identity new` command which creates a new identity.
async fn exec_new(mut config: Config, args: &ArgMatches) -> Result<(), anyhow::Error> {
    let save = !args.get_flag("no-save");
    let alias = args.get_one::<String>("name");
    let server = args.get_one::<String>("server").map(|s| s.as_ref());
    let default = *args.get_one::<bool>("default").unwrap();

    if let Some(alias) = alias {
        if config.name_exists(alias) {
            return Err(anyhow::anyhow!("An identity with that name already exists."));
        }

        if is_hex_identity(alias.as_str()) {
            return Err(anyhow::anyhow!("An identity name cannot be an identity."));
        }
    }

    let email = args.get_one::<String>("email");
    let no_email = args.get_flag("no-email");
    if email.is_none() && !no_email {
        return Err(anyhow::anyhow!(
            "You must either supply an email with --email <email>, or pass the --no-email flag."
        ));
    }

    let mut query_params = Vec::<(&str, &str)>::new();
    if let Some(email) = email {
        if !EmailAddress::is_valid(email.as_str()) {
            return Err(anyhow::anyhow!("The email you provided is malformed: {}", email));
        }
        query_params.push(("email", email.as_str()))
    }

    let mut builder = reqwest::Client::new().post(Url::parse_with_params(
        format!("{}/identity", config.get_host_url(server)?).as_str(),
        query_params,
    )?);

    if let Ok(identity_token) = config.get_default_identity_config(server) {
        builder = builder.basic_auth("token", Some(identity_token.token.clone()));
    }

    let identity_token: IdentityTokenJson = builder.send().await?.error_for_status()?.json().await?;
    let identity = identity_token.identity.clone();

    if save {
        config.identity_configs_mut().push(IdentityConfig {
            identity: identity_token.identity,
            token: identity_token.token,
            nickname: alias.map(|s| s.to_string()),
        });
        if default || config.default_identity(server).is_err() {
            config.set_default_identity(identity.clone(), server)?;
        }

        config.save();
    }

    println!(" IDENTITY     {}", identity);
    println!(" NAME         {}", alias.unwrap_or(&String::new()));
    println!(" EMAIL        {}", email.unwrap_or(&String::new()));

    Ok(())
}

/// Executes the `identity import` command which imports an identity from a token into the config.
async fn exec_import(mut config: Config, args: &ArgMatches) -> Result<(), anyhow::Error> {
    let identity: String = args.get_one::<String>("identity").unwrap().clone();
    let token: String = args.get_one::<String>("token").unwrap().clone();

    //optional
    let nickname = args.get_one::<String>("name").cloned();

    config.identity_configs_mut().push(IdentityConfig {
        identity,
        token,
        nickname: nickname.clone(),
    });

    config.save();

    println!(" New Identity Imported");
    println!(" NAME      {}", nickname.unwrap_or_default());
    // TODO(jdetter): For consistency lets query the database for the user's email and maybe any domain names
    //  associated with this identity.

    Ok(())
}

#[derive(Tabled)]
#[tabled(rename_all = "UPPERCASE")]
struct LsRow {
    default: String,
    identity: String,
    name: String,
    // email: String,
}

/// Executes the `identity list` command which lists all identities in the config.
async fn exec_list(config: Config, args: &ArgMatches) -> Result<(), anyhow::Error> {
    let mut rows: Vec<LsRow> = Vec::new();

    if *args.get_one::<bool>("all").unwrap() {
        for identity_token in config.identity_configs() {
            rows.push(LsRow {
                default: "".to_string(),
                identity: identity_token.identity.clone(),
                name: identity_token.nickname.clone().unwrap_or_default(),
            });
        }
    } else {
        let server = args.get_one::<String>("server").map(|s| s.as_ref());

        let server_name = config.server_nick_or_host(server)?;
        let decoding_key = config.server_decoding_key(server).with_context(|| {
            format!(
                "Cannot list identities for server without a saved fingerprint: {server_name}
Fetch the server's fingerprint with:
\tspacetime server fingerprint {server_name}"
            )
        })?;
        let default_identity = config.default_identity(server);

        let is_default = |id| {
            if let Ok(default_identity) = default_identity {
                id == default_identity
            } else {
                false
            }
        };

        for identity_token in config.identity_configs() {
            if decode_token(&decoding_key, &identity_token.token).is_ok() {
                rows.push(LsRow {
                    default: if is_default(&identity_token.identity) {
                        "***"
                    } else {
                        ""
                    }
                    .to_string(),
                    identity: identity_token.identity.clone(),
                    name: identity_token.nickname.clone().unwrap_or_default(),
                    // TODO(jdetter): We'll have to look this up via a query
                    // email: identity_token.email.unwrap_or_default(),
                });
            }
        }
        println!("Identities for {}:", config.server_nick_or_host(server)?);
    }

    let table = Table::new(&rows)
        .with(Style::empty())
        .with(Modify::new(Columns::first()).with(Alignment::right()));
    println!("{}", table);
    Ok(())
}

#[derive(Debug, Clone, Deserialize)]
struct GetIdentityResponse {
    identities: Vec<GetIdentityResponseEntry>,
}

#[derive(Debug, Clone, Deserialize)]
struct GetIdentityResponseEntry {
    identity: String,
    email: String,
}

/// Executes the `identity find` command which finds an identity by email.
async fn exec_find(config: Config, args: &ArgMatches) -> Result<(), anyhow::Error> {
    let email = args.get_one::<String>("email").unwrap().clone();
    let server = args.get_one::<String>("server").map(|s| s.as_ref());
    let client = reqwest::Client::new();
    let builder = client.get(format!("{}/identity?email={}", config.get_host_url(server)?, email));

    let res = builder.send().await?;

    if res.status() == StatusCode::OK {
        let response: GetIdentityResponse = res.json().await?;
        if response.identities.is_empty() {
            return Err(anyhow::anyhow!("Could not find identity for: {}", email));
        }

        for identity in response.identities {
            println!("Identity");
            println!(" IDENTITY  {}", identity.identity);
            println!(" EMAIL     {}", identity.email);
        }
        Ok(())
    } else if res.status() == StatusCode::NOT_FOUND {
        Err(anyhow::anyhow!("Could not find identity for: {}", email))
    } else {
        Err(anyhow::anyhow!("Error occurred in lookup: {}", res.status()))
    }
}

/// Executes the `identity token` command which prints the token for an identity.
async fn exec_token(config: Config, args: &ArgMatches) -> Result<(), anyhow::Error> {
    let identity_or_name = config
        .resolve_name_to_identity(args.get_one::<String>("identity").map(|s| s.as_str()))?
        .unwrap();
    let ic = config
        .get_identity_config_by_identity(identity_or_name.as_str())
        .unwrap();
    println!("{}", ic.token);
    Ok(())
}

/// Executes the `identity set-default` command which sets the default identity.
async fn exec_set_name(mut config: Config, args: &ArgMatches) -> Result<(), anyhow::Error> {
    let cloned_config = config.clone();
    let identity_or_name = cloned_config
        .resolve_name_to_identity(args.get_one::<String>("identity").map(|s| s.as_ref()))?
        .unwrap();
    let new_name = args.get_one::<String>("name").unwrap().as_ref();
    let old_nickname = config.set_identity_nickname(identity_or_name.as_ref(), new_name)?;
    if let Some(old_nickname) = old_nickname {
        println!("Updated identity: {}", identity_or_name);
        println!(" OLD NAME: {}", old_nickname);
        println!(" NEW NAME: {}", new_name);
    } else {
        println!("Created identity: {}", identity_or_name);
        println!(" NAME: {}", new_name);
    }
    config.save();
    let ic = config
        .get_identity_config_by_identity(identity_or_name.as_ref())
        .unwrap();
    print_identity_config(ic);
    Ok(())
}

/// Executes the `identity set-email` command which sets the email for an identity.
async fn exec_set_email(config: Config, args: &ArgMatches) -> Result<(), anyhow::Error> {
    let email = args.get_one::<String>("email").unwrap().clone();
    let server = args.get_one::<String>("server").map(|s| s.as_ref());
    let identity = config
        .resolve_name_to_identity(args.get_one::<String>("identity").map(|s| s.as_ref()))?
        .unwrap();
    let identity_config = config
        .get_identity_config_by_identity(identity.as_str())
        .unwrap_or_else(|| panic!("Could not find identity: {}", identity));

    // TODO: check that the identity is valid for the server

    let mut builder = reqwest::Client::new().post(format!(
        "{}/identity/{}/set-email?email={}",
        config.get_host_url(server)?,
        identity_config.identity,
        email
    ));

    if let Some(identity_token) = config.get_identity_config_by_identity(identity.as_str()) {
        builder = builder.basic_auth("token", Some(identity_token.token.clone()));
    } else {
        println!("Missing identity credentials for identity.");
        std::process::exit(0);
    }

    builder.send().await?.error_for_status()?;

    println!(" Associated email with identity");
    print_identity_config(config.get_identity_config_by_identity(identity.as_str()).unwrap());
    println!(" EMAIL {}", email);

    Ok(())
}

/// Executes the `identity recover` command which recovers an identity from an email.
async fn exec_recover(mut config: Config, args: &ArgMatches) -> Result<(), anyhow::Error> {
    let email = args.get_one::<String>("email").unwrap();
    let server = args.get_one::<String>("server").map(|s| s.as_ref());
    let identity = config
        .resolve_name_to_identity(args.get_one::<String>("identity").map(|s| s.as_str()))?
        .unwrap();

    let query_params = vec![
        ("email", email.as_str()),
        ("identity", identity.as_str()),
        ("link", "false"),
    ];

    if config
        .identity_configs()
        .iter()
        .any(|a| a.identity.to_lowercase() == identity.to_lowercase())
    {
        return Err(anyhow::anyhow!("No need to recover this identity, it is already stored in your config. Use `spacetime identity list` to list identities."));
    }

    let client = reqwest::Client::new();
    let builder = client.get(Url::parse_with_params(
        format!("{}/database/request_recovery_code", config.get_host_url(server)?,).as_str(),
        query_params,
    )?);
    let res = builder.send().await?;
    res.error_for_status()?;

    println!(
        "We have successfully sent a recovery code to {}. Enter the code now.",
        email
    );
    for _ in 0..5 {
        print!("Recovery Code: ");
        std::io::stdout().flush()?;
        let mut line = String::new();
        std::io::stdin().read_line(&mut line).unwrap();
        let code = match line.trim().parse::<u32>() {
            Ok(value) => value,
            Err(_) => {
                println!("Malformed code. Please try again.");
                continue;
            }
        };

        let client = reqwest::Client::new();
        let builder = client.get(Url::parse_with_params(
            format!("{}/database/confirm_recovery_code", config.get_host_url(server)?,).as_str(),
            vec![
                ("code", code.to_string().as_str()),
                ("email", email.as_str()),
                ("identity", identity.as_str()),
            ],
        )?);
        let res = builder.send().await?;
        match res.error_for_status() {
            Ok(res) => {
                let buf = res.bytes().await?.to_vec();
                let utf8 = String::from_utf8(buf)?;
                let response: RecoveryCodeResponse = serde_json::from_str(utf8.as_str())?;
                let identity_config = IdentityConfig {
                    nickname: None,
                    identity: response.identity.clone(),
                    token: response.token,
                };
                config.identity_configs_mut().push(identity_config.clone());
                config.set_default_identity_if_unset(server, &identity_config.identity)?;
                config.save();
                println!("Success. Identity imported.");
                print_identity_config(&identity_config);
                // TODO: Remove this once print_identity_config prints email
                println!(" EMAIL     {}", email);
                return Ok(());
            }
            Err(_) => {
                println!("Invalid recovery code, please try again.");
            }
        }
    }

    Err(anyhow::anyhow!(
        "Maximum amount of attempts reached. Please start the process over."
    ))
}