Skip to main content

auth_framework/tokens/
mod.rs

1//! Token management and validation for the authentication framework.
2use crate::errors::{AuthError, Result, TokenError};
3use crate::providers::{OAuthProvider, ProfileExtractor, UserProfile};
4use chrono::{DateTime, Utc};
5use jsonwebtoken::{Algorithm, DecodingKey, EncodingKey, Header, Validation, decode, encode};
6use serde::{Deserialize, Serialize};
7#[cfg(feature = "postgres-storage")]
8use sqlx::FromRow;
9use std::collections::HashMap;
10use std::time::Duration;
11use uuid::Uuid;
12
13/// Represents an authentication token with all associated metadata.
14#[cfg_attr(feature = "postgres-storage", derive(FromRow))]
15#[derive(Clone, Serialize, Deserialize)]
16pub struct AuthToken {
17    /// Unique token identifier
18    pub token_id: String,
19
20    /// User identifier this token belongs to
21    pub user_id: String,
22
23    /// Access token value
24    pub access_token: String,
25
26    /// Token type (e.g., "bearer")
27    pub token_type: Option<String>,
28
29    /// Subject claim
30    pub subject: Option<String>,
31
32    /// Token issuer
33    pub issuer: Option<String>,
34
35    /// Optional refresh token
36    pub refresh_token: Option<String>,
37
38    /// When the token was issued
39    pub issued_at: DateTime<Utc>,
40
41    /// When the token expires
42    pub expires_at: DateTime<Utc>,
43
44    /// Scopes granted to this token
45    pub scopes: Vec<String>,
46
47    /// Authentication method used to obtain this token
48    pub auth_method: String,
49
50    /// Client ID that requested this token
51    pub client_id: Option<String>,
52
53    /// User profile data (optional)
54    pub user_profile: Option<UserProfile>,
55
56    /// User's permissions
57    pub permissions: Vec<String>,
58
59    /// User's roles
60    pub roles: Vec<String>,
61
62    /// Additional token metadata
63    pub metadata: TokenMetadata,
64}
65
66impl std::fmt::Debug for AuthToken {
67    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
68        let mut d = f.debug_struct("AuthToken");
69        d.field("token_id", &self.token_id);
70        d.field("user_id", &self.user_id);
71        d.field(
72            "access_token",
73            &crate::utils::redact::redacted(&self.access_token),
74        );
75        d.field("token_type", &self.token_type);
76        d.field("subject", &self.subject);
77        d.field("issuer", &self.issuer);
78        d.field(
79            "refresh_token",
80            &crate::utils::redact::redacted(&self.refresh_token),
81        );
82        d.field("issued_at", &self.issued_at);
83        d.field("expires_at", &self.expires_at);
84        d.field("scopes", &self.scopes);
85        d.field("auth_method", &self.auth_method);
86        d.field("client_id", &self.client_id);
87        d.field("user_profile", &self.user_profile);
88        d.field("permissions", &self.permissions);
89        d.field("roles", &self.roles);
90        d.field("metadata", &self.metadata);
91        d.finish()
92    }
93}
94
95/// Additional metadata that can be attached to tokens.
96#[derive(Clone, Serialize, Deserialize, Default)]
97pub struct TokenMetadata {
98    /// IP address where the token was issued
99    pub issued_ip: Option<String>,
100
101    /// User agent of the client
102    pub user_agent: Option<String>,
103
104    /// Device identifier
105    pub device_id: Option<String>,
106
107    /// Session identifier
108    pub session_id: Option<String>,
109
110    /// Whether this token has been revoked
111    pub revoked: bool,
112
113    /// When the token was revoked (if applicable)
114    pub revoked_at: Option<DateTime<Utc>>,
115
116    /// Reason for revocation
117    pub revoked_reason: Option<String>,
118
119    /// Last time this token was used
120    pub last_used: Option<DateTime<Utc>>,
121
122    /// Number of times this token has been used
123    pub use_count: u64,
124
125    /// Custom metadata
126    pub custom: HashMap<String, serde_json::Value>,
127}
128
129impl std::fmt::Debug for TokenMetadata {
130    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
131        let mut d = f.debug_struct("TokenMetadata");
132        d.field("issued_ip", &self.issued_ip);
133        d.field("user_agent", &self.user_agent);
134        d.field("device_id", &self.device_id);
135        d.field(
136            "session_id",
137            &crate::utils::redact::redacted(&self.session_id),
138        );
139        d.field("revoked", &self.revoked);
140        d.field("revoked_at", &self.revoked_at);
141        d.field("revoked_reason", &self.revoked_reason);
142        d.field("last_used", &self.last_used);
143        d.field("use_count", &self.use_count);
144        d.field("custom", &crate::utils::redact::redacted(&self.custom));
145        d.finish()
146    }
147}
148
149#[cfg(feature = "postgres-storage")]
150use sqlx::{Decode, Postgres, Type, postgres::PgValueRef};
151
152#[cfg(feature = "postgres-storage")]
153impl<'r> Decode<'r, Postgres> for TokenMetadata {
154    fn decode(value: PgValueRef<'r>) -> std::result::Result<Self, sqlx::error::BoxDynError> {
155        let json: serde_json::Value = <serde_json::Value as Decode<Postgres>>::decode(value)?;
156        serde_json::from_value(json).map_err(|e| Box::new(e) as sqlx::error::BoxDynError)
157    }
158}
159
160#[cfg(feature = "postgres-storage")]
161impl Type<Postgres> for TokenMetadata {
162    fn type_info() -> sqlx::postgres::PgTypeInfo {
163        <serde_json::Value as Type<Postgres>>::type_info()
164    }
165    fn compatible(ty: &sqlx::postgres::PgTypeInfo) -> bool {
166        <serde_json::Value as Type<Postgres>>::compatible(ty)
167    }
168}
169
170/// Information about a user extracted from a token.
171#[derive(Debug, Clone, Serialize, Deserialize)]
172pub struct TokenInfo {
173    /// User identifier
174    pub user_id: String,
175
176    /// Username or email
177    pub username: Option<String>,
178
179    /// User's email address
180    pub email: Option<String>,
181
182    /// User's display name
183    pub name: Option<String>,
184
185    /// User's roles
186    pub roles: Vec<String>,
187
188    /// User's permissions
189    pub permissions: Vec<String>,
190
191    /// Additional user attributes
192    pub attributes: HashMap<String, serde_json::Value>,
193}
194
195/// JWT claims structure used internally.
196#[derive(Debug, Clone, Serialize, Deserialize)]
197pub struct JwtClaims {
198    /// Subject (user ID)
199    pub sub: String,
200
201    /// Issuer
202    pub iss: String,
203
204    /// Audience
205    pub aud: String,
206
207    /// Expiration time
208    pub exp: i64,
209
210    /// Issued at
211    pub iat: i64,
212
213    /// Not before
214    pub nbf: i64,
215
216    /// JWT ID
217    pub jti: String,
218
219    /// Scopes
220    pub scope: String,
221
222    /// User permissions
223    pub permissions: Option<Vec<String>>,
224
225    /// User roles
226    pub roles: Option<Vec<String>>,
227
228    /// Client ID
229    pub client_id: Option<String>,
230
231    /// Custom claims
232    #[serde(flatten)]
233    pub custom: HashMap<String, serde_json::Value>,
234}
235
236impl JwtClaims {
237    /// Name of the custom claim that says what a token may be used for.
238    pub const TOKEN_USE_CLAIM: &'static str = "token_use";
239    /// Value of [`TOKEN_USE_CLAIM`](Self::TOKEN_USE_CLAIM) on refresh tokens.
240    pub const TOKEN_USE_REFRESH: &'static str = "refresh";
241
242    /// `true` only for tokens minted by [`TokenManager::create_refresh_jwt_token`].
243    /// The `scope` string plays no part: a scope is permission data a user or client can
244    /// influence, this claim is not.
245    pub fn is_refresh_token(&self) -> bool {
246        self.custom
247            .get(Self::TOKEN_USE_CLAIM)
248            .and_then(|v| v.as_str())
249            == Some(Self::TOKEN_USE_REFRESH)
250    }
251}
252
253/// Token manager for creating, validating, and managing tokens.
254pub struct TokenManager {
255    /// JWT encoding key
256    encoding_key: EncodingKey,
257
258    /// JWT decoding key
259    decoding_key: DecodingKey,
260
261    /// Key material for recreating keys during clone
262    key_material: KeyMaterial,
263
264    /// JWT algorithm
265    algorithm: Algorithm,
266
267    /// Token issuer
268    issuer: String,
269
270    /// Token audience
271    audience: String,
272
273    /// Default token lifetime
274    default_lifetime: Duration,
275}
276
277/// Key material for cloning TokenManager
278#[derive(Clone)]
279enum KeyMaterial {
280    /// HMAC secret
281    Hmac(Vec<u8>),
282    /// RSA private and public keys
283    Rsa { private: Vec<u8>, public: Vec<u8> },
284}
285
286impl AuthToken {
287    /// Create a new authentication token.
288    pub fn new(
289        user_id: impl Into<String>,
290        access_token: impl Into<String>,
291        expires_in: std::time::Duration,
292        auth_method: impl Into<String>,
293    ) -> Self {
294        let now = Utc::now();
295        let expires_in_chrono =
296            chrono::Duration::from_std(expires_in).unwrap_or(chrono::Duration::hours(1));
297
298        Self {
299            token_id: Uuid::new_v4().to_string(),
300            user_id: user_id.into(),
301            access_token: access_token.into(),
302            refresh_token: None,
303            token_type: Some("Bearer".to_string()),
304            subject: None,
305            issuer: None,
306            issued_at: now,
307            expires_at: now + expires_in_chrono,
308            scopes: Vec::new(),
309            auth_method: auth_method.into(),
310            client_id: None,
311            user_profile: None,
312            permissions: Vec::new(),
313            roles: Vec::new(),
314            metadata: TokenMetadata::default(),
315        }
316    }
317
318    /// Get the access token string.
319    pub fn access_token(&self) -> &str {
320        &self.access_token
321    }
322
323    /// Get the user ID.
324    pub fn user_id(&self) -> &str {
325        &self.user_id
326    }
327
328    /// Get the expiration time.
329    pub fn expires_at(&self) -> DateTime<Utc> {
330        self.expires_at
331    }
332
333    /// Get the token value
334    pub fn token_value(&self) -> &str {
335        &self.access_token
336    }
337
338    /// Get the token type
339    pub fn token_type(&self) -> Option<&str> {
340        self.token_type.as_deref()
341    }
342
343    /// Get the subject claim
344    pub fn subject(&self) -> Option<&str> {
345        self.subject.as_deref()
346    }
347
348    /// Get the issuer
349    pub fn issuer(&self) -> Option<&str> {
350        self.issuer.as_deref()
351    }
352
353    /// Check if the token has expired.
354    pub fn is_expired(&self) -> bool {
355        Utc::now() > self.expires_at
356    }
357
358    /// Check if the token is expiring within the given duration.
359    pub fn is_expiring(&self, within: Duration) -> bool {
360        Utc::now() + within > self.expires_at
361    }
362
363    /// Check if the token has been revoked.
364    pub fn is_revoked(&self) -> bool {
365        self.metadata.revoked
366    }
367
368    /// Check if the token is valid (not expired and not revoked).
369    pub fn is_valid(&self) -> bool {
370        !self.is_expired() && !self.is_revoked()
371    }
372
373    /// Revoke the token.
374    pub fn revoke(&mut self, reason: Option<String>) {
375        self.metadata.revoked = true;
376        self.metadata.revoked_at = Some(Utc::now());
377        self.metadata.revoked_reason = reason;
378    }
379
380    /// Update the last used time and increment use count.
381    pub fn mark_used(&mut self) {
382        self.metadata.last_used = Some(Utc::now());
383        self.metadata.use_count += 1;
384    }
385
386    /// Add a scope to the token.
387    pub fn add_scope(&mut self, scope: impl Into<String>) {
388        let scope = scope.into();
389        if !self.scopes.contains(&scope) {
390            self.scopes.push(scope);
391        }
392    }
393
394    /// Check if the token has a specific scope.
395    pub fn has_scope(&self, scope: &str) -> bool {
396        self.scopes.contains(&scope.to_string())
397    }
398
399    /// Set the refresh token.
400    pub fn with_refresh_token(mut self, refresh_token: impl Into<String>) -> Self {
401        self.refresh_token = Some(refresh_token.into());
402        self
403    }
404
405    /// Set the client ID.
406    pub fn with_client_id(mut self, client_id: impl Into<String>) -> Self {
407        self.client_id = Some(client_id.into());
408        self
409    }
410
411    /// Set the token scopes.
412    pub fn with_scopes(mut self, scopes: Vec<String>) -> Self {
413        self.scopes = scopes;
414        self
415    }
416
417    /// Add metadata to the token.
418    pub fn with_metadata(mut self, metadata: TokenMetadata) -> Self {
419        self.metadata = metadata;
420        self
421    }
422
423    /// Get time until expiration.
424    pub fn time_until_expiry(&self) -> Duration {
425        let now = Utc::now();
426        if self.expires_at > now {
427            (self.expires_at - now).to_std().unwrap_or(Duration::ZERO)
428        } else {
429            Duration::ZERO
430        }
431    }
432
433    /// Add a custom claim to the token metadata
434    pub fn add_custom_claim(&mut self, key: impl Into<String>, value: serde_json::Value) {
435        self.metadata.custom.insert(key.into(), value);
436    }
437
438    /// Get a custom claim from the token metadata
439    pub fn get_custom_claim(&self, key: &str) -> Option<&serde_json::Value> {
440        self.metadata.custom.get(key)
441    }
442
443    /// Check if the token has a specific permission
444    pub fn has_permission(&self, permission: &str) -> bool {
445        self.permissions.contains(&permission.to_string())
446    }
447
448    /// Add a permission to the token
449    pub fn add_permission(&mut self, permission: impl Into<String>) {
450        let permission = permission.into();
451        if !self.permissions.contains(&permission) {
452            self.permissions.push(permission);
453        }
454    }
455
456    /// Add a role to the token
457    pub fn add_role(&mut self, role: impl Into<String>) {
458        let role = role.into();
459        if !self.roles.contains(&role) {
460            self.roles.push(role);
461        }
462    }
463
464    /// Check if the token has a specific role
465    pub fn has_role(&self, role: &str) -> bool {
466        self.roles.contains(&role.to_string())
467    }
468
469    /// Set the permissions
470    pub fn with_permissions(mut self, permissions: Vec<String>) -> Self {
471        self.permissions = permissions;
472        self
473    }
474
475    /// Set the roles
476    pub fn with_roles(mut self, roles: Vec<String>) -> Self {
477        self.roles = roles;
478        self
479    }
480}
481
482impl Clone for TokenManager {
483    fn clone(&self) -> Self {
484        match &self.key_material {
485            KeyMaterial::Hmac(secret) => Self {
486                encoding_key: EncodingKey::from_secret(secret),
487                decoding_key: DecodingKey::from_secret(secret),
488                key_material: self.key_material.clone(),
489                algorithm: self.algorithm,
490                issuer: self.issuer.clone(),
491                audience: self.audience.clone(),
492                default_lifetime: self.default_lifetime,
493            },
494            KeyMaterial::Rsa { private, public } => Self {
495                encoding_key: EncodingKey::from_rsa_pem(private).expect("Valid RSA private key"),
496                decoding_key: DecodingKey::from_rsa_pem(public).expect("Valid RSA public key"),
497                key_material: self.key_material.clone(),
498                algorithm: self.algorithm,
499                issuer: self.issuer.clone(),
500                audience: self.audience.clone(),
501                default_lifetime: self.default_lifetime,
502            },
503        }
504    }
505}
506
507impl TokenManager {
508    /// Create a new token manager with HMAC key.
509    pub fn new_hmac(secret: &[u8], issuer: impl Into<String>, audience: impl Into<String>) -> Self {
510        Self {
511            encoding_key: EncodingKey::from_secret(secret),
512            decoding_key: DecodingKey::from_secret(secret),
513            key_material: KeyMaterial::Hmac(secret.to_vec()),
514            algorithm: Algorithm::HS256,
515            issuer: issuer.into(),
516            audience: audience.into(),
517            default_lifetime: Duration::from_secs(3600), // 1 hour
518        }
519    }
520
521    /// Create a new token manager with RSA keys.
522    ///
523    /// ## RSA Key Format Support
524    ///
525    /// This method supports RSA keys in both standard PEM formats:
526    /// - **PKCS#1**: `-----BEGIN RSA PRIVATE KEY-----` (traditional RSA format)
527    /// - **PKCS#8**: `-----BEGIN PRIVATE KEY-----` (modern standard format, recommended)
528    ///
529    /// Both formats are automatically detected and parsed. No format conversion is required.
530    ///
531    /// ## Example
532    ///
533    /// ```rust,no_run
534    /// use auth_framework::tokens::TokenManager;
535    ///
536    /// // Both PKCS#1 and PKCS#8 formats work; provide PEM bytes from your key store.
537    /// # let private_key: &[u8] = b"";
538    /// # let public_key: &[u8] = b"";
539    ///
540    /// let manager = TokenManager::new_rsa(
541    ///     private_key,
542    ///     public_key,
543    ///     "my-service",
544    ///     "my-audience"
545    /// )?;
546    /// # Ok::<(), auth_framework::errors::AuthError>(())
547    /// ```
548    pub fn new_rsa(
549        private_key: &[u8],
550        public_key: &[u8],
551        issuer: impl Into<String>,
552        audience: impl Into<String>,
553    ) -> Result<Self> {
554        let encoding_key = EncodingKey::from_rsa_pem(private_key)
555            .map_err(|e| AuthError::crypto(format!("Invalid RSA private key: {e}")))?;
556
557        let decoding_key = DecodingKey::from_rsa_pem(public_key)
558            .map_err(|e| AuthError::crypto(format!("Invalid RSA public key: {e}")))?;
559
560        Ok(Self {
561            encoding_key,
562            decoding_key,
563            key_material: KeyMaterial::Rsa {
564                private: private_key.to_vec(),
565                public: public_key.to_vec(),
566            },
567            algorithm: Algorithm::RS256,
568            issuer: issuer.into(),
569            audience: audience.into(),
570            default_lifetime: Duration::from_secs(3600), // 1 hour
571        })
572    }
573
574    /// Set the default token lifetime.
575    pub fn with_default_lifetime(mut self, lifetime: Duration) -> Self {
576        self.default_lifetime = lifetime;
577        self
578    }
579
580    /// Create a new JWT token.
581    pub fn create_jwt_token(
582        &self,
583        user_id: impl Into<String>,
584        scopes: Vec<String>,
585        lifetime: Option<Duration>,
586    ) -> Result<String> {
587        self.encode_jwt(user_id.into(), scopes, lifetime, None)
588    }
589
590    /// Create a JWT that is a refresh token: it carries `token_use: "refresh"`, which
591    /// `/auth/refresh` requires and which an access token never has.
592    pub fn create_refresh_jwt_token(
593        &self,
594        user_id: impl Into<String>,
595        lifetime: Option<Duration>,
596    ) -> Result<String> {
597        self.encode_jwt(
598            user_id.into(),
599            vec!["refresh".to_string()],
600            lifetime,
601            Some(JwtClaims::TOKEN_USE_REFRESH),
602        )
603    }
604
605    fn encode_jwt(
606        &self,
607        user_id: String,
608        scopes: Vec<String>,
609        lifetime: Option<Duration>,
610        token_use: Option<&str>,
611    ) -> Result<String> {
612        let lifetime = lifetime.unwrap_or(self.default_lifetime);
613        let now = Utc::now();
614        let exp = now + chrono::Duration::from_std(lifetime).unwrap_or(chrono::Duration::hours(1));
615
616        let mut custom = HashMap::new();
617        if let Some(token_use) = token_use {
618            custom.insert(
619                JwtClaims::TOKEN_USE_CLAIM.to_string(),
620                serde_json::Value::String(token_use.to_string()),
621            );
622        }
623        let claims = JwtClaims {
624            sub: user_id,
625            iss: self.issuer.clone(),
626            aud: self.audience.clone(),
627            exp: exp.timestamp(),
628            iat: now.timestamp(),
629            nbf: now.timestamp(),
630            jti: Uuid::new_v4().to_string(),
631            scope: scopes.join(" "),
632            permissions: None,
633            roles: None,
634            client_id: None,
635            custom,
636        };
637
638        let header = Header::new(self.algorithm);
639
640        encode(&header, &claims, &self.encoding_key)
641            .map_err(|e| TokenError::creation_failed(format!("JWT encoding failed: {e}")).into())
642    }
643
644    /// Validate and decode a JWT token.
645    pub fn validate_jwt_token(&self, token: &str) -> Result<JwtClaims> {
646        let mut validation = Validation::new(self.algorithm);
647        validation.set_issuer(&[&self.issuer]);
648        validation.set_audience(&[&self.audience]);
649
650        let token_data =
651            decode::<JwtClaims>(token, &self.decoding_key, &validation).map_err(|e| {
652                match e.kind() {
653                    jsonwebtoken::errors::ErrorKind::ExpiredSignature => {
654                        AuthError::Token(TokenError::Expired)
655                    }
656                    kind => {
657                        // The caller gets one opaque message so a client learns nothing about why a
658                        // token was refused; the operator gets the cause. The token is never logged.
659                        tracing::debug!(cause = ?kind, "JWT validation failed");
660                        AuthError::Token(TokenError::Invalid {
661                            message: "Invalid token format".to_string(),
662                        })
663                    }
664                }
665            })?;
666
667        Ok(token_data.claims)
668    }
669
670    /// Create a complete authentication token with JWT.
671    pub fn create_auth_token(
672        &self,
673        user_id: impl Into<String>,
674        scopes: Vec<String>,
675        auth_method: impl Into<String>,
676        lifetime: Option<std::time::Duration>,
677    ) -> Result<AuthToken> {
678        let user_id_str = user_id.into();
679        let lifetime = lifetime.unwrap_or(self.default_lifetime);
680
681        let jwt_token = self.create_jwt_token(&user_id_str, scopes.clone(), Some(lifetime))?;
682
683        let token =
684            AuthToken::new(user_id_str, jwt_token, lifetime, auth_method).with_scopes(scopes);
685
686        Ok(token)
687    }
688
689    /// Validate an authentication token.
690    pub fn validate_auth_token(&self, token: &AuthToken) -> Result<()> {
691        // Check if token is expired
692        if token.is_expired() {
693            return Err(TokenError::Expired.into());
694        }
695
696        // Check if token is revoked
697        if token.is_revoked() {
698            return Err(TokenError::Invalid {
699                message: "Token has been revoked".to_string(),
700            }
701            .into());
702        }
703
704        // Validate JWT if it's a JWT token
705        if token.auth_method == "jwt" || token.access_token.contains('.') {
706            self.validate_jwt_token(&token.access_token)?;
707        }
708
709        Ok(())
710    }
711
712    /// Refresh a token (create a new one with extended lifetime).
713    pub fn refresh_token(&self, token: &AuthToken) -> Result<AuthToken> {
714        if token.is_expired() {
715            return Err(TokenError::Expired.into());
716        }
717
718        if token.is_revoked() {
719            return Err(TokenError::Invalid {
720                message: "Cannot refresh revoked token".to_string(),
721            }
722            .into());
723        }
724
725        // Create a new token with the same properties but new expiry
726        self.create_auth_token(
727            &token.user_id,
728            token.scopes.clone(),
729            &token.auth_method,
730            Some(self.default_lifetime),
731        )
732    }
733
734    /// Extract token information from a JWT.
735    pub fn extract_token_info(&self, token: &str) -> Result<TokenInfo> {
736        let claims = self.validate_jwt_token(token)?;
737
738        Ok(TokenInfo {
739            user_id: claims.sub,
740            username: claims
741                .custom
742                .get("username")
743                .and_then(|v| v.as_str())
744                .map(|s| s.to_string()),
745            email: claims
746                .custom
747                .get("email")
748                .and_then(|v| v.as_str())
749                .map(|s| s.to_string()),
750            name: claims
751                .custom
752                .get("name")
753                .and_then(|v| v.as_str())
754                .map(|s| s.to_string()),
755            roles: claims
756                .custom
757                .get("roles")
758                .and_then(|v| v.as_array())
759                .map(|arr| {
760                    arr.iter()
761                        .filter_map(|v| v.as_str())
762                        .map(|s| s.to_string())
763                        .collect()
764                })
765                .unwrap_or_default(),
766            permissions: claims
767                .scope
768                .split_whitespace()
769                .map(|s| s.to_string())
770                .collect(),
771            attributes: claims.custom,
772        })
773    }
774}
775
776/// Trait for converting tokens to user profiles
777#[async_trait::async_trait]
778pub trait TokenToProfile {
779    /// Convert this token to a user profile using the specified provider
780    async fn to_profile(&self, provider: &OAuthProvider) -> Result<UserProfile>;
781
782    /// Convert this token to a user profile with a custom extractor
783    async fn to_profile_with_extractor(
784        &self,
785        provider: &OAuthProvider,
786        extractor: &ProfileExtractor,
787    ) -> Result<UserProfile>;
788}
789
790#[async_trait::async_trait]
791impl TokenToProfile for AuthToken {
792    async fn to_profile(&self, provider: &OAuthProvider) -> Result<UserProfile> {
793        let extractor = ProfileExtractor::new();
794        extractor.extract_profile(self, provider).await
795    }
796
797    async fn to_profile_with_extractor(
798        &self,
799        provider: &OAuthProvider,
800        extractor: &ProfileExtractor,
801    ) -> Result<UserProfile> {
802        extractor.extract_profile(self, provider).await
803    }
804}
805
806#[cfg(test)]
807mod tests {
808    use super::*;
809
810    #[test]
811    fn test_auth_token_creation() {
812        let token = AuthToken::new(
813            "user123",
814            "token123",
815            Duration::from_secs(3600), // 1 hour
816            "password",
817        );
818
819        assert_eq!(token.user_id(), "user123");
820        assert_eq!(token.access_token(), "token123");
821        assert!(!token.is_expired());
822        assert!(!token.is_revoked());
823        assert!(token.is_valid());
824    }
825
826    #[test]
827    fn test_token_expiry() {
828        let token = AuthToken::new("user123", "token123", Duration::from_millis(1), "password");
829
830        // Wait a bit to ensure expiry
831        std::thread::sleep(std::time::Duration::from_millis(10));
832
833        assert!(token.is_expired());
834        assert!(!token.is_valid());
835    }
836
837    #[test]
838    fn test_token_revocation() {
839        let mut token = AuthToken::new(
840            "user123",
841            "token123",
842            Duration::from_secs(3600), // 1 hour
843            "password",
844        );
845
846        assert!(!token.is_revoked());
847
848        token.revoke(Some("User logout".to_string()));
849
850        assert!(token.is_revoked());
851        assert!(!token.is_valid());
852        assert!(token.metadata.revoked);
853    }
854}