feat(api): fully implemented the authenticate endpoint
This commit is contained in:
parent
1477e4cef6
commit
040d338ae0
|
@ -93,7 +93,7 @@ impl Account {
|
|||
Err(e) => Err(Error::new(e)),
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
pub async fn from_email(pool: &MySqlPool, email: &String) -> Result<Option<Self>> {
|
||||
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<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),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
|
|
@ -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 },
|
||||
))
|
||||
}
|
||||
|
||||
|
|
Loading…
Reference in New Issue