Authentication works now
This commit is contained in:
parent
7347151c95
commit
d7d2fa5d9e
7 changed files with 90 additions and 166 deletions
|
@ -1,9 +1,10 @@
|
|||
extern crate bcrypt;
|
||||
extern crate jsonwebtoken;
|
||||
|
||||
use crate::get_env;
|
||||
use actix_web::HttpResponse;
|
||||
use chrono::{Duration, Local};
|
||||
use jsonwebtoken::{decode, encode, Header, Validation};
|
||||
use jsonwebtoken::{decode, encode, DecodingKey, EncodingKey, Header, Validation};
|
||||
use serde::{Deserialize, Serialize};
|
||||
|
||||
#[derive(Debug, Serialize, Deserialize)]
|
||||
|
@ -41,18 +42,20 @@ impl Claims {
|
|||
}
|
||||
}
|
||||
|
||||
fn get_secret() -> [u8] {
|
||||
std::env::var("JWT_SECRET").expect("JWT_SECRET").as_bytes()
|
||||
}
|
||||
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());
|
||||
|
||||
pub fn new_token(id: i32, username: &str, admin: &bool) -> Result<String, HttpResponse> {
|
||||
let claims = Claims::with_username(username, admin);
|
||||
encode(&Header::default(), &claims, get_secret())
|
||||
encode(&Header::default(), &claims, &key)
|
||||
.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())
|
||||
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