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 mas_axum_utils::record_error;
11use ulid::Ulid;
12
13use crate::{
14    admin::{
15        call_context::CallContext,
16        model::User,
17        params::UlidPathParam,
18        response::{ErrorResponse, SingleResponse},
19    },
20    impl_from_error_for_route,
21};
22
23#[derive(Debug, thiserror::Error, OperationIo)]
24#[aide(output_with = "Json<ErrorResponse>")]
25pub enum RouteError {
26    #[error(transparent)]
27    Internal(Box<dyn std::error::Error + Send + Sync + 'static>),
28
29    #[error("User ID {0} not found")]
30    NotFound(Ulid),
31}
32
33impl_from_error_for_route!(mas_storage::RepositoryError);
34
35impl IntoResponse for RouteError {
36    fn into_response(self) -> axum::response::Response {
37        let error = ErrorResponse::from_error(&self);
38        let sentry_event_id = record_error!(self, Self::Internal(_));
39        let status = match self {
40            Self::Internal(_) => StatusCode::INTERNAL_SERVER_ERROR,
41            Self::NotFound(_) => StatusCode::NOT_FOUND,
42        };
43        (status, sentry_event_id, Json(error)).into_response()
44    }
45}
46
47pub fn doc(operation: TransformOperation) -> TransformOperation {
48    operation
49        .id("getUser")
50        .summary("Get a user")
51        .tag("user")
52        .response_with::<200, Json<SingleResponse<User>>, _>(|t| {
53            let [sample, ..] = User::samples();
54            let response = SingleResponse::new_canonical(sample);
55            t.description("User was found").example(response)
56        })
57        .response_with::<404, RouteError, _>(|t| {
58            let response = ErrorResponse::from_error(&RouteError::NotFound(Ulid::nil()));
59            t.description("User was not found").example(response)
60        })
61}
62
63#[tracing::instrument(name = "handler.admin.v1.users.get", skip_all)]
64pub async fn handler(
65    CallContext { mut repo, .. }: CallContext,
66    id: UlidPathParam,
67) -> Result<Json<SingleResponse<User>>, RouteError> {
68    let user = repo
69        .user()
70        .lookup(*id)
71        .await?
72        .ok_or(RouteError::NotFound(*id))?;
73
74    Ok(Json(SingleResponse::new_canonical(User::from(user))))
75}