mas_handlers/admin/v1/users/
get.rs

1// Copyright 2024 New Vector Ltd.
2// Copyright 2024 The Matrix.org Foundation C.I.C.
3//
4// SPDX-License-Identifier: AGPL-3.0-only
5// Please see LICENSE in the repository root for full details.
6
7use aide::{OperationIo, transform::TransformOperation};
8use axum::{Json, response::IntoResponse};
9use hyper::StatusCode;
10use ulid::Ulid;
11
12use crate::{
13    admin::{
14        call_context::CallContext,
15        model::User,
16        params::UlidPathParam,
17        response::{ErrorResponse, SingleResponse},
18    },
19    impl_from_error_for_route,
20};
21
22#[derive(Debug, thiserror::Error, OperationIo)]
23#[aide(output_with = "Json<ErrorResponse>")]
24pub enum RouteError {
25    #[error(transparent)]
26    Internal(Box<dyn std::error::Error + Send + Sync + 'static>),
27
28    #[error("User ID {0} not found")]
29    NotFound(Ulid),
30}
31
32impl_from_error_for_route!(mas_storage::RepositoryError);
33
34impl IntoResponse for RouteError {
35    fn into_response(self) -> axum::response::Response {
36        let error = ErrorResponse::from_error(&self);
37        let status = match self {
38            Self::Internal(_) => StatusCode::INTERNAL_SERVER_ERROR,
39            Self::NotFound(_) => StatusCode::NOT_FOUND,
40        };
41        (status, Json(error)).into_response()
42    }
43}
44
45pub fn doc(operation: TransformOperation) -> TransformOperation {
46    operation
47        .id("getUser")
48        .summary("Get a user")
49        .tag("user")
50        .response_with::<200, Json<SingleResponse<User>>, _>(|t| {
51            let [sample, ..] = User::samples();
52            let response = SingleResponse::new_canonical(sample);
53            t.description("User was found").example(response)
54        })
55        .response_with::<404, RouteError, _>(|t| {
56            let response = ErrorResponse::from_error(&RouteError::NotFound(Ulid::nil()));
57            t.description("User was not found").example(response)
58        })
59}
60
61#[tracing::instrument(name = "handler.admin.v1.users.get", skip_all, err)]
62pub async fn handler(
63    CallContext { mut repo, .. }: CallContext,
64    id: UlidPathParam,
65) -> Result<Json<SingleResponse<User>>, RouteError> {
66    let user = repo
67        .user()
68        .lookup(*id)
69        .await?
70        .ok_or(RouteError::NotFound(*id))?;
71
72    Ok(Json(SingleResponse::new_canonical(User::from(user))))
73}