Init
This commit is contained in:
48
src/utils/auth.rs
Normal file
48
src/utils/auth.rs
Normal file
@@ -0,0 +1,48 @@
|
||||
use jsonwebtoken::{decode, encode, DecodingKey, EncodingKey, Header, Validation};
|
||||
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 expire_at: usize, // Expiration time
|
||||
pub created_at: usize, // Issued at
|
||||
pub username: String,
|
||||
}
|
||||
|
||||
pub fn create_jwt(
|
||||
user_id: Uuid,
|
||||
username: &str,
|
||||
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: user_id,
|
||||
expire_at: (now + expiration_seconds) as usize,
|
||||
created_at: now as usize,
|
||||
username: username.to_string(),
|
||||
};
|
||||
|
||||
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)
|
||||
}
|
||||
@@ -1,3 +1,4 @@
|
||||
pub mod auth;
|
||||
pub mod password;
|
||||
pub mod ssh_auth;
|
||||
pub mod toolbox;
|
||||
|
||||
Reference in New Issue
Block a user