58 lines
1.7 KiB
Rust
58 lines
1.7 KiB
Rust
use axum::{Json, Router, extract::State, http::StatusCode, routing};
|
|
use secrecy::SecretString;
|
|
use serde::{Deserialize, Serialize};
|
|
use tracing::instrument;
|
|
|
|
use crate::{app::AppState, app_error::AppError, auth_user::AuthUser};
|
|
|
|
#[derive(Deserialize, Debug)]
|
|
pub struct CreateUser {
|
|
username: String,
|
|
password: String,
|
|
}
|
|
|
|
#[derive(Serialize, Debug)]
|
|
pub struct UserCreated {
|
|
username: String
|
|
}
|
|
|
|
|
|
|
|
|
|
pub fn users_routes() -> Router<AppState> {
|
|
Router::new()
|
|
.route("/create", routing::post(create_user))
|
|
.route("/auth", routing::get(check_auth))
|
|
.route("/me", routing::delete(delete_user))
|
|
}
|
|
|
|
#[instrument(skip_all)]
|
|
pub async fn create_user(State(st) : State<AppState>, Json(create_user): Json<CreateUser>) -> Result<(StatusCode, axum::Json<UserCreated>), AppError> {
|
|
tracing::info!("Creating user {:?}", create_user.username);
|
|
let username = st.users
|
|
.create_user(&create_user.username, SecretString::from(create_user.password))
|
|
.await?;
|
|
Ok((StatusCode::CREATED, Json(UserCreated{username})))
|
|
}
|
|
|
|
#[derive(Serialize, Debug)]
|
|
pub struct AuthResult {
|
|
authorized: String
|
|
}
|
|
|
|
#[instrument(skip_all)]
|
|
#[axum::debug_handler]
|
|
pub async fn check_auth(_: State<AppState>, _ : AuthUser) -> Result<Json<AuthResult>, AppError> {
|
|
Ok(Json(AuthResult{authorized: "OK".to_string()}))
|
|
}
|
|
|
|
#[derive(Debug, Serialize)]
|
|
pub struct DeleteResult { deleted: bool }
|
|
|
|
#[instrument(skip_all)]
|
|
#[axum::debug_handler]
|
|
pub async fn delete_user(State(app_state): State<AppState>, AuthUser{username} : AuthUser) -> Result<Json<DeleteResult>, AppError> {
|
|
app_state.users.delete_user(&username).await?;
|
|
Ok(Json(DeleteResult{deleted: true}))
|
|
}
|