From 38589ae0c3a04581821b58971d1cec302e3236c4 Mon Sep 17 00:00:00 2001 From: Artemy Date: Tue, 26 Jul 2022 20:36:40 +0300 Subject: [PATCH] feat: change password method (OS-10) --- src/core.rs | 60 +++++++++++++++++++++++++++++++++++++++++++++++++++ src/main.rs | 1 + src/routes.rs | 15 +++++++++++++ src/types.rs | 5 +++++ 4 files changed, 81 insertions(+) diff --git a/src/core.rs b/src/core.rs index ddbd26f..7737e4f 100644 --- a/src/core.rs +++ b/src/core.rs @@ -64,6 +64,66 @@ impl Core { } } } + + pub async fn change_password( + &self, + name: &String, + old: &String, + new: &String, + ) -> serde_json::Value { + let response = self.users.find_one(doc! {"name":&name}, None).await; + match response { + Ok(user) => match user { + Some(user) => { + let old_pass_hash = self.hash(name.clone() + &old); + if &old_pass_hash == user.get_str("password").unwrap() { + let response = self + .users + .update_one( + doc! {"name": name}, + doc! {"$set": { + "password":&self.hash(name.clone() + &new), + }}, + None, + ) + .await; + match response { + Ok(_) => { + json! ({ + "code":"ok", + "msg":"User information updated" + }) + } + Err(_) => { + json! ({ + "code":"err", + "msg":"Some error" + }) + } + } + } else { + json! ({ + "code":"denied", + "msg":"Wrong password" + }) + } + } + None => { + json! ({ + "code":"err", + "msg":"User does not exist" + }) + } + }, + Err(_e) => { + json! ({ + "code":"err", + "msg":"User does not exist" + }) + } + } + } + pub async fn signin(&self, name: &String, password: &String) -> serde_json::Value { let response = self.users.find_one(doc! {"name":name}, None).await; match response { diff --git a/src/main.rs b/src/main.rs index 9b60091..1b3df46 100644 --- a/src/main.rs +++ b/src/main.rs @@ -82,6 +82,7 @@ async fn main() -> std::io::Result<()> { .wrap(HttpAuthentication::bearer(jwt_validator)) .service(routes::apps) .service(routes::update) + .service(routes::change_password) ) .service( web::scope("/auth") diff --git a/src/routes.rs b/src/routes.rs index 175957d..a47aeb1 100644 --- a/src/routes.rs +++ b/src/routes.rs @@ -20,6 +20,21 @@ pub async fn signin( pub async fn apps(app_data: web::Data) -> impl Responder { HttpResponse::Ok().json(app_data.core.get_apps().await) } +#[post("/change_password")] +#[has_any_permission("user", "admin")] +pub async fn change_password( + app_data: web::Data, + info: web::Json, + req: HttpRequest, +) -> impl Responder { + response( + app_data + .core + .change_password(&username(req), &info.old_password, &info.new_password) + .await, + ) +} + #[post("/update")] #[has_any_permission("user", "admin")] pub async fn update( diff --git a/src/types.rs b/src/types.rs index aba51e1..1862561 100644 --- a/src/types.rs +++ b/src/types.rs @@ -35,3 +35,8 @@ pub struct UserData { pub img: String, } +#[derive(Debug, Serialize, Deserialize)] +pub struct PasswordsInf { + pub old_password: String, + pub new_password: String, +}