bitbucket_cli/auth/
mod.rs1pub mod api_key;
2pub mod credential_store;
3pub mod file_store;
4pub mod keyring_store;
5pub mod oauth;
6
7use anyhow::Result;
8use base64::Engine;
9use serde::{Deserialize, Serialize};
10
11pub use api_key::*;
12pub use credential_store::*;
13pub use file_store::*;
14pub use keyring_store::*;
15pub use oauth::*;
16
17#[derive(Debug, Clone, Serialize, Deserialize)]
19pub enum Credential {
20 OAuth {
22 access_token: String,
23 refresh_token: Option<String>,
24 expires_at: Option<i64>,
25 #[serde(default, skip_serializing_if = "Option::is_none")]
26 client_id: Option<String>,
27 #[serde(default, skip_serializing_if = "Option::is_none")]
28 client_secret: Option<String>,
29 },
30 ApiKey { username: String, api_key: String },
32}
33
34impl Credential {
35 #[inline]
37 pub fn auth_header(&self) -> String {
38 match self {
39 Credential::OAuth { access_token, .. } => {
40 let mut result = String::with_capacity(7 + access_token.len());
41 result.push_str("Bearer ");
42 result.push_str(access_token);
43 result
44 }
45 Credential::ApiKey { username, api_key } => {
46 let basic = format!("{}:{}", username, api_key);
47 let encoded = base64::engine::general_purpose::STANDARD.encode(basic.as_bytes());
48 let mut result = String::with_capacity(6 + encoded.len());
49 result.push_str("Basic ");
50 result.push_str(&encoded);
51 result
52 }
53 }
54 }
55
56 #[inline]
58 pub fn type_name(&self) -> &'static str {
59 match self {
60 Credential::OAuth { .. } => "OAuth 2.0",
61 Credential::ApiKey { .. } => "API Key",
62 }
63 }
64
65 #[inline]
67 pub fn needs_refresh(&self) -> bool {
68 match self {
69 Credential::OAuth {
70 expires_at: Some(expires),
71 ..
72 } => {
73 *expires < chrono::Utc::now().timestamp() + 300
75 }
76 _ => false,
77 }
78 }
79
80 pub fn oauth_consumer_credentials(&self) -> Option<(&str, &str)> {
82 match self {
83 Credential::OAuth {
84 client_id: Some(id),
85 client_secret: Some(secret),
86 ..
87 } => Some((id, secret)),
88 _ => None,
89 }
90 }
91
92 pub fn username(&self) -> Option<&str> {
94 match self {
95 Credential::ApiKey { username, .. } => Some(username),
96 _ => None,
97 }
98 }
99}
100
101pub struct AuthManager {
103 store: CredentialStore,
104}
105
106impl AuthManager {
107 pub fn new() -> Result<Self> {
108 Ok(Self {
109 store: CredentialStore::new()?,
110 })
111 }
112
113 pub fn get_credentials(&self) -> Result<Option<Credential>> {
115 self.store.get_credential()
116 }
117
118 pub fn store_credentials(&self, credential: &Credential) -> Result<()> {
120 self.store.store_credential(credential)
121 }
122
123 pub fn clear_credentials(&self) -> Result<()> {
125 self.store.delete_credential()
126 }
127
128 pub fn is_authenticated(&self) -> bool {
130 self.get_credentials().map(|c| c.is_some()).unwrap_or(false)
131 }
132}
133
134impl Default for AuthManager {
135 fn default() -> Self {
136 Self::new().expect("Failed to create auth manager")
137 }
138}