From 95c55921707ad91df0cd4a32a96baaee3ab98111 Mon Sep 17 00:00:00 2001 From: JMARyA Date: Thu, 8 Aug 2024 14:28:23 +0200 Subject: [PATCH] user --- src/library/artist.rs | 2 +- src/library/user.rs | 17 +++++++++++++++++ src/main.rs | 2 ++ src/route/user.rs | 34 ++++++++++++++++++++++++++++++++++ 4 files changed, 54 insertions(+), 1 deletion(-) diff --git a/src/library/artist.rs b/src/library/artist.rs index a64ea8d..0c5e49e 100644 --- a/src/library/artist.rs +++ b/src/library/artist.rs @@ -27,7 +27,7 @@ impl Artist { } /// Gets the image of an artist or `None` if it can't be found. - /// + /// /// This function gets a track from the artist. It then expects the folder structure to be `Artist/Album/Track.ext` and searches for an image file named `artist` in the artist folder. pub async fn get_image_of(id: &str) -> Option { let track_path = Track::find_one(doc! { "artist_id": reference_of!(Artist, id)}) diff --git a/src/library/user.rs b/src/library/user.rs index 910a8a1..84cc4be 100644 --- a/src/library/user.rs +++ b/src/library/user.rs @@ -68,6 +68,23 @@ impl User { Some(u.session().await) } + /// Change the password of a `User` + pub async fn passwd(&mut self, old: &str, new: &str) -> Result<(), ()> { + if self.verify_pw(old) { + self.update(&json!( + { + "password": bcrypt::hash(new, bcrypt::DEFAULT_COST).unwrap() + } + )) + .await + .map_err(|_| ())?; + + return Ok(()); + } + + Err(()) + } + pub async fn session(&self) -> Session { let s = Session { _id: uuid::Uuid::new_v4().to_string(), diff --git a/src/main.rs b/src/main.rs index 90cb2b1..04af6c0 100644 --- a/src/main.rs +++ b/src/main.rs @@ -48,6 +48,8 @@ async fn rocket() -> _ { route::track::track_audio_route, route::album::album_cover_route, route::user::login_route, + route::user::passwd_route, + route::user::user_create_route, route::track::track_audio_opus128_route ], ) diff --git a/src/route/user.rs b/src/route/user.rs index eff2091..f0bc06e 100644 --- a/src/route/user.rs +++ b/src/route/user.rs @@ -49,3 +49,37 @@ pub async fn login_route(login: Json) -> FallibleApiResponse { "token": ses.token })) } + +#[derive(Deserialize)] +pub struct PasswdData { + pub old: String, + pub new: String, +} + +#[post("/passwd", data = "")] +pub async fn passwd_route(passwd: Json, mut u: User) -> FallibleApiResponse { + u.passwd(&passwd.old, &passwd.new) + .await + .map_err(|_| api_error("Password change failed"))?; + + Ok(json!({ + "ok": 1 + })) +} + +#[post("/userCreate", data = "")] +pub async fn user_create_route(user: Json, u: User) -> FallibleApiResponse { + if !u.is_admin() { + return Err(api_error("Forbidden")); + } + + let new_user = User::create( + &user.username, + &user.password, + crate::library::user::UserRole::Regular, + ) + .await + .unwrap(); + + Ok(json!({"created": new_user._id})) +}