From 040d338ae0f460966b578c3d26d1c51a6205dc1e Mon Sep 17 00:00:00 2001 From: antifallobst Date: Thu, 17 Aug 2023 00:57:08 +0200 Subject: [PATCH] feat(api): fully implemented the authenticate endpoint --- src/accounts.rs | 12 +++++++++++- src/api/account/handlers.rs | 15 ++++++++++++--- 2 files changed, 23 insertions(+), 4 deletions(-) diff --git a/src/accounts.rs b/src/accounts.rs index 17b2eb9..cb22ffc 100644 --- a/src/accounts.rs +++ b/src/accounts.rs @@ -93,7 +93,7 @@ impl Account { Err(e) => Err(Error::new(e)), } } - + pub async fn from_email(pool: &MySqlPool, email: &String) -> Result> { match sqlx::query!(r#"SELECT * FROM Accounts WHERE email = ?;"#, email) .fetch_one(pool) @@ -115,4 +115,14 @@ impl Account { Err(e) => Err(Error::new(e)), } } + + pub async fn check_password(&self, password: String) -> Result { + let hash = PasswordHash::new(self.password.as_str()) + .map_err(|_| anyhow::Error::msg("Failed to parse the password hash"))?; + + match Pbkdf2.verify_password(password.as_bytes(), &hash) { + Ok(_) => Ok(true), + Err(_) => Ok(false), + } + } } diff --git a/src/api/account/handlers.rs b/src/api/account/handlers.rs index fad0686..6f8b625 100644 --- a/src/api/account/handlers.rs +++ b/src/api/account/handlers.rs @@ -102,10 +102,19 @@ pub async fn authenticate( return Ok(data::AuthenticateResponse::Blocked); } + let account = match Account::from_username(pool, &request.username).await? { + Some(a) => a, + None => return Ok(data::AuthenticateResponse::UserNotFound), + }; + + if !account.check_password(request.password).await? { + return Ok(data::AuthenticateResponse::WrongPassword); + } + + let token = AuthToken::new(pool, account.id, chrono::Duration::days(7)).await?; + Ok(data::AuthenticateResponse::Success( - data::AuthenticateSuccess { - token: "not_a_valid_token".to_string(), - }, + data::AuthenticateSuccess { token: token.token }, )) }