1use 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#[cfg_attr(feature = "postgres-storage", derive(FromRow))]
15#[derive(Debug, Clone, Serialize, Deserialize)]
16pub struct AuthToken {
17 pub token_id: String,
19
20 pub user_id: String,
22
23 pub access_token: String,
25
26 pub token_type: Option<String>,
28
29 pub subject: Option<String>,
31
32 pub issuer: Option<String>,
34
35 pub refresh_token: Option<String>,
37
38 pub issued_at: DateTime<Utc>,
40
41 pub expires_at: DateTime<Utc>,
43
44 pub scopes: Vec<String>,
46
47 pub auth_method: String,
49
50 pub client_id: Option<String>,
52
53 pub user_profile: Option<UserProfile>,
55
56 pub permissions: Vec<String>,
58
59 pub roles: Vec<String>,
61
62 pub metadata: TokenMetadata,
64}
65
66#[derive(Debug, Clone, Serialize, Deserialize, Default)]
68pub struct TokenMetadata {
69 pub issued_ip: Option<String>,
71
72 pub user_agent: Option<String>,
74
75 pub device_id: Option<String>,
77
78 pub session_id: Option<String>,
80
81 pub revoked: bool,
83
84 pub revoked_at: Option<DateTime<Utc>>,
86
87 pub revoked_reason: Option<String>,
89
90 pub last_used: Option<DateTime<Utc>>,
92
93 pub use_count: u64,
95
96 pub custom: HashMap<String, serde_json::Value>,
98}
99
100#[cfg(feature = "postgres-storage")]
101use sqlx::{Decode, Postgres, Type, postgres::PgValueRef};
102
103#[cfg(feature = "postgres-storage")]
104impl<'r> Decode<'r, Postgres> for TokenMetadata {
105 fn decode(value: PgValueRef<'r>) -> std::result::Result<Self, sqlx::error::BoxDynError> {
106 let json: serde_json::Value = <serde_json::Value as Decode<Postgres>>::decode(value)?;
107 serde_json::from_value(json).map_err(|e| Box::new(e) as sqlx::error::BoxDynError)
108 }
109}
110
111#[cfg(feature = "postgres-storage")]
112impl Type<Postgres> for TokenMetadata {
113 fn type_info() -> sqlx::postgres::PgTypeInfo {
114 <serde_json::Value as Type<Postgres>>::type_info()
115 }
116 fn compatible(ty: &sqlx::postgres::PgTypeInfo) -> bool {
117 <serde_json::Value as Type<Postgres>>::compatible(ty)
118 }
119}
120
121#[derive(Debug, Clone, Serialize, Deserialize)]
123pub struct TokenInfo {
124 pub user_id: String,
126
127 pub username: Option<String>,
129
130 pub email: Option<String>,
132
133 pub name: Option<String>,
135
136 pub roles: Vec<String>,
138
139 pub permissions: Vec<String>,
141
142 pub attributes: HashMap<String, serde_json::Value>,
144}
145
146#[derive(Debug, Clone, Serialize, Deserialize)]
148pub struct JwtClaims {
149 pub sub: String,
151
152 pub iss: String,
154
155 pub aud: String,
157
158 pub exp: i64,
160
161 pub iat: i64,
163
164 pub nbf: i64,
166
167 pub jti: String,
169
170 pub scope: String,
172
173 pub permissions: Option<Vec<String>>,
175
176 pub roles: Option<Vec<String>>,
178
179 pub client_id: Option<String>,
181
182 #[serde(flatten)]
184 pub custom: HashMap<String, serde_json::Value>,
185}
186
187impl JwtClaims {
188 pub const TOKEN_USE_CLAIM: &'static str = "token_use";
190 pub const TOKEN_USE_REFRESH: &'static str = "refresh";
192
193 pub fn is_refresh_token(&self) -> bool {
197 self.custom
198 .get(Self::TOKEN_USE_CLAIM)
199 .and_then(|v| v.as_str())
200 == Some(Self::TOKEN_USE_REFRESH)
201 }
202}
203
204pub struct TokenManager {
206 encoding_key: EncodingKey,
208
209 decoding_key: DecodingKey,
211
212 key_material: KeyMaterial,
214
215 algorithm: Algorithm,
217
218 issuer: String,
220
221 audience: String,
223
224 default_lifetime: Duration,
226}
227
228#[derive(Clone)]
230enum KeyMaterial {
231 Hmac(Vec<u8>),
233 Rsa { private: Vec<u8>, public: Vec<u8> },
235}
236
237impl AuthToken {
238 pub fn new(
240 user_id: impl Into<String>,
241 access_token: impl Into<String>,
242 expires_in: std::time::Duration,
243 auth_method: impl Into<String>,
244 ) -> Self {
245 let now = Utc::now();
246 let expires_in_chrono =
247 chrono::Duration::from_std(expires_in).unwrap_or(chrono::Duration::hours(1));
248
249 Self {
250 token_id: Uuid::new_v4().to_string(),
251 user_id: user_id.into(),
252 access_token: access_token.into(),
253 refresh_token: None,
254 token_type: Some("Bearer".to_string()),
255 subject: None,
256 issuer: None,
257 issued_at: now,
258 expires_at: now + expires_in_chrono,
259 scopes: Vec::new(),
260 auth_method: auth_method.into(),
261 client_id: None,
262 user_profile: None,
263 permissions: Vec::new(),
264 roles: Vec::new(),
265 metadata: TokenMetadata::default(),
266 }
267 }
268
269 pub fn access_token(&self) -> &str {
271 &self.access_token
272 }
273
274 pub fn user_id(&self) -> &str {
276 &self.user_id
277 }
278
279 pub fn expires_at(&self) -> DateTime<Utc> {
281 self.expires_at
282 }
283
284 pub fn token_value(&self) -> &str {
286 &self.access_token
287 }
288
289 pub fn token_type(&self) -> Option<&str> {
291 self.token_type.as_deref()
292 }
293
294 pub fn subject(&self) -> Option<&str> {
296 self.subject.as_deref()
297 }
298
299 pub fn issuer(&self) -> Option<&str> {
301 self.issuer.as_deref()
302 }
303
304 pub fn is_expired(&self) -> bool {
306 Utc::now() > self.expires_at
307 }
308
309 pub fn is_expiring(&self, within: Duration) -> bool {
311 Utc::now() + within > self.expires_at
312 }
313
314 pub fn is_revoked(&self) -> bool {
316 self.metadata.revoked
317 }
318
319 pub fn is_valid(&self) -> bool {
321 !self.is_expired() && !self.is_revoked()
322 }
323
324 pub fn revoke(&mut self, reason: Option<String>) {
326 self.metadata.revoked = true;
327 self.metadata.revoked_at = Some(Utc::now());
328 self.metadata.revoked_reason = reason;
329 }
330
331 pub fn mark_used(&mut self) {
333 self.metadata.last_used = Some(Utc::now());
334 self.metadata.use_count += 1;
335 }
336
337 pub fn add_scope(&mut self, scope: impl Into<String>) {
339 let scope = scope.into();
340 if !self.scopes.contains(&scope) {
341 self.scopes.push(scope);
342 }
343 }
344
345 pub fn has_scope(&self, scope: &str) -> bool {
347 self.scopes.contains(&scope.to_string())
348 }
349
350 pub fn with_refresh_token(mut self, refresh_token: impl Into<String>) -> Self {
352 self.refresh_token = Some(refresh_token.into());
353 self
354 }
355
356 pub fn with_client_id(mut self, client_id: impl Into<String>) -> Self {
358 self.client_id = Some(client_id.into());
359 self
360 }
361
362 pub fn with_scopes(mut self, scopes: Vec<String>) -> Self {
364 self.scopes = scopes;
365 self
366 }
367
368 pub fn with_metadata(mut self, metadata: TokenMetadata) -> Self {
370 self.metadata = metadata;
371 self
372 }
373
374 pub fn time_until_expiry(&self) -> Duration {
376 let now = Utc::now();
377 if self.expires_at > now {
378 (self.expires_at - now).to_std().unwrap_or(Duration::ZERO)
379 } else {
380 Duration::ZERO
381 }
382 }
383
384 pub fn add_custom_claim(&mut self, key: impl Into<String>, value: serde_json::Value) {
386 self.metadata.custom.insert(key.into(), value);
387 }
388
389 pub fn get_custom_claim(&self, key: &str) -> Option<&serde_json::Value> {
391 self.metadata.custom.get(key)
392 }
393
394 pub fn has_permission(&self, permission: &str) -> bool {
396 self.permissions.contains(&permission.to_string())
397 }
398
399 pub fn add_permission(&mut self, permission: impl Into<String>) {
401 let permission = permission.into();
402 if !self.permissions.contains(&permission) {
403 self.permissions.push(permission);
404 }
405 }
406
407 pub fn add_role(&mut self, role: impl Into<String>) {
409 let role = role.into();
410 if !self.roles.contains(&role) {
411 self.roles.push(role);
412 }
413 }
414
415 pub fn has_role(&self, role: &str) -> bool {
417 self.roles.contains(&role.to_string())
418 }
419
420 pub fn with_permissions(mut self, permissions: Vec<String>) -> Self {
422 self.permissions = permissions;
423 self
424 }
425
426 pub fn with_roles(mut self, roles: Vec<String>) -> Self {
428 self.roles = roles;
429 self
430 }
431}
432
433impl Clone for TokenManager {
434 fn clone(&self) -> Self {
435 match &self.key_material {
436 KeyMaterial::Hmac(secret) => Self {
437 encoding_key: EncodingKey::from_secret(secret),
438 decoding_key: DecodingKey::from_secret(secret),
439 key_material: self.key_material.clone(),
440 algorithm: self.algorithm,
441 issuer: self.issuer.clone(),
442 audience: self.audience.clone(),
443 default_lifetime: self.default_lifetime,
444 },
445 KeyMaterial::Rsa { private, public } => Self {
446 encoding_key: EncodingKey::from_rsa_pem(private).expect("Valid RSA private key"),
447 decoding_key: DecodingKey::from_rsa_pem(public).expect("Valid RSA public key"),
448 key_material: self.key_material.clone(),
449 algorithm: self.algorithm,
450 issuer: self.issuer.clone(),
451 audience: self.audience.clone(),
452 default_lifetime: self.default_lifetime,
453 },
454 }
455 }
456}
457
458impl TokenManager {
459 pub fn new_hmac(secret: &[u8], issuer: impl Into<String>, audience: impl Into<String>) -> Self {
461 Self {
462 encoding_key: EncodingKey::from_secret(secret),
463 decoding_key: DecodingKey::from_secret(secret),
464 key_material: KeyMaterial::Hmac(secret.to_vec()),
465 algorithm: Algorithm::HS256,
466 issuer: issuer.into(),
467 audience: audience.into(),
468 default_lifetime: Duration::from_secs(3600), }
470 }
471
472 pub fn new_rsa(
500 private_key: &[u8],
501 public_key: &[u8],
502 issuer: impl Into<String>,
503 audience: impl Into<String>,
504 ) -> Result<Self> {
505 let encoding_key = EncodingKey::from_rsa_pem(private_key)
506 .map_err(|e| AuthError::crypto(format!("Invalid RSA private key: {e}")))?;
507
508 let decoding_key = DecodingKey::from_rsa_pem(public_key)
509 .map_err(|e| AuthError::crypto(format!("Invalid RSA public key: {e}")))?;
510
511 Ok(Self {
512 encoding_key,
513 decoding_key,
514 key_material: KeyMaterial::Rsa {
515 private: private_key.to_vec(),
516 public: public_key.to_vec(),
517 },
518 algorithm: Algorithm::RS256,
519 issuer: issuer.into(),
520 audience: audience.into(),
521 default_lifetime: Duration::from_secs(3600), })
523 }
524
525 pub fn with_default_lifetime(mut self, lifetime: Duration) -> Self {
527 self.default_lifetime = lifetime;
528 self
529 }
530
531 pub fn create_jwt_token(
533 &self,
534 user_id: impl Into<String>,
535 scopes: Vec<String>,
536 lifetime: Option<Duration>,
537 ) -> Result<String> {
538 self.encode_jwt(user_id.into(), scopes, lifetime, None)
539 }
540
541 pub fn create_refresh_jwt_token(
544 &self,
545 user_id: impl Into<String>,
546 lifetime: Option<Duration>,
547 ) -> Result<String> {
548 self.encode_jwt(
549 user_id.into(),
550 vec!["refresh".to_string()],
551 lifetime,
552 Some(JwtClaims::TOKEN_USE_REFRESH),
553 )
554 }
555
556 fn encode_jwt(
557 &self,
558 user_id: String,
559 scopes: Vec<String>,
560 lifetime: Option<Duration>,
561 token_use: Option<&str>,
562 ) -> Result<String> {
563 let lifetime = lifetime.unwrap_or(self.default_lifetime);
564 let now = Utc::now();
565 let exp = now + chrono::Duration::from_std(lifetime).unwrap_or(chrono::Duration::hours(1));
566
567 let mut custom = HashMap::new();
568 if let Some(token_use) = token_use {
569 custom.insert(
570 JwtClaims::TOKEN_USE_CLAIM.to_string(),
571 serde_json::Value::String(token_use.to_string()),
572 );
573 }
574 let claims = JwtClaims {
575 sub: user_id,
576 iss: self.issuer.clone(),
577 aud: self.audience.clone(),
578 exp: exp.timestamp(),
579 iat: now.timestamp(),
580 nbf: now.timestamp(),
581 jti: Uuid::new_v4().to_string(),
582 scope: scopes.join(" "),
583 permissions: None,
584 roles: None,
585 client_id: None,
586 custom,
587 };
588
589 let header = Header::new(self.algorithm);
590
591 encode(&header, &claims, &self.encoding_key)
592 .map_err(|e| TokenError::creation_failed(format!("JWT encoding failed: {e}")).into())
593 }
594
595 pub fn validate_jwt_token(&self, token: &str) -> Result<JwtClaims> {
597 let mut validation = Validation::new(self.algorithm);
598 validation.set_issuer(&[&self.issuer]);
599 validation.set_audience(&[&self.audience]);
600
601 let token_data =
602 decode::<JwtClaims>(token, &self.decoding_key, &validation).map_err(|e| {
603 match e.kind() {
604 jsonwebtoken::errors::ErrorKind::ExpiredSignature => {
605 AuthError::Token(TokenError::Expired)
606 }
607 _ => AuthError::Token(TokenError::Invalid {
608 message: "Invalid token format".to_string(),
609 }),
610 }
611 })?;
612
613 Ok(token_data.claims)
614 }
615
616 pub fn create_auth_token(
618 &self,
619 user_id: impl Into<String>,
620 scopes: Vec<String>,
621 auth_method: impl Into<String>,
622 lifetime: Option<std::time::Duration>,
623 ) -> Result<AuthToken> {
624 let user_id_str = user_id.into();
625 let lifetime = lifetime.unwrap_or(self.default_lifetime);
626
627 let jwt_token = self.create_jwt_token(&user_id_str, scopes.clone(), Some(lifetime))?;
628
629 let token =
630 AuthToken::new(user_id_str, jwt_token, lifetime, auth_method).with_scopes(scopes);
631
632 Ok(token)
633 }
634
635 pub fn validate_auth_token(&self, token: &AuthToken) -> Result<()> {
637 if token.is_expired() {
639 return Err(TokenError::Expired.into());
640 }
641
642 if token.is_revoked() {
644 return Err(TokenError::Invalid {
645 message: "Token has been revoked".to_string(),
646 }
647 .into());
648 }
649
650 if token.auth_method == "jwt" || token.access_token.contains('.') {
652 self.validate_jwt_token(&token.access_token)?;
653 }
654
655 Ok(())
656 }
657
658 pub fn refresh_token(&self, token: &AuthToken) -> Result<AuthToken> {
660 if token.is_expired() {
661 return Err(TokenError::Expired.into());
662 }
663
664 if token.is_revoked() {
665 return Err(TokenError::Invalid {
666 message: "Cannot refresh revoked token".to_string(),
667 }
668 .into());
669 }
670
671 self.create_auth_token(
673 &token.user_id,
674 token.scopes.clone(),
675 &token.auth_method,
676 Some(self.default_lifetime),
677 )
678 }
679
680 pub fn extract_token_info(&self, token: &str) -> Result<TokenInfo> {
682 let claims = self.validate_jwt_token(token)?;
683
684 Ok(TokenInfo {
685 user_id: claims.sub,
686 username: claims
687 .custom
688 .get("username")
689 .and_then(|v| v.as_str())
690 .map(|s| s.to_string()),
691 email: claims
692 .custom
693 .get("email")
694 .and_then(|v| v.as_str())
695 .map(|s| s.to_string()),
696 name: claims
697 .custom
698 .get("name")
699 .and_then(|v| v.as_str())
700 .map(|s| s.to_string()),
701 roles: claims
702 .custom
703 .get("roles")
704 .and_then(|v| v.as_array())
705 .map(|arr| {
706 arr.iter()
707 .filter_map(|v| v.as_str())
708 .map(|s| s.to_string())
709 .collect()
710 })
711 .unwrap_or_default(),
712 permissions: claims
713 .scope
714 .split_whitespace()
715 .map(|s| s.to_string())
716 .collect(),
717 attributes: claims.custom,
718 })
719 }
720}
721
722#[async_trait::async_trait]
724pub trait TokenToProfile {
725 async fn to_profile(&self, provider: &OAuthProvider) -> Result<UserProfile>;
727
728 async fn to_profile_with_extractor(
730 &self,
731 provider: &OAuthProvider,
732 extractor: &ProfileExtractor,
733 ) -> Result<UserProfile>;
734}
735
736#[async_trait::async_trait]
737impl TokenToProfile for AuthToken {
738 async fn to_profile(&self, provider: &OAuthProvider) -> Result<UserProfile> {
739 let extractor = ProfileExtractor::new();
740 extractor.extract_profile(self, provider).await
741 }
742
743 async fn to_profile_with_extractor(
744 &self,
745 provider: &OAuthProvider,
746 extractor: &ProfileExtractor,
747 ) -> Result<UserProfile> {
748 extractor.extract_profile(self, provider).await
749 }
750}
751
752#[cfg(test)]
753mod tests {
754 use super::*;
755
756 #[test]
757 fn test_auth_token_creation() {
758 let token = AuthToken::new(
759 "user123",
760 "token123",
761 Duration::from_secs(3600), "password",
763 );
764
765 assert_eq!(token.user_id(), "user123");
766 assert_eq!(token.access_token(), "token123");
767 assert!(!token.is_expired());
768 assert!(!token.is_revoked());
769 assert!(token.is_valid());
770 }
771
772 #[test]
773 fn test_token_expiry() {
774 let token = AuthToken::new("user123", "token123", Duration::from_millis(1), "password");
775
776 std::thread::sleep(std::time::Duration::from_millis(10));
778
779 assert!(token.is_expired());
780 assert!(!token.is_valid());
781 }
782
783 #[test]
784 fn test_token_revocation() {
785 let mut token = AuthToken::new(
786 "user123",
787 "token123",
788 Duration::from_secs(3600), "password",
790 );
791
792 assert!(!token.is_revoked());
793
794 token.revoke(Some("User logout".to_string()));
795
796 assert!(token.is_revoked());
797 assert!(!token.is_valid());
798 assert!(token.metadata.revoked);
799 }
800}