use uuid::Uuid; use serde::{Serialize, Deserialize}; use chrono::serde::ts_seconds; use chrono::prelude::{DateTime, Utc}; use chrono::Duration; use jsonwebtoken::{ encode, decode, Header, Validation, Algorithm as JwtAlgorithm, EncodingKey, DecodingKey, errors::Result as JwtResult }; use crate::models::user::UserInfo; #[derive(Debug, Serialize, Deserialize)] pub struct AuthClaims { pub jti: String, pub sub: String, #[serde(with = "ts_seconds")] pub exp: DateTime, #[serde(with = "ts_seconds")] pub iat: DateTime, } #[derive(Debug, Serialize)] pub struct AuthTokenResponse { pub token: String } #[derive(Debug, Deserialize)] pub struct AuthTokenRequest { pub username: String, pub password: String, } impl AuthClaims { pub fn new(user_info: &UserInfo, token_duration: Duration) -> AuthClaims { let jti = Uuid::new_v4().to_simple().to_string(); let iat = Utc::now(); let exp = iat + token_duration; AuthClaims { jti, sub: user_info.id.clone(), exp, iat, } } pub fn decode(token: &str, secret: &str) -> JwtResult { decode::( token, &DecodingKey::from_secret(secret.as_ref()), &Validation::new(JwtAlgorithm::HS256) ).map(|data| data.claims) } pub fn encode(self, secret: &str) -> JwtResult { encode(&Header::default(), &self, &EncodingKey::from_secret(secret.as_ref())) } }