summaryrefslogtreecommitdiff
path: root/src/invite/handlers/accept/mod.rs
blob: 8bdaa51f68dbfb8f96e2ab73b38d973c5d0a6de8 (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
58
59
use axum::{
    extract::{Json, Path, State},
    http::StatusCode,
    response::{IntoResponse, Response},
};

use crate::{
    clock::RequestedAt,
    empty::Empty,
    error::{Internal, NotFound},
    invite::{app, app::Invites, handlers::PathInfo},
    name::Name,
    password::Password,
    token::extract::IdentityCookie,
};

#[cfg(test)]
mod test;

pub async fn handler(
    State(invites): State<Invites>,
    RequestedAt(accepted_at): RequestedAt,
    identity: IdentityCookie,
    Path(invite): Path<PathInfo>,
    Json(request): Json<Request>,
) -> Result<(IdentityCookie, Empty), Error> {
    let secret = invites
        .accept(&invite, &request.name, &request.password, &accepted_at)
        .await
        .map_err(Error)?;
    let identity = identity.set(secret);
    Ok((identity, Empty))
}

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

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

impl IntoResponse for Error {
    fn into_response(self) -> Response {
        let Self(error) = self;
        match error {
            app::AcceptError::NotFound(_) => NotFound(error).into_response(),
            app::AcceptError::InvalidName(_) => {
                (StatusCode::BAD_REQUEST, error.to_string()).into_response()
            }
            app::AcceptError::DuplicateLogin(_) => {
                (StatusCode::CONFLICT, error.to_string()).into_response()
            }
            other => Internal::from(other).into_response(),
        }
    }
}