thesis/project/server/src/utils/jwt.rs
2020-04-10 18:44:45 +03:00

62 lines
1.7 KiB
Rust

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<Claims> 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<String, HttpResponse> {
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<UserWithToken, HttpResponse> {
let secret = get_env("JWT_SECRET");
let key = DecodingKey::from_secret(secret.as_bytes());
decode::<Claims>(token, &key, &Validation::default())
.map(|data| data.claims.into())
.map_err(|e| HttpResponse::Unauthorized().json(e.to_string()))
}