rowt/src/rest/admin/user.rs

63 lines
1.6 KiB
Rust
Raw Normal View History

2023-04-04 10:44:14 +02:00
use crate::model::user::{AdminUser, User};
use rocket::{
form::Form,
get, post,
response::{Flash, Redirect},
routes, FromForm, Route, State,
};
use rocket_dyn_templates::{context, Template};
use sqlx::SqlitePool;
#[get("/user")]
async fn index(db: &State<SqlitePool>, _admin: AdminUser) -> Template {
let users = User::all(db).await;
Template::render("admin/user/index", context!(users))
}
#[get("/user/<user>/reset-pw")]
async fn resetpw(db: &State<SqlitePool>, _admin: AdminUser, user: i32) -> Flash<Redirect> {
let user = User::find_by_id(db, user).await;
match user {
Ok(user) => {
user.reset_pw(db).await;
Flash::success(
Redirect::to("/admin/user"),
format!("Successfully reset pw of {}", user.name),
)
}
Err(_) => Flash::error(Redirect::to("/admin/user"), "User does not exist"),
}
}
#[derive(FromForm)]
struct UserEditForm {
id: i32,
is_guest: bool,
is_cox: bool,
is_admin: bool,
}
#[post("/user", data = "<data>")]
2023-04-04 12:19:56 +02:00
async fn update(
db: &State<SqlitePool>,
data: Form<UserEditForm>,
_admin: AdminUser,
) -> Flash<Redirect> {
2023-04-04 10:44:14 +02:00
let user = User::find_by_id(db, data.id).await;
2023-04-04 19:49:27 +02:00
let Ok(user) = user else {
2023-04-04 10:44:14 +02:00
return Flash::error(
Redirect::to("/admin/user"),
format!("User with ID {} does not exist!", data.id),
)
};
user.update(db, data.is_cox, data.is_admin, data.is_guest)
.await;
Flash::success(Redirect::to("/admin/user"), "Successfully updated user")
}
pub fn routes() -> Vec<Route> {
routes![index, resetpw, update]
}