64 lines
1.9 KiB
Rust
64 lines
1.9 KiB
Rust
use chrono::{TimeDelta, Utc};
|
|
use serde::{Deserialize, Serialize};
|
|
|
|
use crate::config;
|
|
|
|
#[derive(Debug, Serialize, Deserialize, Clone)]
|
|
pub struct Claims {
|
|
pub sub: String, // 用户ID
|
|
pub exp: i64, // Token过期时间戳
|
|
}
|
|
|
|
#[inline]
|
|
pub fn generate_token(sub: &str) -> String {
|
|
let claim = Claims {
|
|
sub: sub.to_string(),
|
|
exp: (Utc::now() + TimeDelta::try_seconds(config!().jwt.expires).unwrap()).timestamp(),
|
|
};
|
|
let token = jsonwebtoken::encode(
|
|
&jsonwebtoken::Header::default(),
|
|
&claim,
|
|
&jsonwebtoken::EncodingKey::from_secret(config!().jwt.token_secret.as_bytes()),
|
|
);
|
|
token.unwrap_or_else(|e| {
|
|
tracing::error!(error =?e, "生成Token失败");
|
|
"".to_string()
|
|
})
|
|
}
|
|
|
|
#[inline]
|
|
pub fn generate_refresh_token(sub: &str) -> String {
|
|
let claim = Claims {
|
|
sub: sub.to_string(),
|
|
exp: (Utc::now() + TimeDelta::try_seconds(config!().jwt.refresh_expires).unwrap()).timestamp(),
|
|
};
|
|
let token = jsonwebtoken::encode(
|
|
&jsonwebtoken::Header::default(),
|
|
&claim,
|
|
&jsonwebtoken::EncodingKey::from_secret(config!().jwt.refresh_token_secret.as_bytes()),
|
|
);
|
|
token.unwrap_or_else(|e| {
|
|
tracing::error!(error =?e, "生成Refresh Token失败");
|
|
"".to_string()
|
|
})
|
|
}
|
|
|
|
#[inline]
|
|
pub fn verify_token(token: &str) -> Result<Claims, jsonwebtoken::errors::Error> {
|
|
jsonwebtoken::decode::<Claims>(
|
|
token,
|
|
&jsonwebtoken::DecodingKey::from_secret(config!().jwt.token_secret.as_bytes()),
|
|
&jsonwebtoken::Validation::default(),
|
|
)
|
|
.map(|data| data.claims)
|
|
}
|
|
|
|
#[inline]
|
|
pub fn verify_refresh_token(token: &str) -> Result<Claims, jsonwebtoken::errors::Error> {
|
|
jsonwebtoken::decode::<Claims>(
|
|
token,
|
|
&jsonwebtoken::DecodingKey::from_secret(config!().jwt.refresh_token_secret.as_bytes()),
|
|
&jsonwebtoken::Validation::default(),
|
|
)
|
|
.map(|data| data.claims)
|
|
} |