summaryrefslogtreecommitdiff
path: root/src/user/handlers/password/mod.rs
blob: 91583258c13dc1199fa1020d00385f2b6cb75769 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
use axum::{
    extract::{Json, State},
    http::StatusCode,
    response::{IntoResponse, Response},
};

use crate::{
    app::App,
    clock::RequestedAt,
    error::Internal,
    token::{
        app,
        extract::{Identity, IdentityCookie},
    },
    user::{Password, User},
};

#[cfg(test)]
mod test;

pub async fn handler(
    State(app): State<App>,
    RequestedAt(now): RequestedAt,
    identity: Identity,
    cookie: IdentityCookie,
    Json(request): Json<Request>,
) -> Result<(IdentityCookie, Json<User>), Error> {
    let (login, secret) = app
        .tokens()
        .change_password(&identity.user, &request.password, &request.to, &now)
        .await
        .map_err(Error)?;
    let cookie = cookie.set(secret);
    Ok((cookie, Json(login)))
}

#[derive(serde::Deserialize)]
pub struct Request {
    pub password: Password,
    pub to: Password,
}

#[derive(Debug, thiserror::Error)]
#[error(transparent)]
pub struct Error(#[from] pub app::LoginError);

impl IntoResponse for Error {
    fn into_response(self) -> Response {
        let Self(error) = self;
        match error {
            app::LoginError::Rejected => {
                (StatusCode::BAD_REQUEST, "invalid name or password").into_response()
            }
            other => Internal::from(other).into_response(),
        }
    }
}