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, _admin: AdminUser) -> Template { let users = User::all(db).await; Template::render("admin/user/index", context!(users)) } #[get("/user//reset-pw")] async fn resetpw(db: &State, _admin: AdminUser, user: i32) -> Flash { 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 = "")] async fn update( db: &State, data: Form, _admin: AdminUser, ) -> Flash { let user = User::find_by_id(db, data.id).await; let Ok(user) = user else { 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") } #[derive(FromForm)] struct UserAddForm { name: String, is_guest: bool, } #[post("/user/new", data = "")] async fn create( db: &State, data: Form, _admin: AdminUser, ) -> Flash { if User::create(db, data.name.clone(), data.is_guest).await { //TODO: fix clone() above Flash::success(Redirect::to("/admin/user"), "Successfully created user") } else { Flash::error( Redirect::to("/admin/user"), format!("User {} already exists", data.name), ) } } pub fn routes() -> Vec { routes![index, resetpw, update, create] }