Skip to main content

bitbucket_cli/cli/
auth.rs

1use anyhow::Result;
2use clap::Subcommand;
3use colored::Colorize;
4use dialoguer::Input;
5
6use crate::auth::{ApiKeyAuth, AuthManager, OAuthFlow};
7use crate::config::Config;
8
9#[derive(Subcommand)]
10pub enum AuthCommands {
11    /// Authenticate with Bitbucket (OAuth 2.0 or API key)
12    Login {
13        /// Use API key authentication (for automation/CI)
14        #[arg(long)]
15        api_key: bool,
16
17        /// OAuth Client ID (for OAuth authentication)
18        #[arg(long, env = "BITBUCKET_CLIENT_ID")]
19        client_id: Option<String>,
20
21        /// OAuth Client Secret (for OAuth authentication)
22        #[arg(long, env = "BITBUCKET_CLIENT_SECRET")]
23        client_secret: Option<String>,
24    },
25
26    /// Remove stored credentials
27    Logout,
28
29    /// Show authentication status
30    Status,
31}
32
33impl AuthCommands {
34    pub async fn run(self) -> Result<()> {
35        match self {
36            AuthCommands::Login {
37                api_key,
38                client_id,
39                client_secret,
40            } => {
41                let auth_manager = AuthManager::new()?;
42
43                // If --api-key flag is set, use API key authentication
44                if api_key {
45                    ApiKeyAuth::authenticate(&auth_manager).await?;
46                    return Ok(());
47                }
48
49                // Otherwise, use OAuth 2.0 authentication
50                // Resolve consumer credentials from (in priority):
51                // 1. CLI flags / env vars
52                // 2. Previously stored credentials
53                // 3. Interactive prompt (first-time only)
54                let stored_consumer = auth_manager.get_credentials().ok().flatten().and_then(|c| {
55                    c.oauth_consumer_credentials()
56                        .map(|(id, secret)| (id.to_owned(), secret.to_owned()))
57                });
58
59                let client_id = client_id
60                    .or_else(|| stored_consumer.as_ref().map(|(id, _)| id.clone()))
61                    .or_else(|| {
62                        println!();
63                        println!("📋 OAuth Consumer Setup Required");
64                        println!();
65                        println!("To use OAuth authentication, create an OAuth consumer in Bitbucket:");
66                        println!("1. Go to: https://bitbucket.org/[workspace]/workspace/settings/oauth-consumers/new");
67                        println!("2. Set callback URL to ONE of these (pick any available port):");
68                        println!("   • http://127.0.0.1:8080/callback");
69                        println!("   • http://127.0.0.1:3000/callback");
70                        println!("   • http://127.0.0.1:8888/callback");
71                        println!("   • http://127.0.0.1:9000/callback");
72                        println!("3. Select required permissions:");
73                        println!("   ✓ Account (Read)");
74                        println!("   ✓ Repositories (Read)");
75                        println!("   ✓ Pull requests (Read, Write)");
76                        println!("   ✓ Issues (Read, Write)");
77                        println!("   ✓ Pipelines (Read, Write)");
78                        println!("4. Copy the Key (Client ID) and Secret");
79                        println!();
80
81                        Input::<String>::new()
82                            .with_prompt("OAuth Client ID (Key)")
83                            .interact_text()
84                            .ok()
85                    })
86                    .ok_or_else(|| anyhow::anyhow!("OAuth Client ID is required"))?;
87
88                let client_secret = client_secret
89                    .or_else(|| stored_consumer.map(|(_, secret)| secret))
90                    .or_else(|| {
91                        Input::<String>::new()
92                            .with_prompt("OAuth Client Secret")
93                            .interact_text()
94                            .ok()
95                    })
96                    .ok_or_else(|| anyhow::anyhow!("OAuth Client Secret is required"))?;
97
98                let oauth = OAuthFlow::new(client_id, client_secret);
99                oauth.authenticate(&auth_manager).await?;
100
101                Ok(())
102            }
103
104            AuthCommands::Logout => {
105                let auth_manager = AuthManager::new()?;
106                auth_manager.clear_credentials()?;
107
108                let mut config = Config::load()?;
109                config.clear_auth();
110                config.save()?;
111
112                println!("{} Logged out successfully", "✓".green());
113                Ok(())
114            }
115
116            AuthCommands::Status => {
117                let auth_manager = AuthManager::new()?;
118                let config = Config::load()?;
119
120                if auth_manager.is_authenticated() {
121                    println!("{} Authenticated", "✓".green());
122
123                    if let Ok(Some(credential)) = auth_manager.get_credentials() {
124                        println!("  {} {}", "Method:".dimmed(), credential.type_name());
125
126                        // Show username from credential for API keys, or config for OAuth
127                        if let Some(username) = credential.username() {
128                            println!("  {} {}", "Username:".dimmed(), username);
129                        } else if let Some(username) = config.username() {
130                            println!("  {} {}", "Username:".dimmed(), username);
131                        }
132
133                        if credential.needs_refresh() {
134                            println!(
135                                "  {} {}",
136                                "Status:".dimmed(),
137                                "Token needs refresh (will auto-refresh on next use)".yellow()
138                            );
139                        }
140                    }
141
142                    if let Some(workspace) = config.default_workspace() {
143                        println!("  {} {}", "Workspace:".dimmed(), workspace);
144                    }
145
146                    match crate::api::BitbucketClient::from_stored().await {
147                        Ok(client) => match client.get::<serde_json::Value>("/user").await {
148                            Ok(user) => {
149                                if let Some(display_name) = user.get("display_name") {
150                                    println!(
151                                        "  {} {}",
152                                        "Display name:".dimmed(),
153                                        display_name.as_str().unwrap_or("Unknown")
154                                    );
155                                }
156                            }
157                            Err(e) => {
158                                println!("{} Credentials may be invalid: {}", "âš ".yellow(), e);
159                            }
160                        },
161                        Err(e) => {
162                            println!("{} Failed to create client: {}", "✗".red(), e);
163                        }
164                    }
165                } else {
166                    println!("{} Not authenticated", "✗".red());
167                    println!();
168                    println!("Run {} to authenticate", "bitbucket auth login".cyan());
169                }
170
171                Ok(())
172            }
173        }
174    }
175}