47 lines
1.3 KiB
Rust
47 lines
1.3 KiB
Rust
use jsonwebtoken::{DecodingKey, EncodingKey, Header, Validation, decode, encode};
|
|
use serde::{Deserialize, Serialize};
|
|
use std::time::{SystemTime, UNIX_EPOCH};
|
|
use uuid::Uuid;
|
|
|
|
#[derive(Debug, Serialize, Deserialize)]
|
|
pub struct Claims {
|
|
pub user_id: Uuid, // User ID
|
|
pub exp: usize, // Changé de expire_at -> exp (Standard JWT)
|
|
pub iat: usize, // Changé de created_at -> iat (Standard JWT)
|
|
}
|
|
|
|
pub fn create_jwt(
|
|
user_id: Uuid,
|
|
username: &str,
|
|
is_superuser: bool, // Ajoutez l'argument ici
|
|
secret: &str,
|
|
expiration_seconds: u64,
|
|
) -> Result<String, jsonwebtoken::errors::Error> {
|
|
let now = SystemTime::now()
|
|
.duration_since(UNIX_EPOCH)
|
|
.expect("Time went backwards")
|
|
.as_secs();
|
|
|
|
let claims = Claims {
|
|
user_id,
|
|
exp: (now + expiration_seconds) as usize,
|
|
iat: now as usize,
|
|
};
|
|
|
|
encode(
|
|
&Header::default(),
|
|
&claims,
|
|
&EncodingKey::from_secret(secret.as_ref()),
|
|
)
|
|
}
|
|
|
|
pub fn verify_jwt(token: &str, secret: &str) -> Result<Claims, jsonwebtoken::errors::Error> {
|
|
let validation = Validation::default();
|
|
let token_data = decode::<Claims>(
|
|
token,
|
|
&DecodingKey::from_secret(secret.as_ref()),
|
|
&validation,
|
|
)?;
|
|
Ok(token_data.claims)
|
|
}
|