rowt/src/model/user.rs

104 lines
2.4 KiB
Rust
Raw Normal View History

2023-04-03 17:32:41 +02:00
use argon2::{password_hash::SaltString, Argon2, PasswordHasher};
use serde::Serialize;
2023-04-03 16:11:26 +02:00
use sqlx::{FromRow, SqlitePool};
2023-04-03 17:32:41 +02:00
#[derive(FromRow, Debug, Serialize)]
2023-04-03 16:11:26 +02:00
pub struct User {
id: i64,
name: String,
pw: String,
is_cox: bool,
is_admin: bool,
is_guest: bool,
}
2023-04-03 17:21:34 +02:00
#[derive(Debug)]
2023-04-03 16:11:26 +02:00
pub enum LoginError {
SqlxError(sqlx::Error),
InvalidAuthenticationCombo,
}
impl From<sqlx::Error> for LoginError {
fn from(sqlx_error: sqlx::Error) -> Self {
Self::SqlxError(sqlx_error)
}
}
impl User {
2023-04-03 17:21:34 +02:00
async fn find_by_name(db: &SqlitePool, name: String) -> Result<Self, sqlx::Error> {
2023-04-03 16:11:26 +02:00
let user: User = sqlx::query_as!(
User,
"
SELECT id, name, pw, is_cox, is_admin, is_guest
FROM user
WHERE name like ?
",
name
)
.fetch_one(db)
.await?;
Ok(user)
}
pub async fn login(db: &SqlitePool, name: String, pw: String) -> Result<Self, LoginError> {
let user = User::find_by_name(db, name).await?;
2023-04-03 17:21:34 +02:00
let salt = SaltString::from_b64("dS/X5/sPEKTj4Rzs/CuvzQ").unwrap();
2023-04-03 16:11:26 +02:00
let argon2 = Argon2::default();
let password_hash = argon2
.hash_password(&pw.as_bytes(), &salt)
.unwrap()
.to_string();
2023-04-03 17:21:34 +02:00
if password_hash == user.pw {
return Ok(user);
2023-04-03 16:11:26 +02:00
}
2023-04-03 17:21:34 +02:00
Err(LoginError::InvalidAuthenticationCombo)
2023-04-03 16:11:26 +02:00
}
}
#[cfg(test)]
mod test {
2023-04-03 17:21:34 +02:00
use super::User;
2023-04-03 16:11:26 +02:00
use sqlx::SqlitePool;
2023-04-03 17:21:34 +02:00
async fn setup() -> SqlitePool {
2023-04-03 16:11:26 +02:00
let pool = SqlitePool::connect(":memory:").await.unwrap();
sqlx::query_file!("./migration.sql")
.execute(&pool)
.await
.unwrap();
sqlx::query_file!("./seeds.sql")
.execute(&pool)
.await
.unwrap();
2023-04-03 17:21:34 +02:00
pool
}
#[sqlx::test]
fn succ_login_with_test_db() {
let pool = setup().await;
User::login(&pool, "admin".into(), "admin".into())
.await
.unwrap();
}
#[sqlx::test]
fn wrong_pw() {
let pool = setup().await;
assert!(User::login(&pool, "admin".into(), "admi".into())
.await
.is_err());
}
#[sqlx::test]
fn wrong_username() {
let pool = setup().await;
assert!(User::login(&pool, "admi".into(), "admin".into())
.await
.is_err());
2023-04-03 16:11:26 +02:00
}
}