rowt/src/model/user.rs

595 lines
16 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-07-31 16:33:44 +02:00
use chrono::{Datelike, Local, NaiveDate};
2023-07-11 09:16:13 +02:00
use log::info;
2023-04-03 22:03:45 +02:00
use rocket::{
async_trait,
http::{Cookie, Status},
2023-04-03 22:03:45 +02:00
request::{self, FromRequest, Outcome},
time::{Duration, OffsetDateTime},
2023-07-31 16:33:44 +02:00
Request,
2023-04-03 22:03:45 +02:00
};
use serde::{Deserialize, Serialize};
2023-07-31 16:33:44 +02:00
use sqlx::{FromRow, SqlitePool};
2023-04-03 16:11:26 +02:00
2023-07-25 11:31:51 +02:00
use super::{log::Log, tripdetails::TripDetails, Day};
2023-06-08 17:23:23 +02:00
2023-07-31 16:33:44 +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,
2023-07-24 13:01:39 +02:00
pub pw: Option<String>,
2023-04-04 15:38:47 +02:00
pub is_cox: bool,
2023-04-28 21:19:51 +02:00
pub is_admin: bool,
pub is_guest: bool,
2023-08-02 14:29:19 +02:00
pub is_tech: bool,
2023-07-24 13:01:39 +02:00
pub deleted: bool,
2023-07-31 16:33:44 +02:00
pub last_access: Option<chrono::NaiveDateTime>,
2023-04-03 16:11:26 +02:00
}
#[derive(Debug, Serialize, Deserialize)]
pub struct UserWithWaterStatus {
#[serde(flatten)]
pub user: User,
pub on_water: bool,
}
impl UserWithWaterStatus {
pub async fn from_user(user: User, db: &SqlitePool) -> Self {
Self {
on_water: user.on_water(db).await,
user,
}
}
}
impl PartialEq for User {
fn eq(&self, other: &Self) -> bool {
self.id == other.id
}
}
2023-04-03 17:21:34 +02:00
#[derive(Debug)]
2023-04-03 16:11:26 +02:00
pub enum LoginError {
InvalidAuthenticationCombo,
UserNotFound,
2023-07-28 11:50:11 +02:00
UserDeleted,
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-08-02 14:29:19 +02:00
NotATech,
2023-04-04 10:44:14 +02:00
NoPasswordSet(User),
2023-05-03 15:59:28 +02:00
DeserializationError,
2023-04-03 16:11:26 +02:00
}
impl User {
2023-07-24 20:56:46 +02:00
pub async fn rowed_km(&self, db: &SqlitePool) -> i32 {
sqlx::query!(
"SELECT COALESCE(SUM(distance_in_km),0) as rowed_km
FROM (
SELECT distance_in_km
FROM logbook
WHERE shipmaster = ?1
UNION
SELECT l.distance_in_km
FROM logbook l
INNER JOIN rower r ON r.logbook_id = l.id
WHERE r.rower_id = ?1
);",
self.id,
)
.fetch_one(db)
.await
.unwrap()
.rowed_km
.unwrap()
}
2023-04-10 14:25:31 +02:00
pub async fn find_by_id(db: &SqlitePool, id: i32) -> Option<Self> {
2023-07-31 16:33:44 +02:00
sqlx::query_as!(
Self,
2023-04-24 14:34:06 +02:00
"
2023-08-02 14:29:19 +02:00
SELECT id, name, pw, is_cox, is_admin, is_guest, deleted, last_access, is_tech
2023-04-04 10:44:14 +02:00
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
2023-07-31 16:33:44 +02:00
.ok()
2023-04-04 10:44:14 +02:00
}
2023-05-24 12:11:55 +02:00
pub async fn find_by_name(db: &SqlitePool, name: &str) -> Option<Self> {
2023-07-31 16:33:44 +02:00
sqlx::query_as!(
Self,
2023-04-24 14:34:06 +02:00
"
2023-08-02 14:29:19 +02:00
SELECT id, name, pw, is_cox, is_admin, is_guest, deleted, last_access, is_tech
2023-04-03 16:11:26 +02:00
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
2023-07-31 16:33:44 +02:00
.ok()
2023-04-03 16:11:26 +02:00
}
pub async fn on_water(&self, db: &SqlitePool) -> bool {
2023-07-30 22:59:47 +02:00
if sqlx::query!(
"SELECT * FROM logbook WHERE shipmaster=? AND arrival is null",
self.id
)
.fetch_optional(db)
.await
.unwrap()
.is_some()
2023-07-30 22:59:47 +02:00
{
return true;
}
if sqlx::query!(
"SELECT * FROM logbook JOIN rower ON rower.logbook_id=logbook.id WHERE rower_id=? AND arrival is null",
self.id
)
.fetch_optional(db)
.await
.unwrap()
.is_some()
{
return true;
}
false
}
2023-04-26 11:22:22 +02:00
pub async fn all(db: &SqlitePool) -> Vec<Self> {
2023-07-31 16:33:44 +02:00
sqlx::query_as!(
Self,
2023-04-26 11:22:22 +02:00
"
2023-08-02 14:29:19 +02:00
SELECT id, name, pw, is_cox, is_admin, is_guest, deleted, last_access, is_tech
2023-04-26 11:22:22 +02:00
FROM user
2023-04-28 19:29:20 +02:00
WHERE deleted = 0
2023-06-06 10:08:54 +02:00
ORDER BY last_access DESC
2023-04-26 11:22:22 +02:00
"
)
.fetch_all(db)
.await
2023-07-31 16:25:07 +02:00
.unwrap()
2023-04-26 11:22:22 +02:00
}
2023-07-23 12:17:57 +02:00
pub async fn cox(db: &SqlitePool) -> Vec<Self> {
2023-07-31 16:33:44 +02:00
sqlx::query_as!(
Self,
2023-07-23 12:17:57 +02:00
"
2023-08-02 14:29:19 +02:00
SELECT id, name, pw, is_cox, is_admin, is_guest, deleted, last_access, is_tech
2023-07-23 12:17:57 +02:00
FROM user
WHERE deleted = 0 AND is_cox=true
ORDER BY last_access DESC
"
)
.fetch_all(db)
.await
2023-07-31 16:25:07 +02:00
.unwrap()
2023-07-23 12:17:57 +02:00
}
2023-05-24 12:11:55 +02:00
pub async fn create(db: &SqlitePool, name: &str, is_guest: bool) -> bool {
2023-04-26 11:22:22 +02:00
sqlx::query!(
"INSERT INTO USER(name, is_guest) VALUES (?,?)",
name,
is_guest,
)
.execute(db)
.await
.is_ok()
}
2023-08-02 14:29:19 +02:00
pub async fn update(
&self,
db: &SqlitePool,
is_cox: bool,
is_admin: bool,
is_guest: bool,
is_tech: bool,
) {
2023-04-26 11:22:22 +02:00
sqlx::query!(
2023-08-02 14:29:19 +02:00
"UPDATE user SET is_cox = ?, is_admin = ?, is_guest = ?, is_tech = ? where id = ?",
2023-04-26 11:22:22 +02:00
is_cox,
is_admin,
is_guest,
2023-08-02 14:29:19 +02:00
is_tech,
2023-04-26 11:22:22 +02:00
self.id
)
.execute(db)
.await
.unwrap(); //Okay, because we can only create a User of a valid id
2023-04-04 10:44:14 +02:00
}
2023-05-24 12:11:55 +02:00
pub async fn login(db: &SqlitePool, name: &str, pw: &str) -> Result<Self, LoginError> {
2023-07-11 14:37:48 +02:00
let name = name.trim(); // just to make sure...
2023-04-26 12:52:19 +02:00
let Some(user) = User::find_by_name(db, name).await else {
2023-07-28 11:50:11 +02:00
Log::create(db, format!("Username ({name}) not found (tried to login)")).await;
2023-04-26 12:52:19 +02:00
return Err(LoginError::InvalidAuthenticationCombo); // Username not found
2023-04-10 14:25:31 +02:00
};
2023-04-03 16:11:26 +02:00
2023-04-28 19:29:20 +02:00
if user.deleted {
2023-07-28 11:50:11 +02:00
Log::create(
db,
format!("User ({name}) already deleted (tried to login)."),
)
.await;
2023-04-28 19:29:20 +02:00
return Err(LoginError::InvalidAuthenticationCombo); //User existed sometime ago; has
//been deleted
}
2023-07-25 13:32:20 +02:00
if let Some(user_pw) = user.pw.as_ref() {
let password_hash = &Self::get_hashed_pw(pw);
if password_hash == user_pw {
return Ok(user);
2023-07-11 09:16:13 +02:00
}
2023-07-25 13:32:20 +02:00
Log::create(db, format!("User {name} supplied the wrong PW")).await;
Err(LoginError::InvalidAuthenticationCombo)
} else {
info!("User {name} has no PW set");
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 reset_pw(&self, db: &SqlitePool) {
sqlx::query!("UPDATE user SET pw = null where id = ?", self.id)
.execute(db)
.await
2023-04-26 11:22:22 +02:00
.unwrap(); //Okay, because we can only create a User of a valid id
2023-04-04 10:44:14 +02:00
}
2023-05-24 12:11:55 +02:00
pub async fn update_pw(&self, db: &SqlitePool, pw: &str) {
2023-05-30 14:36:23 +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
2023-04-26 11:22:22 +02:00
.unwrap(); //Okay, because we can only create a User of a valid id
}
fn get_hashed_pw(pw: &str) -> String {
let salt = SaltString::from_b64("dS/X5/sPEKTj4Rzs/CuvzQ").unwrap();
let argon2 = Argon2::default();
argon2
.hash_password(pw.as_bytes(), &salt)
.unwrap()
.to_string()
2023-04-03 16:11:26 +02:00
}
2023-04-28 19:29:20 +02:00
2023-05-10 08:57:20 +02:00
pub async fn logged_in(&self, db: &SqlitePool) {
sqlx::query!(
"UPDATE user SET last_access = CURRENT_TIMESTAMP where id = ?",
self.id
)
.execute(db)
.await
.unwrap(); //Okay, because we can only create a User of a valid id
}
2023-04-28 19:29:20 +02:00
pub async fn delete(&self, db: &SqlitePool) {
sqlx::query!("UPDATE user SET deleted=1 WHERE id=?", self.id)
.execute(db)
.await
.unwrap(); //Okay, because we can only create a User of a valid id
}
2023-06-08 17:23:23 +02:00
pub async fn get_days(&self, db: &SqlitePool) -> Vec<Day> {
let mut days = Vec::new();
for i in 0..self.amount_days_to_show() {
let date = (Local::now() + chrono::Duration::days(i)).date_naive();
if self.is_guest {
days.push(Day::new_guest(db, date, false).await);
} else {
days.push(Day::new(db, date, false).await);
}
}
for date in TripDetails::pinned_days(db, self.amount_days_to_show() - 1).await {
2023-06-08 17:23:23 +02:00
if self.is_guest {
let day = Day::new_guest(db, date, true).await;
if !day.planned_events.is_empty() {
days.push(day);
}
} else {
days.push(Day::new(db, date, true).await);
}
}
days
}
fn amount_days_to_show(&self) -> i64 {
if self.is_cox {
let end_of_year = NaiveDate::from_ymd_opt(Local::now().year(), 12, 31).unwrap(); //Ok,
//december
//has 31
//days
end_of_year
.signed_duration_since(Local::now().date_naive())
.num_days()
+ 1
} else {
6
}
}
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_id) => match user_id.value().parse::<i32>() {
Ok(user_id) => {
2023-05-10 08:57:20 +02:00
let db = req.rocket().state::<SqlitePool>().unwrap();
let Some(user) = User::find_by_id(db, user_id).await else {
return Outcome::Failure((Status::Unauthorized, LoginError::UserNotFound));
};
2023-07-28 11:50:11 +02:00
if user.deleted {
return Outcome::Failure((Status::Unauthorized, LoginError::UserDeleted));
}
2023-05-10 08:57:20 +02:00
user.logged_in(db).await;
let mut cookie = Cookie::new("loggedin_user", format!("{}", user.id));
cookie.set_expires(OffsetDateTime::now_utc() + Duration::weeks(12));
req.cookies().add_private(cookie);
2023-05-10 08:57:20 +02:00
Outcome::Success(user)
}
2023-05-03 15:59:28 +02:00
Err(_) => {
println!("{:?}", user_id.value());
2023-05-03 15:59:28 +02:00
Outcome::Failure((Status::Unauthorized, LoginError::DeserializationError))
}
},
2023-04-03 22:03:45 +02:00
None => Outcome::Failure((Status::Unauthorized, LoginError::NotLoggedIn)),
}
}
}
2023-08-02 14:29:19 +02:00
pub struct TechUser {
pub(crate) user: User,
}
impl Deref for TechUser {
type Target = User;
fn deref(&self) -> &Self::Target {
&self.user
}
}
impl TryFrom<User> for TechUser {
type Error = LoginError;
fn try_from(user: User) -> Result<Self, Self::Error> {
if user.is_tech {
Ok(TechUser { user })
} else {
Err(LoginError::NotATech)
}
}
}
#[async_trait]
impl<'r> FromRequest<'r> for TechUser {
type Error = LoginError;
async fn from_request(req: &'r Request<'_>) -> request::Outcome<Self, Self::Error> {
match User::from_request(req).await {
Outcome::Success(user) => match user.try_into() {
Ok(user) => Outcome::Success(user),
Err(_) => Outcome::Failure((Status::Unauthorized, LoginError::NotACox)),
},
Outcome::Failure(f) => Outcome::Failure(f),
Outcome::Forward(f) => Outcome::Forward(f),
}
}
}
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> {
2023-05-03 16:06:27 +02:00
match User::from_request(req).await {
Outcome::Success(user) => match user.try_into() {
Ok(user) => Outcome::Success(user),
Err(_) => Outcome::Failure((Status::Unauthorized, LoginError::NotACox)),
},
Outcome::Failure(f) => Outcome::Failure(f),
Outcome::Forward(f) => Outcome::Forward(f),
2023-04-04 15:16:21 +02:00
}
}
}
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> {
2023-05-03 16:06:27 +02:00
match User::from_request(req).await {
Outcome::Success(user) => match user.try_into() {
Ok(user) => Outcome::Success(user),
Err(_) => Outcome::Failure((Status::Unauthorized, LoginError::NotAnAdmin)),
},
Outcome::Failure(f) => Outcome::Failure(f),
Outcome::Forward(f) => Outcome::Forward(f),
2023-04-04 10:44:14 +02:00
}
}
}
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-26 11:22:22 +02:00
#[sqlx::test]
fn test_find_correct_id() {
let pool = testdb!();
let user = User::find_by_id(&pool, 1).await.unwrap();
assert_eq!(user.id, 1);
}
#[sqlx::test]
fn test_find_wrong_id() {
let pool = testdb!();
let user = User::find_by_id(&pool, 1337).await;
assert!(user.is_none());
}
#[sqlx::test]
fn test_find_correct_name() {
let pool = testdb!();
let user = User::find_by_name(&pool, "admin".into()).await.unwrap();
assert_eq!(user.id, 1);
}
#[sqlx::test]
fn test_find_wrong_name() {
let pool = testdb!();
let user = User::find_by_name(&pool, "name-does-not-exist".into()).await;
assert!(user.is_none());
}
#[sqlx::test]
fn test_all() {
let pool = testdb!();
let res = User::all(&pool).await;
assert!(res.len() > 3);
}
2023-07-23 12:17:57 +02:00
#[sqlx::test]
fn test_cox() {
let pool = testdb!();
let res = User::cox(&pool).await;
2023-09-23 18:26:04 +02:00
assert_eq!(res.len(), 3);
2023-07-23 12:17:57 +02:00
}
2023-04-26 11:22:22 +02:00
#[sqlx::test]
fn test_succ_create() {
let pool = testdb!();
assert_eq!(
User::create(&pool, "new-user-name".into(), false).await,
true
);
}
#[sqlx::test]
fn test_duplicate_name_create() {
let pool = testdb!();
assert_eq!(User::create(&pool, "admin".into(), false).await, false);
}
#[sqlx::test]
fn test_update() {
let pool = testdb!();
let user = User::find_by_id(&pool, 1).await.unwrap();
2023-08-02 14:29:19 +02:00
user.update(&pool, false, false, false, false).await;
2023-04-26 11:22:22 +02:00
let user = User::find_by_id(&pool, 1).await.unwrap();
assert_eq!(user.is_admin, false);
}
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
}
2023-04-26 11:22:22 +02:00
#[sqlx::test]
fn reset() {
let pool = testdb!();
let user = User::find_by_id(&pool, 1).await.unwrap();
user.reset_pw(&pool).await;
let user = User::find_by_id(&pool, 1).await.unwrap();
assert_eq!(user.pw, None);
}
#[sqlx::test]
fn update_pw() {
let pool = testdb!();
let user = User::find_by_id(&pool, 1).await.unwrap();
assert!(User::login(&pool, "admin".into(), "abc".into())
.await
.is_err());
user.update_pw(&pool, "abc".into()).await;
User::login(&pool, "admin".into(), "abc".into())
.await
.unwrap();
}
2023-04-03 16:11:26 +02:00
}