finish admin tasks

This commit is contained in:
2023-04-04 10:44:14 +02:00
parent 202964bfa4
commit 3dfc64071c
11 changed files with 284 additions and 23 deletions

View File

@ -10,19 +10,37 @@ use sqlx::{FromRow, SqlitePool};
#[derive(FromRow, Debug, Serialize, Deserialize)]
pub struct User {
id: i64,
name: String,
pw: String,
pub id: i64,
pub name: String,
pw: Option<String>,
is_cox: bool,
is_admin: bool,
is_guest: bool,
}
pub struct AdminUser {
user: User,
}
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)
}
}
}
#[derive(Debug)]
pub enum LoginError {
SqlxError(sqlx::Error),
InvalidAuthenticationCombo,
NotLoggedIn,
NotAnAdmin,
NoPasswordSet(User),
}
impl From<sqlx::Error> for LoginError {
@ -31,6 +49,35 @@ impl From<sqlx::Error> for LoginError {
}
}
impl User {
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
}
pub async fn find_by_id(db: &SqlitePool, id: i32) -> Result<Self, sqlx::Error> {
let user: User = sqlx::query_as!(
User,
"
SELECT id, name, pw, is_cox, is_admin, is_guest
FROM user
WHERE id like ?
",
id
)
.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,
@ -47,21 +94,57 @@ WHERE name like ?
Ok(user)
}
fn get_hashed_pw(pw: String) -> 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()
}
pub async fn login(db: &SqlitePool, name: String, pw: String) -> Result<Self, LoginError> {
let user = User::find_by_name(db, name).await?;
let salt = SaltString::from_b64("dS/X5/sPEKTj4Rzs/CuvzQ").unwrap();
let argon2 = Argon2::default();
let password_hash = argon2
.hash_password(&pw.as_bytes(), &salt)
.unwrap()
.to_string();
match user.pw.clone() {
Some(user_pw) => {
let password_hash = Self::get_hashed_pw(pw);
if password_hash == user_pw {
return Ok(user);
}
if password_hash == user.pw {
return Ok(user);
Err(LoginError::InvalidAuthenticationCombo)
}
None => Err(LoginError::NoPasswordSet(user)),
}
}
Err(LoginError::InvalidAuthenticationCombo)
pub async fn all(db: &SqlitePool) -> Vec<Self> {
sqlx::query_as!(
User,
"
SELECT id, name, pw, is_cox, is_admin, is_guest
FROM user
"
)
.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) {
let pw = Self::get_hashed_pw(pw);
sqlx::query!("UPDATE user SET pw = ? where id = ?", pw, self.id)
.execute(db)
.await
.unwrap(); //TODO: fixme
}
}
@ -80,6 +163,24 @@ impl<'r> FromRequest<'r> for User {
}
}
#[async_trait]
impl<'r> FromRequest<'r> for AdminUser {
type Error = LoginError;
async fn from_request(req: &'r Request<'_>) -> request::Outcome<Self, Self::Error> {
match req.cookies().get_private("loggedin_user") {
Some(user) => {
let user: User = serde_json::from_str(&user.value()).unwrap(); //TODO: fixme
match user.try_into() {
Ok(user) => Outcome::Success(user),
Err(_) => Outcome::Failure((Status::Unauthorized, LoginError::NotAnAdmin)),
}
}
None => Outcome::Failure((Status::Unauthorized, LoginError::NotLoggedIn)),
}
}
}
#[cfg(test)]
mod test {
use crate::testdb;