rowt/src/model/user.rs

270 lines
6.8 KiB
Rust
Raw Normal View History

2023-04-04 15:16:21 +02:00
use std::ops::Deref;
2023-04-03 17:32:41 +02:00
use argon2::{password_hash::SaltString, Argon2, PasswordHasher};
2023-04-03 22:03:45 +02:00
use rocket::{
async_trait,
http::Status,
request::{self, FromRequest, Outcome},
Request,
};
use serde::{Deserialize, Serialize};
2023-04-03 16:11:26 +02:00
use sqlx::{FromRow, SqlitePool};
2023-04-03 22:03:45 +02:00
#[derive(FromRow, Debug, Serialize, Deserialize)]
2023-04-03 16:11:26 +02:00
pub struct User {
2023-04-04 10:44:14 +02:00
pub id: i64,
pub name: String,
pw: Option<String>,
2023-04-04 15:38:47 +02:00
pub is_cox: bool,
2023-04-03 16:11:26 +02:00
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 {
InvalidAuthenticationCombo,
2023-04-03 22:03:45 +02:00
NotLoggedIn,
2023-04-04 10:44:14 +02:00
NotAnAdmin,
2023-04-04 15:16:21 +02:00
NotACox,
2023-04-04 10:44:14 +02:00
NoPasswordSet(User),
2023-04-03 16:11:26 +02:00
}
impl User {
2023-04-04 10:44:14 +02:00
pub async fn update(&self, db: &SqlitePool, is_cox: bool, is_admin: bool, is_guest: bool) {
sqlx::query!(
"UPDATE user SET is_cox = ?, is_admin = ?, is_guest = ? where id = ?",
is_cox,
is_admin,
is_guest,
self.id
)
.execute(db)
.await
.unwrap(); //TODO: fixme
}
2023-04-05 20:56:36 +02:00
pub async fn create(db: &SqlitePool, name: String, is_guest: bool) -> bool {
sqlx::query!(
"INSERT INTO USER(name, is_guest) VALUES (?,?)",
name,
is_guest,
)
.execute(db)
.await
.is_ok()
}
2023-04-10 14:25:31 +02:00
pub async fn find_by_id(db: &SqlitePool, id: i32) -> Option<Self> {
2023-04-24 14:34:06 +02:00
sqlx::query_as!(
User,
"
2023-04-04 10:44:14 +02:00
SELECT id, name, pw, is_cox, is_admin, is_guest
FROM user
WHERE id like ?
",
2023-04-24 14:34:06 +02:00
id
2023-04-04 10:44:14 +02:00
)
2023-04-24 14:34:06 +02:00
.fetch_one(db)
.await
.ok()
2023-04-04 10:44:14 +02:00
}
2023-04-10 14:25:31 +02:00
async fn find_by_name(db: &SqlitePool, name: String) -> Option<Self> {
2023-04-24 14:34:06 +02:00
sqlx::query_as!(
User,
"
2023-04-03 16:11:26 +02:00
SELECT id, name, pw, is_cox, is_admin, is_guest
FROM user
WHERE name like ?
",
2023-04-24 14:34:06 +02:00
name
2023-04-03 16:11:26 +02:00
)
2023-04-24 14:34:06 +02:00
.fetch_one(db)
.await
.ok()
2023-04-03 16:11:26 +02:00
}
2023-04-04 19:49:27 +02:00
fn get_hashed_pw(pw: &str) -> String {
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();
2023-04-04 10:44:14 +02:00
argon2
2023-04-04 19:49:27 +02:00
.hash_password(pw.as_bytes(), &salt)
2023-04-03 16:11:26 +02:00
.unwrap()
2023-04-04 10:44:14 +02:00
.to_string()
}
pub async fn login(db: &SqlitePool, name: String, pw: String) -> Result<Self, LoginError> {
2023-04-10 14:25:31 +02:00
let user = match User::find_by_name(db, name).await {
Some(user) => user,
None => {
return Err(LoginError::InvalidAuthenticationCombo); // Username not found
}
};
2023-04-03 16:11:26 +02:00
2023-04-04 10:44:14 +02:00
match user.pw.clone() {
Some(user_pw) => {
2023-04-04 19:49:27 +02:00
let password_hash = Self::get_hashed_pw(&pw);
2023-04-04 10:44:14 +02:00
if password_hash == user_pw {
return Ok(user);
}
Err(LoginError::InvalidAuthenticationCombo)
}
None => Err(LoginError::NoPasswordSet(user)),
2023-04-03 16:11:26 +02:00
}
2023-04-04 10:44:14 +02:00
}
2023-04-03 16:11:26 +02:00
2023-04-04 10:44:14 +02:00
pub async fn all(db: &SqlitePool) -> Vec<Self> {
sqlx::query_as!(
User,
"
SELECT id, name, pw, is_cox, is_admin, is_guest
2023-04-05 22:09:24 +02:00
FROM user
ORDER BY name
2023-04-04 10:44:14 +02:00
"
)
.fetch_all(db)
.await
.unwrap() //TODO: fixme
}
pub async fn reset_pw(&self, db: &SqlitePool) {
sqlx::query!("UPDATE user SET pw = null where id = ?", self.id)
.execute(db)
.await
.unwrap(); //TODO: fixme
}
pub async fn update_pw(&self, db: &SqlitePool, pw: String) {
2023-04-04 19:49:27 +02:00
let pw = Self::get_hashed_pw(&pw);
2023-04-04 10:44:14 +02:00
sqlx::query!("UPDATE user SET pw = ? where id = ?", pw, self.id)
.execute(db)
.await
.unwrap(); //TODO: fixme
2023-04-03 16:11:26 +02:00
}
}
2023-04-03 22:03:45 +02:00
#[async_trait]
impl<'r> FromRequest<'r> for User {
type Error = LoginError;
async fn from_request(req: &'r Request<'_>) -> request::Outcome<Self, Self::Error> {
match req.cookies().get_private("loggedin_user") {
Some(user) => {
2023-04-04 19:49:27 +02:00
let user: User = serde_json::from_str(user.value()).unwrap(); //TODO: fixme
2023-04-03 22:03:45 +02:00
Outcome::Success(user)
}
None => Outcome::Failure((Status::Unauthorized, LoginError::NotLoggedIn)),
}
}
}
2023-04-06 08:06:50 +02:00
pub struct CoxUser {
user: User,
}
impl Deref for CoxUser {
type Target = User;
fn deref(&self) -> &Self::Target {
&self.user
}
}
impl TryFrom<User> for CoxUser {
type Error = LoginError;
fn try_from(user: User) -> Result<Self, Self::Error> {
if user.is_cox {
Ok(CoxUser { user })
} else {
Err(LoginError::NotACox)
}
}
}
2023-04-04 10:44:14 +02:00
#[async_trait]
2023-04-06 08:06:50 +02:00
impl<'r> FromRequest<'r> for CoxUser {
2023-04-04 10:44:14 +02:00
type Error = LoginError;
2023-04-04 15:16:21 +02:00
async fn from_request(req: &'r Request<'_>) -> request::Outcome<Self, Self::Error> {
match req.cookies().get_private("loggedin_user") {
Some(user) => {
2023-04-04 19:49:27 +02:00
let user: User = serde_json::from_str(user.value()).unwrap(); //TODO: fixme
2023-04-04 15:16:21 +02:00
match user.try_into() {
Ok(user) => Outcome::Success(user),
Err(_) => Outcome::Failure((Status::Unauthorized, LoginError::NotAnAdmin)),
}
}
None => Outcome::Failure((Status::Unauthorized, LoginError::NotLoggedIn)),
}
}
}
2023-04-06 18:57:10 +02:00
#[derive(Debug, Serialize, Deserialize)]
2023-04-06 08:06:50 +02:00
pub struct AdminUser {
2023-04-06 18:57:10 +02:00
pub(crate) user: User,
2023-04-06 08:06:50 +02:00
}
impl TryFrom<User> for AdminUser {
type Error = LoginError;
fn try_from(user: User) -> Result<Self, Self::Error> {
if user.is_admin {
Ok(AdminUser { user })
} else {
Err(LoginError::NotAnAdmin)
}
}
}
2023-04-04 15:16:21 +02:00
#[async_trait]
2023-04-06 08:06:50 +02:00
impl<'r> FromRequest<'r> for AdminUser {
2023-04-04 15:16:21 +02:00
type Error = LoginError;
2023-04-04 10:44:14 +02:00
async fn from_request(req: &'r Request<'_>) -> request::Outcome<Self, Self::Error> {
match req.cookies().get_private("loggedin_user") {
Some(user) => {
2023-04-04 19:49:27 +02:00
let user: User = serde_json::from_str(user.value()).unwrap(); //TODO: fixme
2023-04-04 10:44:14 +02:00
match user.try_into() {
Ok(user) => Outcome::Success(user),
Err(_) => Outcome::Failure((Status::Unauthorized, LoginError::NotAnAdmin)),
}
}
None => Outcome::Failure((Status::Unauthorized, LoginError::NotLoggedIn)),
}
}
}
2023-04-03 16:11:26 +02:00
#[cfg(test)]
mod test {
2023-04-03 22:03:45 +02:00
use crate::testdb;
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
#[sqlx::test]
fn succ_login_with_test_db() {
2023-04-03 22:03:45 +02:00
let pool = testdb!();
2023-04-03 17:21:34 +02:00
User::login(&pool, "admin".into(), "admin".into())
.await
.unwrap();
}
#[sqlx::test]
fn wrong_pw() {
2023-04-03 22:03:45 +02:00
let pool = testdb!();
2023-04-03 17:21:34 +02:00
assert!(User::login(&pool, "admin".into(), "admi".into())
.await
.is_err());
}
#[sqlx::test]
fn wrong_username() {
2023-04-03 22:03:45 +02:00
let pool = testdb!();
2023-04-03 17:21:34 +02:00
assert!(User::login(&pool, "admi".into(), "admin".into())
.await
.is_err());
2023-04-03 16:11:26 +02:00
}
}