Refactored the whole code to a better structure

This commit is contained in:
Marko Korhonen 2020-04-05 22:53:42 +03:00
parent 87cc8ac794
commit 12b865bf17
No known key found for this signature in database
GPG key ID: 911B85FBC6003FE5
21 changed files with 473 additions and 257 deletions

50
project/src/utils/jwt.rs Normal file
View file

@ -0,0 +1,50 @@
extern crate bcrypt;
use actix_web::HttpResponse;
use chrono::{Duration, Local};
use jwt::{decode, encode, DecodingKey, EncodingKey, Header, Validation};
#[derive(Debug, Serialize, Deserialize)]
struct Claims {
sub: String,
admin: bool,
exp: usize,
}
pub struct UserWithToken {
pub username: String,
pub admin: bool,
}
impl From<Claims> for UserWithToken {
fn from(claims: Claims) -> Self {
UserWithToken {
username: claims.sub,
admin: claims.admin,
}
}
}
impl Claims {
fn with_username(username: &str, admin: &bool) -> Self {
Claims {
sub: email.into(),
admin: admin.into(),
exp: (Local::now() + Duration::hours(24)).timestamp() as usize,
}
}
}
pub fn new_token(username: &str) -> Result<String, HttpResponse> {
let secret = dotenv!("JWT_SECRET").as_bytes();
let claims = Claims::with_username(username, admin);
encode(&Header::default(), &claims, secret)
.map_err(|e| HttpResponse::InternalServerError().json(e.to_string()))
}
pub fn decode_token(token: &str) -> Result<UserWithToken, HttpResponse> {
decode::<Claims>(token, get_secret(), &Validation::default())
.map(|data| data.claims.into())
.map_err(|e| HttpResponse::Unauthorized().json(e.to_string()))
}