Started JWT token generation

This commit is contained in:
Jef Roosens 2021-08-21 13:46:41 +02:00
parent d90dbcdc2a
commit 6782fecc0d
Signed by untrusted user: Jef Roosens
GPG key ID: 955C0660072F691F
5 changed files with 203 additions and 9 deletions

View file

@ -4,6 +4,16 @@ use crate::schema::users::dsl as users;
use argon2::verify_encoded;
use diesel::prelude::*;
use diesel::PgConnection;
use hmac::{Hmac, NewMac};
use jwt::SignWithKey;
use sha2::Sha256;
use std::collections::HashMap;
use chrono::Utc;
/// Expire time for the JWT tokens in seconds.
const JWT_EXP_SECONDS: i64 = 900;
/// Amount of bytes the refresh tokens should consist of
const REFRESH_TOKEN_N_BYTES: u32 = 64;
pub fn verify_user(conn: &PgConnection, username: &str, password: &str) -> Result<User, AuthError> {
// TODO handle non-"NotFound" Diesel errors accordingely
@ -20,3 +30,24 @@ pub fn verify_user(conn: &PgConnection, username: &str, password: &str) -> Resul
_ => Err(AuthError::InvalidPassword),
}
}
struct JWTResponse {
token: String,
refresh_token: String
}
pub fn generate_jwt_token(conn: &PgConnection, user: &User) -> JWTResponse {
// TODO actually use proper secret here
// TODO don't just unwrap here
let key: Hmac<Sha256> = Hmac::new_from_slice(b"some-secret").unwrap();
// Create the claims
let mut claims = HashMap::new();
claims.insert("id", user.id.to_string());
claims.insert("username", user.username);
claims.insert("exp", (Utc::now().timestamp() + JWT_EXP_SECONDS).to_string());
// Sign the claims into a new token
// TODO don't just unwrap here
let token = claims.sign_with_key(&key).unwrap();
}

View file

@ -1,11 +1,14 @@
use diesel::Queryable;
use uuid::Uuid;
use serde::Serialize;
#[derive(Queryable)]
#[derive(Queryable, Serialize)]
pub struct User {
id: Uuid,
username: String,
pub id: Uuid,
pub username: String,
#[serde(skip_serializing)]
pub password: String,
#[serde(skip_serializing)]
blocked: bool,
admin: bool,
}

View file

@ -11,9 +11,12 @@ struct Credentials {
#[post("/login", data = "<credentials>")]
async fn login(conn: RbDbConn, credentials: Json<Credentials>) {
let credentials = credentials.into_inner();
let user = conn
.run(move |c| verify_user(c, &credentials.username, &credentials.password))
.await;
user
}
// /refresh