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 }, )) }