Moved backend to it's own directory under project
This commit is contained in:
parent
c8a6acd07d
commit
36c58a89f7
19 changed files with 0 additions and 0 deletions
62
project/server/src/utils/jwt.rs
Normal file
62
project/server/src/utils/jwt.rs
Normal file
|
@ -0,0 +1,62 @@
|
|||
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()))
|
||||
}
|
Loading…
Add table
Add a link
Reference in a new issue