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