mas_handlers/admin/v1/users/
by_username.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, extract::Path, response::IntoResponse};
9use hyper::StatusCode;
10use mas_axum_utils::record_error;
11use schemars::JsonSchema;
12use serde::Deserialize;
13
14use crate::{
15    admin::{
16        call_context::CallContext,
17        model::User,
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 with username {0:?} not found")]
30    NotFound(String),
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
47#[derive(Deserialize, JsonSchema)]
48pub struct UsernamePathParam {
49    /// The username (localpart) of the user to get
50    username: String,
51}
52
53pub fn doc(operation: TransformOperation) -> TransformOperation {
54    operation
55        .id("getUserByUsername")
56        .summary("Get a user by its username (localpart)")
57        .tag("user")
58        .response_with::<200, Json<SingleResponse<User>>, _>(|t| {
59            let [sample, ..] = User::samples();
60            let response =
61                SingleResponse::new(sample, "/api/admin/v1/users/by-username/alice".to_owned());
62            t.description("User was found").example(response)
63        })
64        .response_with::<404, RouteError, _>(|t| {
65            let response = ErrorResponse::from_error(&RouteError::NotFound("alice".to_owned()));
66            t.description("User was not found").example(response)
67        })
68}
69
70#[tracing::instrument(name = "handler.admin.v1.users.by_username", skip_all)]
71pub async fn handler(
72    CallContext { mut repo, .. }: CallContext,
73    Path(UsernamePathParam { username }): Path<UsernamePathParam>,
74) -> Result<Json<SingleResponse<User>>, RouteError> {
75    let self_path = format!("/api/admin/v1/users/by-username/{username}");
76    let user = repo
77        .user()
78        .find_by_username(&username)
79        .await?
80        .ok_or(RouteError::NotFound(username))?;
81
82    Ok(Json(SingleResponse::new(User::from(user), self_path)))
83}