diff --git a/src/library/user.rs b/src/library/user.rs index 84cc4be..ba944a0 100644 --- a/src/library/user.rs +++ b/src/library/user.rs @@ -9,6 +9,8 @@ use rand::RngCore; use serde::{Deserialize, Serialize}; use serde_json::json; +use crate::route::ToAPI; + fn gen_token(token_length: usize) -> String { let mut token_bytes = vec![0u8; token_length]; @@ -106,6 +108,15 @@ impl User { } } +impl ToAPI for User { + async fn api(&self) -> serde_json::Value { + json!({ + "username": self.username, + "role": self.role + }) + } +} + #[derive(Debug, Clone, Serialize, Deserialize, Model, Referencable)] pub struct Session { pub _id: String, diff --git a/src/main.rs b/src/main.rs index 04af6c0..7df36e6 100644 --- a/src/main.rs +++ b/src/main.rs @@ -5,6 +5,8 @@ mod library; mod route; use library::user::{User, UserRole}; +use mongod::Model; +use mongodb::bson::doc; use rocket::routes; use rocket::{http::Method, launch}; @@ -29,7 +31,13 @@ async fn rocket() -> _ { lib.rescan().await; - User::create("admin", "admin", UserRole::Admin).await; + // create initial admin user + if User::find(doc! { "username": "admin" }, None) + .await + .is_none() + { + User::create("admin", "admin", UserRole::Admin).await; + } let cache = cache::RouteCache::new(); @@ -50,6 +58,7 @@ async fn rocket() -> _ { route::user::login_route, route::user::passwd_route, route::user::user_create_route, + route::user::users_route, route::track::track_audio_opus128_route ], ) diff --git a/src/route/user.rs b/src/route/user.rs index f0bc06e..5c69061 100644 --- a/src/route/user.rs +++ b/src/route/user.rs @@ -1,7 +1,10 @@ use crate::library::user::Session; use crate::library::user::User; +use crate::route::to_api; +use crate::route::ToAPI; use mongod::Model; use mongodb::bson::doc; +use rocket::get; use rocket::http::Status; use rocket::outcome::Outcome; use rocket::post; @@ -14,6 +17,14 @@ use serde_json::json; use super::api_error; use super::FallibleApiResponse; +macro_rules! check_admin { + ($u:ident) => { + if !$u.is_admin() { + return Err(api_error("Forbidden")); + } + }; +} + #[rocket::async_trait] impl<'r> FromRequest<'r> for User { type Error = (); @@ -67,11 +78,18 @@ pub async fn passwd_route(passwd: Json, mut u: User) -> FallibleApiR })) } +#[get("/users")] +pub async fn users_route(u: User) -> FallibleApiResponse { + check_admin!(u); + + let users: Vec<_> = to_api(&User::find(doc! {}, None).await.unwrap()).await; + + Ok(json!({"users": users})) +} + #[post("/userCreate", data = "")] pub async fn user_create_route(user: Json, u: User) -> FallibleApiResponse { - if !u.is_admin() { - return Err(api_error("Forbidden")); - } + check_admin!(u); let new_user = User::create( &user.username,