feat: change password method (OS-10)

This commit is contained in:
Artemy 2022-07-26 20:36:40 +03:00
parent 4340c6d212
commit 38589ae0c3
4 changed files with 81 additions and 0 deletions

View file

@ -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 { pub async fn signin(&self, name: &String, password: &String) -> serde_json::Value {
let response = self.users.find_one(doc! {"name":name}, None).await; let response = self.users.find_one(doc! {"name":name}, None).await;
match response { match response {

View file

@ -82,6 +82,7 @@ async fn main() -> std::io::Result<()> {
.wrap(HttpAuthentication::bearer(jwt_validator)) .wrap(HttpAuthentication::bearer(jwt_validator))
.service(routes::apps) .service(routes::apps)
.service(routes::update) .service(routes::update)
.service(routes::change_password)
) )
.service( .service(
web::scope("/auth") web::scope("/auth")

View file

@ -20,6 +20,21 @@ pub async fn signin(
pub async fn apps(app_data: web::Data<crate::AppState>) -> impl Responder { pub async fn apps(app_data: web::Data<crate::AppState>) -> impl Responder {
HttpResponse::Ok().json(app_data.core.get_apps().await) 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<crate::AppState>,
info: web::Json<PasswordsInf>,
req: HttpRequest,
) -> impl Responder {
response(
app_data
.core
.change_password(&username(req), &info.old_password, &info.new_password)
.await,
)
}
#[post("/update")] #[post("/update")]
#[has_any_permission("user", "admin")] #[has_any_permission("user", "admin")]
pub async fn update( pub async fn update(

View file

@ -35,3 +35,8 @@ pub struct UserData {
pub img: String, pub img: String,
} }
#[derive(Debug, Serialize, Deserialize)]
pub struct PasswordsInf {
pub old_password: String,
pub new_password: String,
}