use proper result for finding user

This commit is contained in:
2023-04-10 14:25:31 +02:00
parent 4592e610a3
commit 494ec31c8d
4 changed files with 35 additions and 137 deletions

View File

@ -22,7 +22,6 @@ pub struct User {
#[derive(Debug)]
pub enum LoginError {
SqlxError(sqlx::Error),
InvalidAuthenticationCombo,
NotLoggedIn,
NotAnAdmin,
@ -30,11 +29,6 @@ pub enum LoginError {
NoPasswordSet(User),
}
impl From<sqlx::Error> for LoginError {
fn from(sqlx_error: sqlx::Error) -> Self {
Self::SqlxError(sqlx_error)
}
}
impl User {
pub async fn update(&self, db: &SqlitePool, is_cox: bool, is_admin: bool, is_guest: bool) {
sqlx::query!(
@ -60,36 +54,38 @@ impl User {
.is_ok()
}
pub async fn find_by_id(db: &SqlitePool, id: i32) -> Result<Self, sqlx::Error> {
let user: User = sqlx::query_as!(
User,
"
pub async fn find_by_id(db: &SqlitePool, id: i32) -> Option<Self> {
Some(
sqlx::query_as!(
User,
"
SELECT id, name, pw, is_cox, is_admin, is_guest
FROM user
WHERE id like ?
",
id
id
)
.fetch_one(db)
.await
.ok()?,
)
.fetch_one(db)
.await?;
Ok(user)
}
async fn find_by_name(db: &SqlitePool, name: String) -> Result<Self, sqlx::Error> {
let user: User = sqlx::query_as!(
User,
"
async fn find_by_name(db: &SqlitePool, name: String) -> Option<Self> {
Some(
sqlx::query_as!(
User,
"
SELECT id, name, pw, is_cox, is_admin, is_guest
FROM user
WHERE name like ?
",
name
name
)
.fetch_one(db)
.await
.ok()?,
)
.fetch_one(db)
.await?;
Ok(user)
}
fn get_hashed_pw(pw: &str) -> String {
@ -102,7 +98,12 @@ WHERE name like ?
}
pub async fn login(db: &SqlitePool, name: String, pw: String) -> Result<Self, LoginError> {
let user = User::find_by_name(db, name).await?;
let user = match User::find_by_name(db, name).await {
Some(user) => user,
None => {
return Err(LoginError::InvalidAuthenticationCombo); // Username not found
}
};
match user.pw.clone() {
Some(user_pw) => {