extern crate bcrypt; extern crate jsonwebtoken; use crate::get_env; use actix_web::HttpResponse; use chrono::{Duration, Local}; use jsonwebtoken::{decode, encode, DecodingKey, EncodingKey, Header, Validation}; use serde::{Deserialize, Serialize}; #[derive(Debug, Serialize, Deserialize)] struct Claims { sub: i32, name: String, admin: bool, exp: usize, } #[derive(Deserialize)] pub struct UserWithToken { pub id: i32, pub username: String, pub admin: bool, } impl From for UserWithToken { fn from(claims: Claims) -> Self { UserWithToken { id: claims.sub, username: claims.name, admin: claims.admin, } } } impl Claims { fn with_username(id: i32, username: &str, admin: bool) -> Self { Claims { sub: id, name: username.into(), admin, exp: (Local::now() + Duration::hours(24)).timestamp() as usize, } } } pub fn encode_token(id: i32, username: &str, admin: bool) -> Result { let claims = Claims::with_username(id, username, admin); let secret = get_env("JWT_SECRET"); let key = EncodingKey::from_secret(secret.as_bytes()); encode(&Header::default(), &claims, &key) .map_err(|e| HttpResponse::InternalServerError().json(e.to_string())) } pub fn decode_token(token: &str) -> Result { let secret = get_env("JWT_SECRET"); let key = DecodingKey::from_secret(secret.as_bytes()); decode::(token, &key, &Validation::default()) .map(|data| data.claims.into()) .map_err(|e| HttpResponse::Unauthorized().json(e.to_string())) }