From 65bcc5ce455bdc298af3b9c4a30039afed047a4f Mon Sep 17 00:00:00 2001 From: alpaylan Date: Mon, 12 Apr 2021 22:15:17 +0300 Subject: implement user authentication using jwt --- src/handlers.rs | 60 +++++++++++++++++++++++++++++++++++++++++++++++++++++---- 1 file changed, 56 insertions(+), 4 deletions(-) (limited to 'src/handlers.rs') diff --git a/src/handlers.rs b/src/handlers.rs index 38bd459..07986f5 100644 --- a/src/handlers.rs +++ b/src/handlers.rs @@ -1,16 +1,29 @@ +use blake2::{Blake2s, Digest}; +use jsonwebtoken::{decode, Algorithm, DecodingKey, Validation}; /// API handlers, the ends of each filter chain use log::debug; +use md5::Md5; use parking_lot::RwLockUpgradableReadGuard; +use serde::{Deserialize, Serialize}; use serde_json; use serde_json::json; use std::convert::Infallible; -use warp::{http::Response, http::StatusCode, reply}; +use std::fs; +use warp::{http::Response, http::StatusCode, reject, reply}; -use blake2::{Blake2s, Digest}; +use gradecoin::schema::{ + AuthRequest, Block, Db, MetuId, NakedBlock, PublicKeySignature, Transaction, User, +}; -use std::fs; +const BEARER: &str = "Bearer "; -use gradecoin::schema::{AuthRequest, Block, Db, MetuId, NakedBlock, Transaction, User}; +/// tha: Transaction Hash, String +/// iat: Issued At, Unix Time, epoch +#[derive(Debug, Serialize, Deserialize)] +pub struct Claims { + pub tha: String, + pub iat: usize, +} /// POST /register /// Enables a student to introduce themselves to the system @@ -167,3 +180,42 @@ pub async fn propose_block(new_block: Block, db: Db) -> Result Result { + debug!("new transaction request {:?}", new_transaction); + let raw_jwt = token.trim_start_matches(BEARER).to_owned(); + + let decoded = jsonwebtoken::decode::( + &token, + &DecodingKey::from_rsa_pem( + db.users + .read() + .get(&new_transaction.by) + .unwrap() + .public_key + .as_bytes(), + ) + .unwrap(), + // todo@keles: If user is not found return user not found error + &Validation::new(Algorithm::PS256), + ) + .unwrap(); + // todo: If user is found but header is not validated, return header not valid + + let hashed_transaction = Md5::digest(&serde_json::to_vec(&new_transaction).unwrap()); + + // let mut transactions = db.lock().await; + if decoded.claims.tha == format!("{:x}", hashed_transaction) { + let mut transactions = db.pending_transactions.write(); + + transactions.insert(new_transaction.source.to_owned(), new_transaction); + + Ok(StatusCode::CREATED) + } else { + Ok(StatusCode::BAD_REQUEST) + } +} -- cgit v1.2.3-70-g09d2