Skip to main content

auths_cli/commands/
whoami.rs

1use anyhow::{Result, anyhow};
2use auths_sdk::ports::IdentityStorage;
3use auths_sdk::storage::RegistryIdentityStorage;
4use auths_sdk::storage_layout as layout;
5use clap::Parser;
6use serde::Serialize;
7
8use crate::config::CliConfig;
9use crate::ux::format::{JsonResponse, Output, is_json_mode};
10
11/// Show the current identity on this machine.
12#[derive(Parser, Debug, Clone)]
13#[command(
14    name = "whoami",
15    about = "Show the current identity on this machine",
16    after_help = "Examples:
17  auths whoami              # Show the current identity
18  auths whoami --json       # JSON output
19
20Related:
21  auths status  — Show full identity and device status
22  auths init    — Initialize a new identity"
23)]
24pub struct WhoamiCommand {}
25
26#[derive(Debug, Serialize)]
27struct WhoamiResponse {
28    identity_did: String,
29    #[serde(skip_serializing_if = "Option::is_none")]
30    label: Option<String>,
31}
32
33pub fn handle_whoami(_cmd: WhoamiCommand, repo: Option<std::path::PathBuf>) -> Result<()> {
34    let repo_path = layout::resolve_repo_path(repo).map_err(|e| anyhow!(e))?;
35
36    if crate::factories::storage::open_git_repo(&repo_path).is_err() {
37        if is_json_mode() {
38            JsonResponse::<()>::error(
39                "whoami",
40                "No identity found. Run `auths init` to get started.",
41            )
42            .print()?;
43        } else {
44            let out = Output::new();
45            out.print_error("No identity found. Run `auths init` to get started.");
46        }
47        return Ok(());
48    }
49
50    let storage = RegistryIdentityStorage::new(&repo_path);
51    match storage.load_identity() {
52        Ok(identity) => {
53            let response = WhoamiResponse {
54                identity_did: identity.controller_did.to_string(),
55                label: None,
56            };
57
58            if is_json_mode() {
59                JsonResponse::success("whoami", &response).print()?;
60            } else {
61                let out = Output::new();
62                out.println(&format!("Identity: {}", out.info(&response.identity_did)));
63            }
64        }
65        Err(_) => {
66            if is_json_mode() {
67                JsonResponse::<()>::error(
68                    "whoami",
69                    "No identity found. Run `auths init` to get started.",
70                )
71                .print()?;
72            } else {
73                let out = Output::new();
74                out.print_error("No identity found. Run `auths init` to get started.");
75            }
76        }
77    }
78
79    Ok(())
80}
81
82impl crate::commands::executable::ExecutableCommand for WhoamiCommand {
83    fn execute(&self, ctx: &CliConfig) -> Result<()> {
84        handle_whoami(self.clone(), ctx.repo_path.clone())
85    }
86}