1use crate::errors::{AuthError, Result};
7use crate::security::secure_utils::constant_time_compare;
8use crate::server::oauth::oauth2_enhanced_storage::{
9 EnhancedAuthorizationCode, EnhancedClientCredentials, EnhancedTokenStorage, RefreshToken,
10};
11use crate::tokens::{AuthToken, TokenManager};
12use crate::user_context::{SessionStore, UserContext};
13use serde::{Deserialize, Serialize};
14use sha2::{Digest, Sha256};
15use std::sync::Arc;
16use std::time::Duration;
17use tokio::sync::RwLock;
18
19#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
21pub enum GrantType {
22 AuthorizationCode,
23 RefreshToken,
24 ClientCredentials,
25 DeviceCode,
26 TokenExchange,
27}
28
29impl std::fmt::Display for GrantType {
30 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
31 match self {
32 GrantType::AuthorizationCode => write!(f, "authorization_code"),
33 GrantType::RefreshToken => write!(f, "refresh_token"),
34 GrantType::ClientCredentials => write!(f, "client_credentials"),
35 GrantType::DeviceCode => write!(f, "urn:ietf:params:oauth:grant-type:device_code"),
36 GrantType::TokenExchange => {
37 write!(f, "urn:ietf:params:oauth:grant-type:token-exchange")
38 }
39 }
40 }
41}
42
43impl std::str::FromStr for GrantType {
44 type Err = AuthError;
45
46 fn from_str(s: &str) -> std::result::Result<Self, Self::Err> {
47 match s {
48 "authorization_code" => Ok(Self::AuthorizationCode),
49 "refresh_token" => Ok(Self::RefreshToken),
50 "client_credentials" => Ok(Self::ClientCredentials),
51 "urn:ietf:params:oauth:grant-type:device_code" => Ok(Self::DeviceCode),
52 "urn:ietf:params:oauth:grant-type:token-exchange" => Ok(Self::TokenExchange),
53 other => Err(AuthError::auth_method(
54 "oauth2",
55 format!("Unsupported grant type: {other}"),
56 )),
57 }
58 }
59}
60
61#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
63pub enum ResponseType {
64 Code,
65 Token,
66 IdToken,
67}
68
69impl std::fmt::Display for ResponseType {
70 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
71 match self {
72 ResponseType::Code => write!(f, "code"),
73 ResponseType::Token => write!(f, "token"),
74 ResponseType::IdToken => write!(f, "id_token"),
75 }
76 }
77}
78
79impl std::str::FromStr for ResponseType {
80 type Err = AuthError;
81
82 fn from_str(s: &str) -> std::result::Result<Self, Self::Err> {
83 match s {
84 "code" => Ok(Self::Code),
85 "token" => Ok(Self::Token),
86 "id_token" => Ok(Self::IdToken),
87 other => Err(AuthError::auth_method(
88 "oauth2",
89 format!("Unsupported response type: {other}"),
90 )),
91 }
92 }
93}
94
95#[derive(Debug, Clone)]
97pub struct OAuth2Config {
98 pub issuer: String,
100 pub authorization_code_lifetime: Duration,
102 pub access_token_lifetime: Duration,
104 pub refresh_token_lifetime: Duration,
106 pub device_code_lifetime: Duration,
108 pub default_scope: Option<String>,
110 pub max_scope_lifetime: Duration,
112 pub require_pkce: bool,
114 pub enable_introspection: bool,
116 pub enable_revocation: bool,
118}
119
120impl Default for OAuth2Config {
121 fn default() -> Self {
122 Self {
123 issuer: "https://auth.example.com".to_string(),
124 authorization_code_lifetime: Duration::from_secs(600), access_token_lifetime: Duration::from_secs(3600), refresh_token_lifetime: Duration::from_secs(86400 * 7), device_code_lifetime: Duration::from_secs(600), default_scope: Some("read".to_string()),
129 max_scope_lifetime: Duration::from_secs(86400 * 30), require_pkce: true,
131 enable_introspection: true,
132 enable_revocation: true,
133 }
134 }
135}
136
137impl OAuth2Config {
138 pub fn builder() -> OAuth2ConfigBuilder {
153 OAuth2ConfigBuilder::default()
154 }
155}
156
157#[derive(Debug, Clone, Default)]
162pub struct OAuth2ConfigBuilder {
163 config: OAuth2Config,
164}
165
166impl OAuth2ConfigBuilder {
167 pub fn issuer(mut self, issuer: impl Into<String>) -> Self {
169 self.config.issuer = issuer.into();
170 self
171 }
172
173 pub fn authorization_code_lifetime(mut self, lifetime: Duration) -> Self {
175 self.config.authorization_code_lifetime = lifetime;
176 self
177 }
178
179 pub fn access_token_lifetime(mut self, lifetime: Duration) -> Self {
181 self.config.access_token_lifetime = lifetime;
182 self
183 }
184
185 pub fn refresh_token_lifetime(mut self, lifetime: Duration) -> Self {
187 self.config.refresh_token_lifetime = lifetime;
188 self
189 }
190
191 pub fn device_code_lifetime(mut self, lifetime: Duration) -> Self {
193 self.config.device_code_lifetime = lifetime;
194 self
195 }
196
197 pub fn default_scope(mut self, scope: impl Into<String>) -> Self {
199 self.config.default_scope = Some(scope.into());
200 self
201 }
202
203 pub fn max_scope_lifetime(mut self, lifetime: Duration) -> Self {
205 self.config.max_scope_lifetime = lifetime;
206 self
207 }
208
209 pub fn require_pkce(mut self, require: bool) -> Self {
211 self.config.require_pkce = require;
212 self
213 }
214
215 pub fn enable_introspection(mut self, enable: bool) -> Self {
217 self.config.enable_introspection = enable;
218 self
219 }
220
221 pub fn enable_revocation(mut self, enable: bool) -> Self {
223 self.config.enable_revocation = enable;
224 self
225 }
226
227 pub fn build(self) -> OAuth2Config {
229 self.config
230 }
231}
232
233#[derive(Debug, Clone, Serialize, Deserialize, Default)]
255pub struct TokenRequest {
256 pub grant_type: String,
257 #[serde(default)]
260 pub client_id: Option<String>,
261 pub client_secret: Option<String>,
262 pub code: Option<String>,
263 pub redirect_uri: Option<String>,
264 pub refresh_token: Option<String>,
265 pub scope: Option<String>,
266 pub code_verifier: Option<String>,
267 pub username: Option<String>,
268 pub password: Option<String>,
269 pub device_code: Option<String>,
270 #[serde(default)]
272 pub resource: Option<Vec<String>>,
273}
274
275impl TokenRequest {
276 pub fn authorization_code(code: impl Into<String>) -> Self {
278 Self {
279 grant_type: "authorization_code".to_string(),
280 code: Some(code.into()),
281 ..Default::default()
282 }
283 }
284
285 pub fn refresh(token: impl Into<String>) -> Self {
287 Self {
288 grant_type: "refresh_token".to_string(),
289 refresh_token: Some(token.into()),
290 ..Default::default()
291 }
292 }
293
294 pub fn client_credentials(
296 client_id: impl Into<String>,
297 client_secret: impl Into<String>,
298 ) -> Self {
299 Self {
300 grant_type: "client_credentials".to_string(),
301 client_id: Some(client_id.into()),
302 client_secret: Some(client_secret.into()),
303 ..Default::default()
304 }
305 }
306
307 pub fn client_id(mut self, id: impl Into<String>) -> Self {
309 self.client_id = Some(id.into());
310 self
311 }
312
313 pub fn client_secret(mut self, secret: impl Into<String>) -> Self {
315 self.client_secret = Some(secret.into());
316 self
317 }
318
319 pub fn redirect_uri(mut self, uri: impl Into<String>) -> Self {
321 self.redirect_uri = Some(uri.into());
322 self
323 }
324
325 pub fn code_verifier(mut self, verifier: impl Into<String>) -> Self {
327 self.code_verifier = Some(verifier.into());
328 self
329 }
330
331 pub fn scope(mut self, scope: impl Into<String>) -> Self {
333 self.scope = Some(scope.into());
334 self
335 }
336
337 pub fn resource(mut self, uris: Vec<String>) -> Self {
339 self.resource = Some(uris);
340 self
341 }
342}
343
344#[derive(Debug, Clone, Serialize, Deserialize)]
346pub struct TokenResponse {
347 pub access_token: String,
348 pub token_type: String,
349 pub expires_in: u64,
350 pub refresh_token: Option<String>,
351 pub scope: Option<String>,
352 pub id_token: Option<String>,
353}
354
355#[derive(Debug, Clone, Serialize, Deserialize)]
368pub struct AuthorizationRequest {
369 pub client_id: String,
370 pub response_type: String,
371 pub redirect_uri: String,
372 pub scope: Option<String>,
373 pub state: Option<String>,
374 pub code_challenge: Option<String>,
375 pub code_challenge_method: Option<String>,
376 pub nonce: Option<String>,
377 #[serde(default)]
379 pub resource: Option<Vec<String>>,
380}
381
382impl AuthorizationRequest {
383 pub fn new(
385 client_id: impl Into<String>,
386 response_type: impl Into<String>,
387 redirect_uri: impl Into<String>,
388 ) -> Self {
389 Self {
390 client_id: client_id.into(),
391 response_type: response_type.into(),
392 redirect_uri: redirect_uri.into(),
393 scope: None,
394 state: None,
395 code_challenge: None,
396 code_challenge_method: None,
397 nonce: None,
398 resource: None,
399 }
400 }
401
402 pub fn scope(mut self, scope: impl Into<String>) -> Self {
404 self.scope = Some(scope.into());
405 self
406 }
407
408 pub fn state(mut self, state: impl Into<String>) -> Self {
410 self.state = Some(state.into());
411 self
412 }
413
414 pub fn pkce(mut self, challenge: impl Into<String>, method: impl Into<String>) -> Self {
416 self.code_challenge = Some(challenge.into());
417 self.code_challenge_method = Some(method.into());
418 self
419 }
420
421 pub fn nonce(mut self, nonce: impl Into<String>) -> Self {
423 self.nonce = Some(nonce.into());
424 self
425 }
426
427 pub fn resource(mut self, uris: Vec<String>) -> Self {
429 self.resource = Some(uris);
430 self
431 }
432}
433
434pub struct OAuth2Server {
436 config: OAuth2Config,
437 token_storage: Arc<RwLock<EnhancedTokenStorage>>,
438 session_store: Arc<RwLock<SessionStore>>,
439 token_manager: Arc<TokenManager>,
440}
441
442impl OAuth2Server {
443 pub async fn new(config: OAuth2Config, token_manager: Arc<TokenManager>) -> Result<Self> {
444 Ok(Self {
445 config,
446 token_storage: Arc::new(RwLock::new(EnhancedTokenStorage::new())),
447 session_store: Arc::new(RwLock::new(SessionStore::new())),
448 token_manager,
449 })
450 }
451
452 pub async fn register_confidential_client(
454 &self,
455 client_id: String,
456 client_secret: &str,
457 redirect_uris: Vec<String>,
458 allowed_scopes: Vec<String>,
459 grant_types: Vec<String>,
460 ) -> Result<()> {
461 if client_secret.len() < 32 {
463 return Err(AuthError::auth_method(
464 "oauth2",
465 "Client secret must be at least 32 characters",
466 ));
467 }
468
469 let credentials = EnhancedClientCredentials::new_confidential(
470 client_id,
471 client_secret,
472 redirect_uris,
473 allowed_scopes,
474 grant_types,
475 )?;
476
477 let mut storage = self.token_storage.write().await;
478 storage.store_client_credentials(credentials).await?;
479
480 Ok(())
481 }
482
483 pub async fn register_public_client(
485 &self,
486 client_id: String,
487 redirect_uris: Vec<String>,
488 allowed_scopes: Vec<String>,
489 grant_types: Vec<String>,
490 ) -> Result<()> {
491 let credentials = EnhancedClientCredentials::new_public(
492 client_id,
493 redirect_uris,
494 allowed_scopes,
495 grant_types,
496 );
497
498 let mut storage = self.token_storage.write().await;
499 storage.store_client_credentials(credentials).await?;
500
501 Ok(())
502 }
503
504 pub async fn create_authorization_code(
506 &self,
507 request: AuthorizationRequest,
508 user_context: UserContext,
509 ) -> Result<EnhancedAuthorizationCode> {
510 let storage = self.token_storage.read().await;
512 let client = storage
513 .get_client_credentials(&request.client_id)
514 .await?
515 .ok_or_else(|| AuthError::auth_method("oauth2", "Invalid client_id"))?;
516
517 if !client.supports_grant_type("authorization_code") {
518 return Err(AuthError::auth_method(
519 "oauth2",
520 "Client does not support authorization code grant",
521 ));
522 }
523
524 if !client.redirect_uris.contains(&request.redirect_uri) {
525 return Err(AuthError::auth_method("oauth2", "Invalid redirect_uri"));
526 }
527
528 let requested_scopes = self.parse_scopes(request.scope.as_deref())?;
530 let authorized_scopes = self.authorize_scopes(&client, &user_context, &requested_scopes)?;
531
532 let auth_code = EnhancedAuthorizationCode::new(
534 client.client_id.clone(),
535 user_context.user_id.clone(), request.redirect_uri,
537 authorized_scopes,
538 request.code_challenge,
539 request.code_challenge_method,
540 self.config.authorization_code_lifetime,
541 );
542
543 drop(storage);
545 let mut storage = self.token_storage.write().await;
546 storage.store_authorization_code(auth_code.clone()).await?;
547
548 Ok(auth_code)
549 }
550
551 pub async fn token_exchange(&self, request: TokenRequest) -> Result<TokenResponse> {
553 match request.grant_type.as_str() {
554 "authorization_code" => self.handle_authorization_code_grant(request).await,
555 "refresh_token" => self.handle_refresh_token_grant(request).await,
556 "client_credentials" => self.handle_client_credentials_grant(request).await,
557 _ => Err(AuthError::auth_method("oauth2", "Unsupported grant type")),
558 }
559 }
560
561 async fn handle_authorization_code_grant(
563 &self,
564 request: TokenRequest,
565 ) -> Result<TokenResponse> {
566 let client_id = request
567 .client_id
568 .ok_or_else(|| AuthError::auth_method("oauth2", "client_id is required"))?;
569 let storage = self.token_storage.read().await;
571 let _client = storage
572 .get_client_credentials(&client_id)
573 .await?
574 .ok_or_else(|| AuthError::auth_method("oauth2", "Invalid client_id"))?;
575
576 if !storage
578 .validate_client_credentials(&client_id, request.client_secret.as_deref())
579 .await?
580 {
581 return Err(AuthError::auth_method(
582 "oauth2",
583 "Invalid client credentials",
584 ));
585 }
586
587 let code = request
589 .code
590 .ok_or_else(|| AuthError::auth_method("oauth2", "Missing authorization code"))?;
591
592 drop(storage);
593 let mut storage = self.token_storage.write().await;
594 let auth_code = storage
595 .consume_authorization_code(&code)
596 .await?
597 .ok_or_else(|| {
598 AuthError::auth_method("oauth2", "Invalid or expired authorization code")
599 })?;
600
601 if auth_code.client_id != client_id {
603 return Err(AuthError::auth_method(
604 "oauth2",
605 "Authorization code does not belong to client",
606 ));
607 }
608
609 if let Some(challenge) = &auth_code.code_challenge {
611 let verifier = request
612 .code_verifier
613 .ok_or_else(|| AuthError::auth_method("oauth2", "PKCE code verifier required"))?;
614
615 if !self.validate_pkce_challenge(
616 challenge,
617 &verifier,
618 &auth_code.code_challenge_method,
619 )? {
620 return Err(AuthError::auth_method(
621 "oauth2",
622 "Invalid PKCE code verifier",
623 ));
624 }
625 }
626
627 let access_token = self
629 .generate_access_token(
630 &auth_code.client_id,
631 Some(&auth_code.user_id), &auth_code.scopes,
633 )
634 .await?;
635
636 let refresh_token = RefreshToken::new(
638 auth_code.client_id.clone(),
639 auth_code.user_id.clone(), auth_code.scopes.clone(), self.config.refresh_token_lifetime,
642 );
643
644 let refresh_token_id = storage.store_refresh_token(refresh_token).await?;
645
646 Ok(TokenResponse {
647 access_token: access_token.access_token,
648 token_type: "Bearer".to_string(),
649 expires_in: self.config.access_token_lifetime.as_secs(),
650 refresh_token: Some(refresh_token_id),
651 scope: Some(auth_code.scopes.join(" ")),
652 id_token: None,
653 })
654 }
655
656 async fn handle_refresh_token_grant(&self, request: TokenRequest) -> Result<TokenResponse> {
658 let client_id = request
659 .client_id
660 .ok_or_else(|| AuthError::auth_method("oauth2", "client_id is required"))?;
661 let storage = self.token_storage.read().await;
663 if !storage
664 .validate_client_credentials(&client_id, request.client_secret.as_deref())
665 .await?
666 {
667 return Err(AuthError::auth_method(
668 "oauth2",
669 "Invalid client credentials",
670 ));
671 }
672
673 let refresh_token_id = request
675 .refresh_token
676 .ok_or_else(|| AuthError::auth_method("oauth2", "Missing refresh token"))?;
677
678 let stored_token = storage
680 .get_refresh_token(&refresh_token_id)
681 .await?
682 .ok_or_else(|| AuthError::auth_method("oauth2", "Invalid refresh token"))?;
683
684 if !stored_token.is_valid() {
685 return Err(AuthError::auth_method(
686 "oauth2",
687 "Refresh token is expired or revoked",
688 ));
689 }
690
691 if stored_token.client_id != client_id {
693 return Err(AuthError::auth_method(
694 "oauth2",
695 "Refresh token does not belong to client",
696 ));
697 }
698
699 let requested_scopes = self.parse_scopes(request.scope.as_deref())?;
701 let authorized_scopes = if requested_scopes.is_empty() {
702 stored_token.scopes.clone() } else {
704 self.validate_scope_subset(&stored_token.scopes, &requested_scopes)?
705 };
706
707 drop(storage);
708
709 let access_token = self
711 .generate_access_token(
712 &stored_token.client_id,
713 Some(&stored_token.user_id), &authorized_scopes,
715 )
716 .await?;
717
718 let mut storage = self.token_storage.write().await;
720 storage.revoke_refresh_token(&refresh_token_id).await?; let new_refresh_token = RefreshToken::new(
723 stored_token.client_id.clone(),
724 stored_token.user_id.clone(),
725 authorized_scopes.clone(),
726 self.config.refresh_token_lifetime,
727 );
728
729 let new_refresh_token_id = storage.store_refresh_token(new_refresh_token).await?;
730
731 Ok(TokenResponse {
732 access_token: access_token.access_token,
733 token_type: "Bearer".to_string(),
734 expires_in: self.config.access_token_lifetime.as_secs(),
735 refresh_token: Some(new_refresh_token_id),
736 scope: Some(authorized_scopes.join(" ")),
737 id_token: None,
738 })
739 }
740
741 async fn handle_client_credentials_grant(
743 &self,
744 request: TokenRequest,
745 ) -> Result<TokenResponse> {
746 let client_id = request
747 .client_id
748 .ok_or_else(|| AuthError::auth_method("oauth2", "client_id is required"))?;
749 let storage = self.token_storage.read().await;
751 let client = storage
752 .get_client_credentials(&client_id)
753 .await?
754 .ok_or_else(|| AuthError::auth_method("oauth2", "Invalid client_id"))?;
755
756 if !storage
758 .validate_client_credentials(&client_id, request.client_secret.as_deref())
759 .await?
760 {
761 return Err(AuthError::auth_method(
762 "oauth2",
763 "Invalid client credentials",
764 ));
765 }
766
767 if !client.supports_grant_type("client_credentials") {
768 return Err(AuthError::auth_method(
769 "oauth2",
770 "Client does not support client credentials grant",
771 ));
772 }
773
774 let requested_scopes = self.parse_scopes(request.scope.as_deref())?;
776 let authorized_scopes = requested_scopes
777 .iter()
778 .filter(|scope| client.has_scope(scope))
779 .cloned()
780 .collect::<Vec<_>>();
781
782 if authorized_scopes.is_empty() && !requested_scopes.is_empty() {
783 return Err(AuthError::auth_method("oauth2", "No authorized scopes"));
784 }
785
786 drop(storage);
787
788 let access_token = self
790 .generate_access_token(&client_id, None, &authorized_scopes)
791 .await?;
792
793 Ok(TokenResponse {
794 access_token: access_token.access_token,
795 token_type: "Bearer".to_string(),
796 expires_in: self.config.access_token_lifetime.as_secs(),
797 refresh_token: None, scope: Some(authorized_scopes.join(" ")),
799 id_token: None,
800 })
801 }
802
803 async fn generate_access_token(
805 &self,
806 client_id: &str,
807 user_id: Option<&str>,
808 scopes: &[String],
809 ) -> Result<AuthToken> {
810 let subject = user_id.unwrap_or(client_id);
811 let mut token = self.token_manager.create_auth_token(
812 subject,
813 crate::types::Scopes::from(
814 scopes
815 .iter()
816 .map(|s| s.to_string())
817 .collect::<Vec<String>>(),
818 ),
819 "oauth2",
820 Some(self.config.access_token_lifetime),
821 )?;
822
823 token.add_custom_claim(
825 "client_id".to_string(),
826 serde_json::Value::String(client_id.to_string()),
827 );
828
829 if let Some(uid) = user_id {
831 token.add_custom_claim(
832 "user_id".to_string(),
833 serde_json::Value::String(uid.to_string()),
834 );
835 }
836
837 Ok(token)
838 }
839
840 fn parse_scopes(&self, scope_str: Option<&str>) -> Result<Vec<String>> {
842 match scope_str {
843 Some(scopes) => Ok(scopes.split_whitespace().map(|s| s.to_string()).collect()),
844 None => match &self.config.default_scope {
845 Some(default) => Ok(vec![default.clone()]),
846 None => Ok(vec![]),
847 },
848 }
849 }
850
851 fn authorize_scopes(
853 &self,
854 client: &EnhancedClientCredentials,
855 user_context: &UserContext,
856 requested_scopes: &[String],
857 ) -> Result<Vec<String>> {
858 let mut authorized = Vec::new();
859
860 for scope in requested_scopes {
861 if client.has_scope(scope) {
863 if user_context.has_scope(scope) {
865 authorized.push(scope.clone());
866 }
867 }
868 }
869
870 if authorized.is_empty() && !requested_scopes.is_empty() {
871 return Err(AuthError::auth_method("oauth2", "No authorized scopes"));
872 }
873
874 Ok(authorized)
875 }
876
877 fn validate_scope_subset(
879 &self,
880 original_scopes: &[String],
881 requested_scopes: &[String],
882 ) -> Result<Vec<String>> {
883 let mut validated = Vec::new();
884
885 for scope in requested_scopes {
886 if original_scopes.contains(scope) {
887 validated.push(scope.clone());
888 } else {
889 return Err(AuthError::auth_method(
890 "oauth2",
891 format!("Requested scope '{}' not in original grant", scope),
892 ));
893 }
894 }
895
896 Ok(validated)
897 }
898
899 fn validate_pkce_challenge(
901 &self,
902 challenge: &str,
903 verifier: &str,
904 method: &Option<String>,
905 ) -> Result<bool> {
906 let method = method.as_deref().unwrap_or("plain");
907
908 match method {
909 "plain" => Ok(constant_time_compare(
910 challenge.as_bytes(),
911 verifier.as_bytes(),
912 )),
913 "S256" => {
914 use base64::{Engine, engine::general_purpose::URL_SAFE_NO_PAD};
915 use sha2::{Digest, Sha256};
916
917 let hash = Sha256::digest(verifier.as_bytes());
918 let encoded = URL_SAFE_NO_PAD.encode(hash);
919 Ok(constant_time_compare(
920 challenge.as_bytes(),
921 encoded.as_bytes(),
922 ))
923 }
924 _ => Err(AuthError::auth_method("oauth2", "Unsupported PKCE method")),
925 }
926 }
927
928 pub async fn revoke_token(&self, token: &str, client_id: &str) -> Result<bool> {
930 let mut storage = self.token_storage.write().await;
931
932 if client_id.is_empty() {
934 return Err(AuthError::auth_method(
935 "oauth2",
936 "Client ID is required for token revocation",
937 ));
938 }
939
940 if storage.get_client_credentials(client_id).await.is_err() {
942 return Err(AuthError::auth_method("oauth2", "Invalid client"));
943 }
944
945 if storage.validate_refresh_token(token).await? {
947 return storage.revoke_refresh_token(token).await;
948 }
949
950 Ok(false)
953 }
954
955 pub async fn cleanup_expired_tokens(&self) -> Result<usize> {
957 let mut storage = self.token_storage.write().await;
958 storage.cleanup_expired_tokens().await
959 }
960
961 pub async fn add_user_credentials(
968 &self,
969 creds: crate::server::oauth::oauth2_enhanced_storage::UserCredentials,
970 ) -> Result<()> {
971 let mut storage = self.token_storage.write().await;
972 storage.store_user_credentials(creds).await
973 }
974
975 pub async fn authenticate_user(
977 &self,
978 username: &str,
979 password: &str,
980 scopes: Vec<String>,
981 ) -> Result<UserContext> {
982 let storage = self.token_storage.read().await;
984
985 if !self
987 .validate_user_credentials_against_storage(&storage, username, password)
988 .await?
989 {
990 return Err(AuthError::auth_method(
991 "oauth2",
992 "Invalid username or password",
993 ));
994 }
995
996 let authorized_scopes = self
998 .validate_user_scopes_against_storage(&storage, username, &scopes)
999 .await?;
1000
1001 drop(storage);
1002
1003 let user_context = UserContext::new(
1005 self.generate_user_id(username).await?,
1006 username.to_string(),
1007 self.get_user_email(username).await?,
1008 )
1009 .with_scopes(authorized_scopes);
1010
1011 let mut session_store = self.session_store.write().await;
1012 session_store.create_session(user_context.clone());
1013
1014 Ok(user_context)
1015 }
1016
1017 async fn validate_user_credentials_against_storage(
1019 &self,
1020 storage: &EnhancedTokenStorage,
1021 username: &str,
1022 password: &str,
1023 ) -> Result<bool> {
1024 let is_empty = username.is_empty() || password.is_empty();
1026 let is_too_short = password.len() < 8;
1027
1028 match storage.get_user_credentials(username).await {
1030 Ok(Some(stored_credentials)) => {
1031 use bcrypt::verify;
1033 match verify(password, &stored_credentials.password_hash) {
1034 Ok(is_valid) => {
1035 Ok(is_valid && !is_empty && !is_too_short)
1037 }
1038 Err(_) => {
1039 Ok(false)
1041 }
1042 }
1043 }
1044 Ok(None) => {
1045 use bcrypt::verify;
1047 let _dummy_result = verify(
1048 password,
1049 "$2b$12$K2CtDP7zMH7VgxScmHTa/.EUm5nd9.xnZM8Cl/p9RMb5QZaJUHgBm",
1050 );
1051 Ok(false)
1052 }
1053 Err(_) => {
1054 use bcrypt::verify;
1056 let _dummy_result = verify(
1057 password,
1058 "$2b$12$K2CtDP7zMH7VgxScmHTa/.EUm5nd9.xnZM8Cl/p9RMb5QZaJUHgBm",
1059 );
1060 Ok(false)
1061 }
1062 }
1063 }
1064
1065 async fn validate_user_scopes_against_storage(
1067 &self,
1068 storage: &EnhancedTokenStorage,
1069 username: &str,
1070 requested_scopes: &[String],
1071 ) -> Result<Vec<String>> {
1072 let user_permissions = match storage.get_user_permissions(username).await {
1074 Ok(Some(permissions)) => permissions.scopes,
1075 Ok(None) => {
1076 return Err(AuthError::auth_method(
1077 "oauth2",
1078 "User not found in permission store",
1079 ));
1080 }
1081 Err(_) => {
1082 return Err(AuthError::auth_method(
1083 "oauth2",
1084 "Failed to retrieve user permissions",
1085 ));
1086 }
1087 };
1088
1089 let mut authorized = Vec::new();
1090 for scope in requested_scopes {
1091 if user_permissions.contains(scope) {
1092 authorized.push(scope.clone());
1093 }
1094 }
1095
1096 if authorized.is_empty() && !requested_scopes.is_empty() {
1098 return Err(AuthError::auth_method(
1099 "oauth2",
1100 "User not authorized for requested scopes",
1101 ));
1102 }
1103
1104 if authorized.is_empty() {
1105 if user_permissions.contains(&"read".to_string()) {
1107 authorized.push("read".to_string());
1108 } else {
1109 return Err(AuthError::auth_method(
1110 "oauth2",
1111 "User has no authorized scopes",
1112 ));
1113 }
1114 }
1115
1116 Ok(authorized)
1117 }
1118
1119 async fn generate_user_id(&self, username: &str) -> Result<String> {
1121 let hash = Sha256::digest(format!("user_id_{}", username).as_bytes());
1124 let hash_str = format!("{:x}", hash);
1125 Ok(format!("user_{}", &hash_str[0..16]))
1126 }
1127
1128 async fn get_user_email(&self, username: &str) -> Result<Option<String>> {
1130 let storage = self.token_storage.read().await;
1131 match storage.get_user_credentials(username).await {
1132 Ok(Some(creds)) => Ok(creds.email),
1133 _ => Ok(None),
1135 }
1136 }
1137
1138 pub async fn get_user_context(&self, session_id: &str) -> Result<Option<UserContext>> {
1140 let session_store = self.session_store.read().await;
1141 Ok(session_store.get_session(session_id).cloned())
1142 }
1143
1144 pub async fn invalidate_session(&self, session_id: &str) -> Result<bool> {
1146 let mut session_store = self.session_store.write().await;
1147 Ok(session_store.invalidate_session(session_id))
1148 }
1149}