Register works, login almost
This commit is contained in:
parent
12b865bf17
commit
c85bb0ef72
6 changed files with 79 additions and 41 deletions
|
@ -1,17 +1,21 @@
|
|||
extern crate bcrypt;
|
||||
extern crate jsonwebtoken;
|
||||
|
||||
use actix_web::HttpResponse;
|
||||
use chrono::{Duration, Local};
|
||||
use jwt::{decode, encode, DecodingKey, EncodingKey, Header, Validation};
|
||||
use jsonwebtoken::{decode, encode, Header, Validation};
|
||||
use serde::{Deserialize, Serialize};
|
||||
|
||||
#[derive(Debug, Serialize, Deserialize)]
|
||||
struct Claims {
|
||||
sub: String,
|
||||
sub: i32,
|
||||
name: String,
|
||||
admin: bool,
|
||||
exp: usize,
|
||||
}
|
||||
|
||||
pub struct UserWithToken {
|
||||
pub id: i32,
|
||||
pub username: String,
|
||||
pub admin: bool,
|
||||
}
|
||||
|
@ -19,27 +23,31 @@ pub struct UserWithToken {
|
|||
impl From<Claims> for UserWithToken {
|
||||
fn from(claims: Claims) -> Self {
|
||||
UserWithToken {
|
||||
username: claims.sub,
|
||||
id: claims.sub,
|
||||
username: claims.name,
|
||||
admin: claims.admin,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
impl Claims {
|
||||
fn with_username(username: &str, admin: &bool) -> Self {
|
||||
fn with_username(id: i32, username: &str, admin: bool) -> Self {
|
||||
Claims {
|
||||
sub: email.into(),
|
||||
admin: admin.into(),
|
||||
sub: id,
|
||||
name: username.into(),
|
||||
admin,
|
||||
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();
|
||||
fn get_secret() -> [u8] {
|
||||
std::env::var("JWT_SECRET").expect("JWT_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, secret)
|
||||
encode(&Header::default(), &claims, get_secret())
|
||||
.map_err(|e| HttpResponse::InternalServerError().json(e.to_string()))
|
||||
}
|
||||
|
||||
|
|
Loading…
Add table
Add a link
Reference in a new issue