sa_token_core/token/
mod.rs

1// Author: 金书记
2//
3//! Token 管理模块
4
5use chrono::{DateTime, Utc};
6use serde::{Deserialize, Serialize};
7
8pub mod generator;
9pub mod validator;
10pub mod jwt;
11
12pub use generator::TokenGenerator;
13pub use validator::TokenValidator;
14pub use jwt::{JwtManager, JwtClaims, JwtAlgorithm};
15
16/// Token 值
17#[derive(Debug, Clone, PartialEq, Eq, Hash, Serialize, Deserialize)]
18pub struct TokenValue(String);
19
20impl TokenValue {
21    pub fn new(value: impl Into<String>) -> Self {
22        Self(value.into())
23    }
24    
25    pub fn as_str(&self) -> &str {
26        &self.0
27    }
28}
29
30impl From<String> for TokenValue {
31    fn from(s: String) -> Self {
32        Self(s)
33    }
34}
35
36impl From<TokenValue> for String {
37    fn from(v: TokenValue) -> Self {
38        v.0
39    }
40}
41
42impl std::fmt::Display for TokenValue {
43    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
44        write!(f, "{}", self.0)
45    }
46}
47
48/// Token 信息 | Token Information
49/// 
50/// 存储 Token 的完整信息,包括元数据和安全特性
51/// Stores complete token information, including metadata and security features
52/// 
53/// # 字段说明 | Field Description
54/// - `token`: Token 值 | Token value
55/// - `login_id`: 登录用户 ID | Logged-in user ID
56/// - `login_type`: 登录类型(如 "user", "admin")| Login type (e.g., "user", "admin")
57/// - `create_time`: Token 创建时间 | Token creation time
58/// - `last_active_time`: 最后活跃时间 | Last active time
59/// - `expire_time`: 过期时间(None 表示永不过期)| Expiration time (None means never expires)
60/// - `device`: 设备标识 | Device identifier
61/// - `extra_data`: 额外数据 | Extra data
62/// - `nonce`: 防重放攻击的一次性令牌 | One-time token for replay attack prevention
63/// - `refresh_token`: 用于刷新的长期令牌 | Long-term token for refresh
64/// - `refresh_token_expire_time`: Refresh Token 过期时间 | Refresh token expiration time
65#[derive(Debug, Clone, Serialize, Deserialize)]
66pub struct TokenInfo {
67    /// Token 值 | Token value
68    pub token: TokenValue,
69    
70    /// 登录 ID | Login ID
71    pub login_id: String,
72    
73    /// 登录类型(user、admin 等)| Login type (user, admin, etc.)
74    pub login_type: String,
75    
76    /// Token 创建时间 | Token creation time
77    pub create_time: DateTime<Utc>,
78    
79    /// Token 最后活跃时间 | Token last active time
80    pub last_active_time: DateTime<Utc>,
81    
82    /// Token 过期时间(None 表示永不过期)| Token expiration time (None means never expires)
83    pub expire_time: Option<DateTime<Utc>>,
84    
85    /// 设备标识 | Device identifier
86    pub device: Option<String>,
87    
88    /// 额外数据 | Extra data
89    pub extra_data: Option<serde_json::Value>,
90    
91    /// Nonce(用于防重放攻击)| Nonce (for replay attack prevention)
92    pub nonce: Option<String>,
93    
94    /// Refresh Token(用于刷新访问令牌)| Refresh Token (for refreshing access token)
95    pub refresh_token: Option<String>,
96    
97    /// Refresh Token 过期时间 | Refresh Token expiration time
98    pub refresh_token_expire_time: Option<DateTime<Utc>>,
99}
100
101impl TokenInfo {
102    pub fn new(token: TokenValue, login_id: impl Into<String>) -> Self {
103        let now = Utc::now();
104        Self {
105            token,
106            login_id: login_id.into(),
107            login_type: "default".to_string(),
108            create_time: now,
109            last_active_time: now,
110            expire_time: None,
111            device: None,
112            extra_data: None,
113            nonce: None,
114            refresh_token: None,
115            refresh_token_expire_time: None,
116        }
117    }
118    
119    pub fn is_expired(&self) -> bool {
120        if let Some(expire_time) = self.expire_time {
121            Utc::now() > expire_time
122        } else {
123            false
124        }
125    }
126    
127    pub fn update_active_time(&mut self) {
128        self.last_active_time = Utc::now();
129    }
130}
131
132/// Token 签名
133#[derive(Debug, Clone)]
134pub struct TokenSign {
135    pub value: String,
136    pub device: Option<String>,
137}