feat(api): fully implemented the authenticate endpoint

This commit is contained in:
antifallobst 2023-08-17 00:57:08 +02:00
parent 1477e4cef6
commit 040d338ae0
Signed by: antifallobst
GPG Key ID: 2B4F402172791BAF
2 changed files with 23 additions and 4 deletions

View File

@ -93,7 +93,7 @@ impl Account {
Err(e) => Err(Error::new(e)), Err(e) => Err(Error::new(e)),
} }
} }
pub async fn from_email(pool: &MySqlPool, email: &String) -> Result<Option<Self>> { pub async fn from_email(pool: &MySqlPool, email: &String) -> Result<Option<Self>> {
match sqlx::query!(r#"SELECT * FROM Accounts WHERE email = ?;"#, email) match sqlx::query!(r#"SELECT * FROM Accounts WHERE email = ?;"#, email)
.fetch_one(pool) .fetch_one(pool)
@ -115,4 +115,14 @@ impl Account {
Err(e) => Err(Error::new(e)), Err(e) => Err(Error::new(e)),
} }
} }
pub async fn check_password(&self, password: String) -> Result<bool> {
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),
}
}
} }

View File

@ -102,10 +102,19 @@ pub async fn authenticate(
return Ok(data::AuthenticateResponse::Blocked); 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( Ok(data::AuthenticateResponse::Success(
data::AuthenticateSuccess { data::AuthenticateSuccess { token: token.token },
token: "not_a_valid_token".to_string(),
},
)) ))
} }