diff --git a/src/auth.rs b/src/auth.rs index d3d22b7..6fab2ef 100644 --- a/src/auth.rs +++ b/src/auth.rs @@ -46,7 +46,7 @@ pub fn force_init_keys() { LazyLock::force(&KEYS); } -/// Hashes the bytes with Scrypt with the given salt +/// Hashes the bytes using Scrypt with the given salt #[must_use] fn hash_scrypt(bytes: &[u8], salt: &[u8]) -> [u8; HASH_LENGTH] { let mut hash = [0; HASH_LENGTH]; @@ -55,6 +55,7 @@ fn hash_scrypt(bytes: &[u8], salt: &[u8]) -> [u8; HASH_LENGTH] { } /// Verifieble scrypt hashed bytes +#[cfg_attr(test, derive(PartialEq))] pub struct HashedBytes { pub hash: [u8; HASH_LENGTH], pub salt: [u8; SALT_LENGTH], @@ -163,11 +164,32 @@ impl FromRequestParts for Claims { .extract::>>() .await .map_err(|_| Error::InvalidToken)?; - // Decode the user data - let token_data = - decode::(bearer.token(), &KEYS.decoding_key, &Validation::default()) - .map_err(|_| Error::InvalidToken)?; - + let token_data = decode(bearer.token(), &KEYS.decoding_key, &Validation::default()) + .map_err(|_| Error::InvalidToken)?; Ok(token_data.claims) } } + +#[cfg(test)] +mod tests { + use super::HashedBytes; + + const PASSWORD: &str = "Password12313#!#4)$*!#"; + + #[test] + fn test_hash_conversion() { + let bytes = HashedBytes::hash_bytes(PASSWORD.as_bytes()); + let bytes2 = HashedBytes::from_bytes(&bytes.as_bytes()).unwrap(); + assert!(bytes == bytes2); + } + + #[test] + fn test_hash() { + assert!(HashedBytes::hash_bytes(PASSWORD.as_bytes()).verify(PASSWORD.as_bytes())); + } + + #[test] + fn test_different_hash() { + assert!(!HashedBytes::hash_bytes(PASSWORD.as_bytes()).verify(b"Different Password")); + } +} diff --git a/src/endpoints/users/get.rs b/src/endpoints/users/get.rs index 203673d..9d66233 100644 --- a/src/endpoints/users/get.rs +++ b/src/endpoints/users/get.rs @@ -5,12 +5,21 @@ pub struct Params { user_id: i32, } -pub async fn get( - State(pool): State, - Query(params): Query, -) -> Result, StatusCode> { +type Response = Result, StatusCode>; + +pub async fn get(State(pool): State, Query(params): Query) -> Response { let info = db::users::get(params.user_id, &pool) .await .handle_internal()?; Ok(Json(info)) } + +pub async fn current(state: State, claims: Claims) -> Response { + get( + state, + Query(Params { + user_id: claims.user_id, + }), + ) + .await +} diff --git a/src/main.rs b/src/main.rs index 5ad79ab..4099bbf 100644 --- a/src/main.rs +++ b/src/main.rs @@ -120,6 +120,7 @@ fn app(state: AppState) -> Router { .delete(users::delete::delete) .put(users::put::put), ) + .route("/users/current", get(users::get::current)) .route("/users/search", get(users::search::search)) .route("/authorize", post(authorization::auth_post::post)) .layer(middleware)