use tayvo_authifier::models::Account;
use tayvo_authifier::util::hash_password;
use tayvo_authifier::{Authifier, Result};
use rocket::serde::json::Json;
use rocket::State;
use tayvo_rocket_empty::EmptyResponse;
#[derive(Serialize, Deserialize, JsonSchema)]
pub struct DataChangePassword {
pub password: String,
pub current_password: String,
}
#[openapi(tag = "Account")]
#[patch("/change/password", data = "<data>")]
pub async fn change_password(
authifier: &State<Authifier>,
mut account: Account,
data: Json<DataChangePassword>,
) -> Result<EmptyResponse> {
let data = data.into_inner();
authifier
.config
.password_scanning
.assert_safe(&data.password)
.await?;
account.verify_password(&data.current_password)?;
account.password = hash_password(data.password)?;
account.save(authifier).await.map(|_| EmptyResponse)
}
#[cfg(test)]
#[cfg(feature = "test")]
mod tests {
use crate::test::*;
#[async_std::test]
async fn success() {
use rocket::http::Header;
let (authifier, session, _, _) = for_test_authenticated("change_password::success").await;
let client = bootstrap_rocket_with_auth(
authifier,
routes![crate::routes::account::change_password::change_password],
)
.await;
let res = client
.patch("/change/password")
.header(ContentType::JSON)
.header(Header::new("X-Session-Token", session.token.clone()))
.body(
json!({
"password": "new password",
"current_password": "password_insecure"
})
.to_string(),
)
.dispatch()
.await;
assert_eq!(res.status(), Status::NoContent);
let res = client
.patch("/change/password")
.header(ContentType::JSON)
.header(Header::new("X-Session-Token", session.token))
.body(
json!({
"password": "sussy password",
"current_password": "new password"
})
.to_string(),
)
.dispatch()
.await;
assert_eq!(res.status(), Status::NoContent);
}
}