Refactored the whole code to a better structure
This commit is contained in:
parent
87cc8ac794
commit
12b865bf17
21 changed files with 473 additions and 257 deletions
50
project/src/utils/jwt.rs
Normal file
50
project/src/utils/jwt.rs
Normal 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()))
|
||||
}
|
Loading…
Add table
Add a link
Reference in a new issue