1impl Default for ProviderProfile {
3 fn default() -> Self {
4 Self::new()
5 }
6}
7use crate::errors::{AuthError, Result};
8use crate::tokens::AuthToken;
9use base64::Engine;
10use reqwest::Client;
11use serde::{Deserialize, Serialize};
12use serde_json::Value;
13use std::collections::HashMap;
14use std::fmt;
15use url::Url;
16
17#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
19pub enum OAuthProvider {
20 GitHub,
22
23 Google,
25
26 Microsoft,
28
29 Discord,
31
32 Twitter,
34
35 Facebook,
37
38 LinkedIn,
40
41 GitLab,
43
44 Custom {
46 name: String,
47 config: Box<OAuthProviderConfig>,
48 },
49}
50
51#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
53pub struct OAuthProviderConfig {
54 pub authorization_url: String,
56
57 pub token_url: String,
59
60 pub device_authorization_url: Option<String>,
62
63 pub userinfo_url: Option<String>,
65
66 pub revocation_url: Option<String>,
68
69 pub default_scopes: crate::types::Scopes,
71
72 pub supports_pkce: bool,
74
75 pub supports_refresh: bool,
77
78 pub supports_device_flow: bool,
80
81 pub additional_params: crate::types::AdditionalParams,
83}
84
85impl OAuthProviderConfig {
86 pub fn builder(
105 authorization_url: impl Into<String>,
106 token_url: impl Into<String>,
107 ) -> OAuthProviderConfigBuilder {
108 OAuthProviderConfigBuilder {
109 inner: OAuthProviderConfig {
110 authorization_url: authorization_url.into(),
111 token_url: token_url.into(),
112 device_authorization_url: None,
113 userinfo_url: None,
114 revocation_url: None,
115 default_scopes: crate::types::Scopes::empty(),
116 supports_pkce: false,
117 supports_refresh: false,
118 supports_device_flow: false,
119 additional_params: crate::types::AdditionalParams::new(),
120 },
121 }
122 }
123}
124
125#[derive(Debug, Clone)]
127pub struct OAuthProviderConfigBuilder {
128 inner: OAuthProviderConfig,
129}
130
131impl OAuthProviderConfigBuilder {
132 pub fn device_authorization_url(mut self, url: impl Into<String>) -> Self {
134 self.inner.device_authorization_url = Some(url.into());
135 self
136 }
137
138 pub fn userinfo_url(mut self, url: impl Into<String>) -> Self {
140 self.inner.userinfo_url = Some(url.into());
141 self
142 }
143
144 pub fn revocation_url(mut self, url: impl Into<String>) -> Self {
146 self.inner.revocation_url = Some(url.into());
147 self
148 }
149
150 pub fn default_scope(mut self, scope: impl Into<String>) -> Self {
152 self.inner.default_scopes.push(scope.into());
153 self
154 }
155
156 pub fn supports_pkce(mut self, yes: bool) -> Self {
158 self.inner.supports_pkce = yes;
159 self
160 }
161
162 pub fn supports_refresh(mut self, yes: bool) -> Self {
164 self.inner.supports_refresh = yes;
165 self
166 }
167
168 pub fn supports_device_flow(mut self, yes: bool) -> Self {
170 self.inner.supports_device_flow = yes;
171 self
172 }
173
174 pub fn param(mut self, key: impl Into<String>, value: impl Into<String>) -> Self {
176 self.inner
177 .additional_params
178 .insert(key.into(), value.into());
179 self
180 }
181
182 pub fn build(self) -> OAuthProviderConfig {
184 self.inner
185 }
186}
187
188#[derive(Clone, Serialize, Deserialize)]
190pub struct DeviceAuthorizationResponse {
191 pub device_code: String,
193
194 pub user_code: String,
196
197 pub verification_uri: String,
199
200 pub verification_uri_complete: Option<String>,
202
203 pub interval: u64,
205
206 pub expires_in: u64,
208}
209
210impl std::fmt::Debug for DeviceAuthorizationResponse {
211 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
212 let mut d = f.debug_struct("DeviceAuthorizationResponse");
213 d.field(
214 "device_code",
215 &crate::utils::redact::redacted(&self.device_code),
216 );
217 d.field("user_code", &self.user_code);
218 d.field("verification_uri", &self.verification_uri);
219 d.field("verification_uri_complete", &self.verification_uri_complete);
220 d.field("interval", &self.interval);
221 d.field("expires_in", &self.expires_in);
222 d.finish()
223 }
224}
225
226#[derive(Debug, Clone, Serialize, Deserialize)]
232pub struct ProviderProfile {
233 pub id: Option<String>,
235
236 pub provider: Option<String>,
238
239 pub username: Option<String>,
241
242 pub name: Option<String>,
244
245 pub email: Option<String>,
247
248 pub email_verified: Option<bool>,
250
251 pub picture: Option<String>,
253
254 pub locale: Option<String>,
256
257 pub additional_data: HashMap<String, serde_json::Value>,
259}
260
261#[cfg(feature = "postgres-storage")]
262use sqlx::{Decode, Postgres, Type, postgres::PgValueRef};
263
264#[cfg(feature = "postgres-storage")]
265impl<'r> Decode<'r, Postgres> for ProviderProfile {
266 fn decode(value: PgValueRef<'r>) -> std::result::Result<Self, sqlx::error::BoxDynError> {
267 let json: serde_json::Value = <serde_json::Value as Decode<Postgres>>::decode(value)?;
268 serde_json::from_value(json).map_err(|e| Box::new(e) as sqlx::error::BoxDynError)
269 }
270}
271
272#[cfg(feature = "postgres-storage")]
273impl Type<Postgres> for ProviderProfile {
274 fn type_info() -> sqlx::postgres::PgTypeInfo {
275 <serde_json::Value as Type<Postgres>>::type_info()
276 }
277 fn compatible(ty: &sqlx::postgres::PgTypeInfo) -> bool {
278 <serde_json::Value as Type<Postgres>>::compatible(ty)
279 }
280}
281
282impl ProviderProfile {
283 pub fn new() -> Self {
285 Self {
286 id: None,
287 provider: None,
288 username: None,
289 name: None,
290 email: None,
291 email_verified: None,
292 picture: None,
293 locale: None,
294 additional_data: HashMap::new(),
295 }
296 }
297
298 pub fn with_id(mut self, id: impl Into<String>) -> Self {
300 self.id = Some(id.into());
301 self
302 }
303
304 pub fn with_provider(mut self, provider: impl Into<String>) -> Self {
306 self.provider = Some(provider.into());
307 self
308 }
309
310 pub fn with_username(mut self, username: Option<impl Into<String>>) -> Self {
312 self.username = username.map(Into::into);
313 self
314 }
315
316 pub fn with_name(mut self, name: Option<impl Into<String>>) -> Self {
318 self.name = name.map(Into::into);
319 self
320 }
321
322 pub fn with_email(mut self, email: Option<impl Into<String>>) -> Self {
324 self.email = email.map(Into::into);
325 self
326 }
327
328 pub fn with_email_verified(mut self, verified: bool) -> Self {
330 self.email_verified = Some(verified);
331 self
332 }
333
334 pub fn with_picture(mut self, picture: Option<impl Into<String>>) -> Self {
336 self.picture = picture.map(Into::into);
337 self
338 }
339
340 pub fn with_locale(mut self, locale: Option<impl Into<String>>) -> Self {
342 self.locale = locale.map(Into::into);
343 self
344 }
345
346 pub fn with_additional_data(
348 mut self,
349 key: impl Into<String>,
350 value: serde_json::Value,
351 ) -> Self {
352 self.additional_data.insert(key.into(), value);
353 self
354 }
355
356 pub fn from_token_response(
358 token: &OAuthTokenResponse,
359 provider: &OAuthProvider,
360 ) -> Option<Self> {
361 if let Some(id_token_value) = token.additional_fields.get("id_token")
363 && let Some(id_token) = id_token_value.as_str()
364 && let Ok(profile) = Self::from_id_token(id_token)
365 {
366 return Some(profile.with_provider(provider.to_string()));
367 }
368 None
369 }
370
371 pub fn from_id_token(id_token: &str) -> Result<Self> {
373 let parts: Vec<&str> = id_token.split('.').collect();
375 if parts.len() != 3 {
376 return Err(AuthError::validation("Invalid JWT format"));
377 }
378
379 let payload = parts[1];
381 let padding_len = payload.len() % 4;
382 let padded_payload = if padding_len > 0 {
383 format!("{}{}", payload, "=".repeat(4 - padding_len))
384 } else {
385 payload.to_string()
386 };
387
388 let decoded = base64::engine::general_purpose::URL_SAFE_NO_PAD
390 .decode(&padded_payload)
391 .map_err(|e| AuthError::validation(format!("Failed to decode JWT: {}", e)))?;
392
393 let json: Value = serde_json::from_slice(&decoded)
395 .map_err(|e| AuthError::validation(format!("Failed to parse JWT payload: {}", e)))?;
396
397 let mut profile = Self::new();
399
400 if let Some(sub) = json.get("sub").and_then(|v| v.as_str()) {
402 profile = profile.with_id(sub);
403 } else if let Some(id) = json.get("id").and_then(|v| v.as_str()) {
404 profile = profile.with_id(id);
405 } else {
406 return Err(AuthError::validation("JWT missing subject claim"));
407 }
408
409 if let Some(name) = json.get("name").and_then(|v| v.as_str()) {
411 profile = profile.with_name(Some(name));
412 }
413
414 if let Some(email) = json.get("email").and_then(|v| v.as_str()) {
415 profile = profile.with_email(Some(email));
416 }
417
418 if let Some(verified) = json.get("email_verified").and_then(|v| v.as_bool()) {
419 profile = profile.with_email_verified(verified);
420 }
421
422 if let Some(preferred_username) = json.get("preferred_username").and_then(|v| v.as_str()) {
423 profile = profile.with_username(Some(preferred_username));
424 }
425
426 if let Some(picture) = json.get("picture").and_then(|v| v.as_str()) {
427 profile = profile.with_picture(Some(picture));
428 }
429
430 if let Some(locale) = json.get("locale").and_then(|v| v.as_str()) {
431 profile = profile.with_locale(Some(locale));
432 }
433
434 profile = profile.with_additional_data("id_token_claims", json);
436
437 Ok(profile)
438 }
439
440 pub fn to_auth_token(&self, access_token: String) -> AuthToken {
443 self.to_auth_token_with_lifetime(access_token, std::time::Duration::from_secs(3600))
444 }
445
446 pub fn to_auth_token_with_lifetime(
448 &self,
449 access_token: String,
450 lifetime: std::time::Duration,
451 ) -> AuthToken {
452 let user_id = self.id.as_deref().unwrap_or("unknown").to_string();
453 let auth_method = self.provider.as_deref().unwrap_or("oauth").to_string();
454
455 let mut token = AuthToken::new(user_id.clone(), access_token, lifetime, auth_method);
456 token.subject = self.id.clone();
457 token.issuer = self.provider.clone();
458 token.user_profile = Some(self.clone());
459 token
460 }
461
462 pub fn has_id(&self) -> bool {
464 self.id.is_some()
465 }
466
467 pub fn display_name(&self) -> Option<&str> {
469 self.name.as_deref().or(self.username.as_deref())
470 }
471}
472
473#[derive(Clone, Serialize, Deserialize)]
475pub struct OAuthTokenResponse {
476 pub access_token: String,
478
479 pub token_type: String,
481
482 pub expires_in: Option<u64>,
484
485 pub refresh_token: Option<String>,
487
488 pub scope: Option<String>,
490
491 #[serde(flatten)]
493 pub additional_fields: HashMap<String, serde_json::Value>,
494}
495
496impl std::fmt::Debug for OAuthTokenResponse {
497 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
498 let mut d = f.debug_struct("OAuthTokenResponse");
499 d.field(
500 "access_token",
501 &crate::utils::redact::redacted(&self.access_token),
502 );
503 d.field("token_type", &self.token_type);
504 d.field("expires_in", &self.expires_in);
505 d.field(
506 "refresh_token",
507 &crate::utils::redact::redacted(&self.refresh_token),
508 );
509 d.field("scope", &self.scope);
510 d.field("additional_fields", &self.additional_fields);
511 d.finish()
512 }
513}
514
515#[derive(Debug, Clone, Serialize, Deserialize)]
517pub struct OAuthUserInfo {
518 pub id: String,
520
521 pub username: Option<String>,
523
524 pub name: Option<String>,
526
527 pub email: Option<String>,
529
530 pub email_verified: Option<bool>,
532
533 pub picture: Option<String>,
535
536 pub locale: Option<String>,
538
539 #[serde(flatten)]
541 pub additional_fields: HashMap<String, serde_json::Value>,
542}
543
544impl OAuthProvider {
545 pub fn config(&self) -> OAuthProviderConfig {
547 match self {
548 Self::GitHub => OAuthProviderConfig {
549 authorization_url: "https://github.com/login/oauth/authorize".to_string(),
550 token_url: "https://github.com/login/oauth/access_token".to_string(),
551 device_authorization_url: Some("https://github.com/login/device/code".to_string()),
552 userinfo_url: Some("https://api.github.com/user".to_string()),
553 revocation_url: None,
554 default_scopes: vec!["user:email".to_string()].into(),
555 supports_pkce: true,
556 supports_refresh: false,
557 supports_device_flow: true,
558 additional_params: crate::types::AdditionalParams::new(),
559 },
560
561 Self::Google => OAuthProviderConfig {
562 authorization_url: "https://accounts.google.com/o/oauth2/v2/auth".to_string(),
563 token_url: "https://oauth2.googleapis.com/token".to_string(),
564 device_authorization_url: Some(
565 "https://oauth2.googleapis.com/device/code".to_string(),
566 ),
567 userinfo_url: Some("https://www.googleapis.com/oauth2/v2/userinfo".to_string()),
568 revocation_url: Some("https://oauth2.googleapis.com/revoke".to_string()),
569 default_scopes: vec![
570 "openid".to_string(),
571 "profile".to_string(),
572 "email".to_string(),
573 ]
574 .into(),
575 supports_pkce: true,
576 supports_refresh: true,
577 supports_device_flow: true,
578 additional_params: crate::types::AdditionalParams::new(),
579 },
580
581 Self::Microsoft => OAuthProviderConfig {
582 authorization_url: "https://login.microsoftonline.com/common/oauth2/v2.0/authorize"
583 .to_string(),
584 token_url: "https://login.microsoftonline.com/common/oauth2/v2.0/token".to_string(),
585 device_authorization_url: Some(
586 "https://login.microsoftonline.com/common/oauth2/v2.0/devicecode".to_string(),
587 ),
588 userinfo_url: Some("https://graph.microsoft.com/v1.0/me".to_string()),
589 revocation_url: None,
590 default_scopes: vec![
591 "openid".to_string(),
592 "profile".to_string(),
593 "email".to_string(),
594 ]
595 .into(),
596 supports_pkce: true,
597 supports_refresh: true,
598 supports_device_flow: true,
599 additional_params: crate::types::AdditionalParams::new(),
600 },
601
602 Self::Discord => OAuthProviderConfig {
603 authorization_url: "https://discord.com/api/oauth2/authorize".to_string(),
604 token_url: "https://discord.com/api/oauth2/token".to_string(),
605 device_authorization_url: None,
606 userinfo_url: Some("https://discord.com/api/users/@me".to_string()),
607 revocation_url: Some("https://discord.com/api/oauth2/token/revoke".to_string()),
608 default_scopes: vec!["identify".to_string(), "email".to_string()].into(),
609 supports_pkce: false,
610 supports_refresh: true,
611 supports_device_flow: false,
612 additional_params: crate::types::AdditionalParams::new(),
613 },
614
615 Self::Twitter => OAuthProviderConfig {
616 authorization_url: "https://twitter.com/i/oauth2/authorize".to_string(),
617 token_url: "https://api.twitter.com/2/oauth2/token".to_string(),
618 device_authorization_url: None,
619 userinfo_url: Some("https://api.twitter.com/2/users/me".to_string()),
620 revocation_url: Some("https://api.twitter.com/2/oauth2/revoke".to_string()),
621 default_scopes: vec!["tweet.read".to_string(), "users.read".to_string()].into(),
622 supports_pkce: true,
623 supports_refresh: true,
624 supports_device_flow: false,
625 additional_params: crate::types::AdditionalParams::new(),
626 },
627
628 Self::Facebook => OAuthProviderConfig {
629 authorization_url: "https://www.facebook.com/v18.0/dialog/oauth".to_string(),
630 token_url: "https://graph.facebook.com/v18.0/oauth/access_token".to_string(),
631 device_authorization_url: None,
632 userinfo_url: Some("https://graph.facebook.com/me".to_string()),
633 revocation_url: None,
634 default_scopes: vec!["email".to_string(), "public_profile".to_string()].into(),
635 supports_pkce: false,
636 supports_refresh: false,
637 supports_device_flow: false,
638 additional_params: crate::types::AdditionalParams::new(),
639 },
640
641 Self::LinkedIn => OAuthProviderConfig {
642 authorization_url: "https://www.linkedin.com/oauth/v2/authorization".to_string(),
643 token_url: "https://www.linkedin.com/oauth/v2/accessToken".to_string(),
644 device_authorization_url: None,
645 userinfo_url: Some("https://api.linkedin.com/v2/me".to_string()),
646 revocation_url: None,
647 default_scopes: vec!["r_liteprofile".to_string(), "r_emailaddress".to_string()]
648 .into(),
649 supports_pkce: false,
650 supports_refresh: true,
651 supports_device_flow: false,
652 additional_params: crate::types::AdditionalParams::new(),
653 },
654
655 Self::GitLab => OAuthProviderConfig {
656 authorization_url: "https://gitlab.com/oauth/authorize".to_string(),
657 token_url: "https://gitlab.com/oauth/token".to_string(),
658 device_authorization_url: None,
659 userinfo_url: Some("https://gitlab.com/api/v4/user".to_string()),
660 revocation_url: Some("https://gitlab.com/oauth/revoke".to_string()),
661 default_scopes: vec!["read_user".to_string()].into(),
662 supports_pkce: true,
663 supports_refresh: true,
664 supports_device_flow: false,
665 additional_params: crate::types::AdditionalParams::new(),
666 },
667
668 Self::Custom { config, .. } => *config.clone(),
669 }
670 }
671
672 pub fn name(&self) -> &str {
674 match self {
675 Self::GitHub => "github",
676 Self::Google => "google",
677 Self::Microsoft => "microsoft",
678 Self::Discord => "discord",
679 Self::Twitter => "twitter",
680 Self::Facebook => "facebook",
681 Self::LinkedIn => "linkedin",
682 Self::GitLab => "gitlab",
683 Self::Custom { name, .. } => name,
684 }
685 }
686
687 pub fn custom(name: impl Into<String>, config: OAuthProviderConfig) -> Self {
689 Self::Custom {
690 name: name.into(),
691 config: Box::new(config),
692 }
693 }
694
695 pub fn build_authorization_url(
697 &self,
698 client_id: &str,
699 redirect_uri: &str,
700 state: &str,
701 scopes: Option<&[String]>,
702 code_challenge: Option<&str>,
703 ) -> Result<String> {
704 let config = self.config();
705 let mut url = Url::parse(&config.authorization_url)
706 .map_err(|e| AuthError::config(format!("Invalid authorization URL: {e}")))?;
707
708 let scopes = scopes.unwrap_or(config.default_scopes.as_slice());
709
710 {
711 let mut query = url.query_pairs_mut();
712 query.append_pair("client_id", client_id);
713 query.append_pair("redirect_uri", redirect_uri);
714 query.append_pair("response_type", "code");
715 query.append_pair("state", state);
716
717 if !scopes.is_empty() {
718 query.append_pair("scope", &scopes.join(" "));
719 }
720
721 if config.supports_pkce
723 && let Some(challenge) = code_challenge
724 {
725 query.append_pair("code_challenge", challenge);
726 query.append_pair("code_challenge_method", "S256");
727 }
728
729 for (key, value) in &config.additional_params {
731 query.append_pair(key, value);
732 }
733 }
734
735 Ok(url.to_string())
736 }
737
738 pub async fn exchange_code(
740 &self,
741 client_id: &str,
742 client_secret: &str,
743 authorization_code: &str,
744 redirect_uri: &str,
745 code_verifier: Option<&str>,
746 ) -> Result<OAuthTokenResponse> {
747 let config = self.config();
748 let client = reqwest::Client::new();
749
750 let mut params = HashMap::new();
751 params.insert("grant_type".to_string(), "authorization_code".to_string());
752 params.insert("client_id".to_string(), client_id.to_string());
753 params.insert("client_secret".to_string(), client_secret.to_string());
754 params.insert("code".to_string(), authorization_code.to_string());
755 params.insert("redirect_uri".to_string(), redirect_uri.to_string());
756
757 if let Some(verifier) = code_verifier {
759 params.insert("code_verifier".to_string(), verifier.to_string());
760 }
761
762 let response = client.post(&config.token_url).form(¶ms).send().await?;
763
764 if !response.status().is_success() {
765 let error_text = response.text().await.unwrap_or_default();
766 return Err(AuthError::auth_method(
767 self.name(),
768 format!("Token exchange failed: {error_text}"),
769 ));
770 }
771
772 let token_response: OAuthTokenResponse = response.json().await?;
773 Ok(token_response)
774 }
775
776 pub async fn refresh_token(
778 &self,
779 client_id: &str,
780 client_secret: &str,
781 refresh_token: &str,
782 ) -> Result<OAuthTokenResponse> {
783 let config = self.config();
784
785 if !config.supports_refresh {
786 return Err(AuthError::auth_method(
787 self.name(),
788 "Provider does not support token refresh".to_string(),
789 ));
790 }
791
792 let client = reqwest::Client::new();
793
794 let mut params = HashMap::new();
795 params.insert("grant_type".to_string(), "refresh_token".to_string());
796 params.insert("client_id".to_string(), client_id.to_string());
797 params.insert("client_secret".to_string(), client_secret.to_string());
798 params.insert("refresh_token".to_string(), refresh_token.to_string());
799
800 let response = client.post(&config.token_url).form(¶ms).send().await?;
801
802 if !response.status().is_success() {
803 let error_text = response.text().await.unwrap_or_default();
804 return Err(AuthError::auth_method(
805 self.name(),
806 format!("Token refresh failed: {error_text}"),
807 ));
808 }
809
810 let token_response: OAuthTokenResponse = response.json().await?;
811 Ok(token_response)
812 }
813
814 pub async fn get_user_info(&self, access_token: &str) -> Result<OAuthUserInfo> {
816 let config = self.config();
817
818 let userinfo_url = config.userinfo_url.ok_or_else(|| {
819 AuthError::auth_method(
820 self.name(),
821 "Provider does not support user info endpoint".to_string(),
822 )
823 })?;
824
825 let client = reqwest::Client::new();
826 let response = client
827 .get(&userinfo_url)
828 .bearer_auth(access_token)
829 .send()
830 .await?;
831
832 if !response.status().is_success() {
833 let error_text = response.text().await.unwrap_or_default();
834 return Err(AuthError::auth_method(
835 self.name(),
836 format!("User info request failed: {error_text}"),
837 ));
838 }
839
840 let user_data: serde_json::Value = response.json().await?;
841
842 let user_info = self.parse_user_info(user_data)?;
844 Ok(user_info)
845 }
846
847 fn parse_user_info(&self, data: serde_json::Value) -> Result<OAuthUserInfo> {
849 let mut additional_fields = HashMap::new();
850
851 let user_info = match self {
852 Self::GitHub => {
853 let id = data["id"]
854 .as_u64()
855 .ok_or_else(|| AuthError::auth_method(self.name(), "Missing user ID"))?
856 .to_string();
857
858 OAuthUserInfo {
859 id,
860 username: data["login"].as_str().map(|s| s.to_string()),
861 email: data["email"].as_str().map(|s| s.to_string()),
862 name: data["name"].as_str().map(|s| s.to_string()),
863 picture: data["avatar_url"].as_str().map(|s| s.to_string()),
864 email_verified: None, locale: None,
866 additional_fields,
867 }
868 }
869
870 Self::Google => {
871 let id = data["id"]
872 .as_str()
873 .ok_or_else(|| AuthError::auth_method(self.name(), "Missing user ID"))?
874 .to_string();
875
876 OAuthUserInfo {
877 id,
878 username: None, email: data["email"].as_str().map(|s| s.to_string()),
880 name: data["name"].as_str().map(|s| s.to_string()),
881 picture: data["picture"].as_str().map(|s| s.to_string()),
882 email_verified: data["verified_email"].as_bool(),
883 locale: data["locale"].as_str().map(|s| s.to_string()),
884 additional_fields,
885 }
886 }
887
888 _ => {
890 let id = data["id"]
892 .as_str()
893 .or_else(|| data["sub"].as_str())
894 .or_else(|| data["user_id"].as_str())
895 .ok_or_else(|| AuthError::auth_method(self.name(), "Missing user ID"))?
896 .to_string();
897
898 if let serde_json::Value::Object(map) = data {
900 additional_fields = map.into_iter().collect();
901 }
902
903 OAuthUserInfo {
904 id,
905 username: additional_fields
906 .get("username")
907 .or_else(|| additional_fields.get("login"))
908 .and_then(|v| v.as_str())
909 .map(|s| s.to_string()),
910 email: additional_fields
911 .get("email")
912 .and_then(|v| v.as_str())
913 .map(|s| s.to_string()),
914 name: additional_fields
915 .get("name")
916 .or_else(|| additional_fields.get("display_name"))
917 .and_then(|v| v.as_str())
918 .map(|s| s.to_string()),
919 picture: additional_fields
920 .get("avatar_url")
921 .or_else(|| additional_fields.get("picture"))
922 .and_then(|v| v.as_str())
923 .map(|s| s.to_string()),
924 email_verified: additional_fields
925 .get("email_verified")
926 .and_then(|v| v.as_bool()),
927 locale: additional_fields
928 .get("locale")
929 .and_then(|v| v.as_str())
930 .map(|s| s.to_string()),
931 additional_fields,
932 }
933 }
934 };
935
936 Ok(user_info)
937 }
938
939 pub async fn revoke_token(&self, access_token: &str) -> Result<()> {
941 let config = self.config();
942
943 let revocation_url = config.revocation_url.ok_or_else(|| {
944 AuthError::auth_method(
945 self.name(),
946 "Provider does not support token revocation".to_string(),
947 )
948 })?;
949
950 let client = reqwest::Client::new();
951 let mut params = HashMap::new();
952 params.insert("token".to_string(), access_token.to_string());
953
954 let response = client.post(&revocation_url).form(¶ms).send().await?;
955
956 if !response.status().is_success() {
957 let error_text = response.text().await.unwrap_or_default();
958 return Err(AuthError::auth_method(
959 self.name(),
960 format!("Token revocation failed: {error_text}"),
961 ));
962 }
963
964 Ok(())
965 }
966
967 pub async fn device_authorization(
969 &self,
970 client_id: &str,
971 scope: Option<&[String]>,
972 ) -> Result<DeviceAuthorizationResponse> {
973 let config = self.config();
974
975 if !config.supports_device_flow {
976 return Err(AuthError::auth_method(
977 self.name(),
978 "Provider does not support device authorization flow".to_string(),
979 ));
980 }
981
982 let client = reqwest::Client::new();
983
984 let scope_string = scope.unwrap_or(&config.default_scopes).join(" ");
985 let mut params = HashMap::new();
986 params.insert("client_id".to_string(), client_id.to_string());
987 params.insert("scope".to_string(), scope_string);
988
989 let device_auth_url = config.device_authorization_url.as_deref().ok_or_else(|| {
990 AuthError::auth_method(
991 self.name(),
992 "Device authorization URL is not configured for this provider".to_string(),
993 )
994 })?;
995
996 let response = client.post(device_auth_url).form(¶ms).send().await?;
997
998 if !response.status().is_success() {
999 let error_text = response.text().await.unwrap_or_default();
1000 return Err(AuthError::auth_method(
1001 self.name(),
1002 format!("Device authorization request failed: {error_text}"),
1003 ));
1004 }
1005
1006 let device_response: DeviceAuthorizationResponse = response.json().await?;
1007 Ok(device_response)
1008 }
1009
1010 pub async fn poll_device_code(
1012 &self,
1013 client_id: &str,
1014 device_code: &str,
1015 _interval: Option<u64>,
1016 ) -> Result<OAuthTokenResponse> {
1017 let config = self.config();
1018
1019 if !config.supports_device_flow {
1020 return Err(AuthError::auth_method(
1021 self.name(),
1022 "Provider does not support device authorization flow".to_string(),
1023 ));
1024 }
1025
1026 let client = reqwest::Client::new();
1027
1028 let mut params = HashMap::new();
1029 params.insert("client_id".to_string(), client_id.to_string());
1030 params.insert(
1031 "grant_type".to_string(),
1032 "urn:ietf:params:oauth:grant-type:device_code".to_string(),
1033 );
1034 params.insert("device_code".to_string(), device_code.to_string());
1035
1036 let response = client.post(&config.token_url).form(¶ms).send().await?;
1037
1038 if !response.status().is_success() {
1039 let error_text = response.text().await.unwrap_or_default();
1040 return Err(AuthError::auth_method(
1041 self.name(),
1042 format!("Token request failed: {error_text}"),
1043 ));
1044 }
1045
1046 let token_response: OAuthTokenResponse = response.json().await?;
1047 Ok(token_response)
1048 }
1049}
1050
1051pub fn generate_state() -> String {
1053 let mut bytes = [0u8; 32];
1054 use rand::Rng;
1055 rand::rng().fill_bytes(&mut bytes);
1056 base64::engine::general_purpose::URL_SAFE_NO_PAD.encode(bytes)
1057}
1058
1059pub fn generate_pkce() -> (String, String) {
1061 use rand::Rng;
1062 use ring::digest;
1063
1064 let mut rng = rand::rng();
1066 let mut bytes = [0u8; 96]; rng.fill_bytes(&mut bytes);
1068 let code_verifier = base64::engine::general_purpose::URL_SAFE_NO_PAD.encode(bytes);
1069
1070 let digest = digest::digest(&digest::SHA256, code_verifier.as_bytes());
1072 let code_challenge = base64::engine::general_purpose::URL_SAFE_NO_PAD.encode(digest.as_ref());
1073
1074 (code_verifier, code_challenge)
1075}
1076
1077pub struct ProfileExtractor {
1079 client: Client,
1080}
1081
1082impl ProfileExtractor {
1083 pub fn new() -> Self {
1085 Self {
1086 client: Client::new(),
1087 }
1088 }
1089
1090 pub async fn extract_profile(
1092 &self,
1093 token: &AuthToken,
1094 provider: &OAuthProvider,
1095 ) -> Result<ProviderProfile> {
1096 match provider {
1097 OAuthProvider::GitHub => self.extract_github_profile(token).await,
1098 OAuthProvider::Google => self.extract_google_profile(token).await,
1099 OAuthProvider::Microsoft => self.extract_microsoft_profile(token).await,
1100 OAuthProvider::Discord => self.extract_discord_profile(token).await,
1101 OAuthProvider::GitLab => self.extract_gitlab_profile(token).await,
1102 OAuthProvider::Custom { name, config } => {
1103 self.extract_custom_profile(token, name, config).await
1104 }
1105 _ => Err(AuthError::UnsupportedProvider(format!(
1106 "Profile extraction not supported for {:?}",
1107 provider
1108 ))),
1109 }
1110 }
1111
1112 async fn extract_github_profile(&self, token: &AuthToken) -> Result<ProviderProfile> {
1114 let response = self
1115 .client
1116 .get("https://api.github.com/user")
1117 .bearer_auth(&token.access_token)
1118 .send()
1119 .await
1120 .map_err(|e| AuthError::internal(e.to_string()))?;
1121
1122 let json: Value = response
1123 .json()
1124 .await
1125 .map_err(|e| AuthError::internal(e.to_string()))?;
1126
1127 let mut profile = ProviderProfile::new();
1128 profile = profile.with_id(json["id"].as_u64().unwrap_or(0).to_string());
1129 profile = profile.with_provider("github".to_string());
1130
1131 if let Some(login) = json["login"].as_str() {
1132 profile.username = Some(login.to_string());
1133 }
1134
1135 if let Some(name) = json["name"].as_str() {
1136 profile.name = Some(name.to_string());
1137 }
1138
1139 if let Some(email) = json["email"].as_str() {
1140 profile.email = Some(email.to_string());
1141 }
1142
1143 if let Some(avatar_url) = json["avatar_url"].as_str() {
1144 profile.picture = Some(avatar_url.to_string());
1145 }
1146
1147 if let Some(company) = json["company"].as_str() {
1149 profile
1150 .additional_data
1151 .insert("company".to_string(), Value::String(company.to_string()));
1152 }
1153
1154 if let Some(blog) = json["blog"].as_str() {
1155 profile
1156 .additional_data
1157 .insert("blog".to_string(), Value::String(blog.to_string()));
1158 }
1159
1160 if let Some(bio) = json["bio"].as_str() {
1161 profile
1162 .additional_data
1163 .insert("bio".to_string(), Value::String(bio.to_string()));
1164 }
1165
1166 Ok(profile)
1167 }
1168
1169 async fn extract_google_profile(&self, token: &AuthToken) -> Result<ProviderProfile> {
1171 let response = self
1172 .client
1173 .get("https://www.googleapis.com/oauth2/v2/userinfo")
1174 .bearer_auth(&token.access_token)
1175 .send()
1176 .await
1177 .map_err(|e| AuthError::internal(e.to_string()))?;
1178
1179 let json: Value = response
1180 .json()
1181 .await
1182 .map_err(|e| AuthError::internal(e.to_string()))?;
1183
1184 let mut profile = ProviderProfile::new();
1185 profile = profile.with_id(json["id"].as_str().unwrap_or("").to_string());
1186 profile = profile.with_provider("google".to_string());
1187
1188 if let Some(name) = json["name"].as_str() {
1189 profile.name = Some(name.to_string());
1190 }
1191
1192 if let Some(email) = json["email"].as_str() {
1193 profile.email = Some(email.to_string());
1194 }
1195
1196 if let Some(verified) = json["verified_email"].as_bool() {
1197 profile.email_verified = Some(verified);
1198 }
1199
1200 if let Some(picture) = json["picture"].as_str() {
1201 profile.picture = Some(picture.to_string());
1202 }
1203
1204 if let Some(locale) = json["locale"].as_str() {
1205 profile.locale = Some(locale.to_string());
1206 }
1207
1208 Ok(profile)
1209 }
1210
1211 async fn extract_microsoft_profile(&self, token: &AuthToken) -> Result<ProviderProfile> {
1213 let response = self
1214 .client
1215 .get("https://graph.microsoft.com/v1.0/me")
1216 .bearer_auth(&token.access_token)
1217 .send()
1218 .await
1219 .map_err(|e| AuthError::internal(e.to_string()))?;
1220
1221 let json: Value = response
1222 .json()
1223 .await
1224 .map_err(|e| AuthError::internal(e.to_string()))?;
1225
1226 let mut profile = ProviderProfile::new();
1227 profile = profile.with_id(json["id"].as_str().unwrap_or("").to_string());
1228 profile = profile.with_provider("microsoft".to_string());
1229
1230 if let Some(display_name) = json["displayName"].as_str() {
1231 profile.name = Some(display_name.to_string());
1232 }
1233
1234 if let Some(user_principal_name) = json["userPrincipalName"].as_str() {
1235 profile.username = Some(user_principal_name.to_string());
1236 }
1237
1238 if let Some(mail) = json["mail"].as_str() {
1239 profile.email = Some(mail.to_string());
1240 }
1241
1242 if let Some(preferred_language) = json["preferredLanguage"].as_str() {
1243 profile.locale = Some(preferred_language.to_string());
1244 }
1245
1246 if let Some(job_title) = json["jobTitle"].as_str() {
1248 profile
1249 .additional_data
1250 .insert("jobTitle".to_string(), Value::String(job_title.to_string()));
1251 }
1252
1253 if let Some(office_location) = json["officeLocation"].as_str() {
1254 profile.additional_data.insert(
1255 "officeLocation".to_string(),
1256 Value::String(office_location.to_string()),
1257 );
1258 }
1259
1260 Ok(profile)
1261 }
1262
1263 async fn extract_discord_profile(&self, token: &AuthToken) -> Result<ProviderProfile> {
1265 let response = self
1266 .client
1267 .get("https://discord.com/api/users/@me")
1268 .bearer_auth(&token.access_token)
1269 .send()
1270 .await
1271 .map_err(|e| AuthError::internal(e.to_string()))?;
1272
1273 let json: Value = response
1274 .json()
1275 .await
1276 .map_err(|e| AuthError::internal(e.to_string()))?;
1277
1278 let mut profile = ProviderProfile::new();
1279 profile = profile.with_id(json["id"].as_str().unwrap_or("").to_string());
1280 profile = profile.with_provider("discord".to_string());
1281
1282 if let Some(username) = json["username"].as_str() {
1283 profile.username = Some(username.to_string());
1284 }
1285
1286 if let Some(discriminator) = json["discriminator"].as_str() {
1287 profile.name = Some(format!(
1288 "{}#{}",
1289 json["username"].as_str().unwrap_or(""),
1290 discriminator
1291 ));
1292 }
1293
1294 if let Some(email) = json["email"].as_str() {
1295 profile.email = Some(email.to_string());
1296 }
1297
1298 if let Some(verified) = json["verified"].as_bool() {
1299 profile.email_verified = Some(verified);
1300 }
1301
1302 if let Some(avatar) = json["avatar"].as_str() {
1303 let user_id = json["id"].as_str().unwrap_or("");
1304 profile.picture = Some(format!(
1305 "https://cdn.discordapp.com/avatars/{}/{}.png",
1306 user_id, avatar
1307 ));
1308 }
1309
1310 if let Some(locale) = json["locale"].as_str() {
1311 profile.locale = Some(locale.to_string());
1312 }
1313
1314 Ok(profile)
1315 }
1316
1317 async fn extract_gitlab_profile(&self, token: &AuthToken) -> Result<ProviderProfile> {
1319 let response = self
1320 .client
1321 .get("https://gitlab.com/api/v4/user")
1322 .bearer_auth(&token.access_token)
1323 .send()
1324 .await
1325 .map_err(|e| AuthError::internal(e.to_string()))?;
1326
1327 let json: Value = response
1328 .json()
1329 .await
1330 .map_err(|e| AuthError::internal(e.to_string()))?;
1331
1332 let mut profile = ProviderProfile::new();
1333 profile = profile.with_id(json["id"].as_u64().unwrap_or(0).to_string());
1334 profile = profile.with_provider("gitlab".to_string());
1335
1336 if let Some(username) = json["username"].as_str() {
1337 profile.username = Some(username.to_string());
1338 }
1339
1340 if let Some(name) = json["name"].as_str() {
1341 profile.name = Some(name.to_string());
1342 }
1343
1344 if let Some(email) = json["email"].as_str() {
1345 profile.email = Some(email.to_string());
1346 }
1347
1348 if let Some(avatar_url) = json["avatar_url"].as_str() {
1349 profile.picture = Some(avatar_url.to_string());
1350 }
1351
1352 if let Some(web_url) = json["web_url"].as_str() {
1354 profile
1355 .additional_data
1356 .insert("web_url".to_string(), Value::String(web_url.to_string()));
1357 }
1358
1359 if let Some(bio) = json["bio"].as_str() {
1360 profile
1361 .additional_data
1362 .insert("bio".to_string(), Value::String(bio.to_string()));
1363 }
1364
1365 Ok(profile)
1366 }
1367
1368 async fn extract_custom_profile(
1370 &self,
1371 token: &AuthToken,
1372 provider_name: &str,
1373 config: &OAuthProviderConfig,
1374 ) -> Result<ProviderProfile> {
1375 if let Some(user_info_url) = &config.userinfo_url {
1376 let response = self
1377 .client
1378 .get(user_info_url)
1379 .bearer_auth(&token.access_token)
1380 .send()
1381 .await
1382 .map_err(|e| AuthError::internal(e.to_string()))?;
1383
1384 let json: Value = response
1385 .json()
1386 .await
1387 .map_err(|e| AuthError::internal(e.to_string()))?;
1388
1389 let mut profile = ProviderProfile::new();
1390 profile = profile.with_id(
1391 json["id"]
1392 .as_str()
1393 .or_else(|| json["sub"].as_str())
1394 .unwrap_or("")
1395 .to_string(),
1396 );
1397 profile = profile.with_provider(provider_name.to_string());
1398
1399 if let Some(username) = json["username"].as_str().or_else(|| json["login"].as_str()) {
1401 profile.username = Some(username.to_string());
1402 }
1403
1404 if let Some(name) = json["name"]
1405 .as_str()
1406 .or_else(|| json["display_name"].as_str())
1407 {
1408 profile.name = Some(name.to_string());
1409 }
1410
1411 if let Some(email) = json["email"].as_str() {
1412 profile.email = Some(email.to_string());
1413 }
1414
1415 if let Some(verified) = json["email_verified"]
1416 .as_bool()
1417 .or_else(|| json["verified"].as_bool())
1418 {
1419 profile.email_verified = Some(verified);
1420 }
1421
1422 if let Some(picture) = json["picture"]
1423 .as_str()
1424 .or_else(|| json["avatar_url"].as_str())
1425 {
1426 profile.picture = Some(picture.to_string());
1427 }
1428
1429 if let Some(locale) = json["locale"].as_str().or_else(|| json["lang"].as_str()) {
1430 profile.locale = Some(locale.to_string());
1431 }
1432
1433 for (key, value) in json.as_object().unwrap_or(&serde_json::Map::new()) {
1435 if ![
1436 "id",
1437 "sub",
1438 "username",
1439 "login",
1440 "name",
1441 "display_name",
1442 "email",
1443 "email_verified",
1444 "verified",
1445 "picture",
1446 "avatar_url",
1447 "locale",
1448 "lang",
1449 ]
1450 .contains(&key.as_str())
1451 {
1452 profile.additional_data.insert(key.clone(), value.clone());
1453 }
1454 }
1455
1456 Ok(profile)
1457 } else {
1458 Err(AuthError::config(
1459 "Custom provider requires user_info_url".to_string(),
1460 ))
1461 }
1462 }
1463}
1464
1465impl Default for ProfileExtractor {
1466 fn default() -> Self {
1467 Self::new()
1468 }
1469}
1470
1471impl fmt::Display for OAuthProvider {
1472 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1473 match self {
1474 OAuthProvider::GitHub => write!(f, "github"),
1475 OAuthProvider::Google => write!(f, "google"),
1476 OAuthProvider::Microsoft => write!(f, "microsoft"),
1477 OAuthProvider::Discord => write!(f, "discord"),
1478 OAuthProvider::Twitter => write!(f, "twitter"),
1479 OAuthProvider::Facebook => write!(f, "facebook"),
1480 OAuthProvider::LinkedIn => write!(f, "linkedin"),
1481 OAuthProvider::GitLab => write!(f, "gitlab"),
1482 OAuthProvider::Custom { name, .. } => write!(f, "{}", name),
1483 }
1484 }
1485}
1486
1487#[cfg(test)]
1488mod tests {
1489 use super::*;
1490
1491 #[test]
1492 fn test_provider_config() {
1493 let github = OAuthProvider::GitHub;
1494 let config = github.config();
1495
1496 assert_eq!(
1497 config.authorization_url,
1498 "https://github.com/login/oauth/authorize"
1499 );
1500 assert_eq!(
1501 config.token_url,
1502 "https://github.com/login/oauth/access_token"
1503 );
1504 assert!(config.supports_pkce);
1505 }
1506
1507 #[test]
1508 fn test_authorization_url() {
1509 let github = OAuthProvider::GitHub;
1510 let url = github
1511 .build_authorization_url(
1512 "client123",
1513 "https://example.com/callback",
1514 "state123",
1515 None,
1516 Some("challenge123"),
1517 )
1518 .unwrap();
1519
1520 assert!(url.contains("client_id=client123"));
1521 assert!(url.contains("redirect_uri=https%3A%2F%2Fexample.com%2Fcallback"));
1522 assert!(url.contains("state=state123"));
1523 assert!(url.contains("code_challenge=challenge123"));
1524 }
1525
1526 #[test]
1527 fn test_generate_state() {
1528 let state1 = generate_state();
1529 let state2 = generate_state();
1530
1531 assert_eq!(state1.len(), 43);
1532 assert_eq!(state2.len(), 43);
1533 assert_ne!(state1, state2);
1534 }
1535
1536 #[test]
1537 fn test_generate_pkce() {
1538 let (verifier1, challenge1) = generate_pkce();
1539 let (verifier2, challenge2) = generate_pkce();
1540
1541 assert_eq!(verifier1.len(), 128);
1542 assert_eq!(verifier2.len(), 128);
1543 assert_ne!(verifier1, verifier2);
1544 assert_ne!(challenge1, challenge2);
1545 }
1546}