Authentication works now

This commit is contained in:
Marko Korhonen 2020-04-10 12:46:39 +03:00
parent 7347151c95
commit d7d2fa5d9e
No known key found for this signature in database
GPG key ID: 911B85FBC6003FE5
7 changed files with 90 additions and 166 deletions

View file

@ -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()))
}