130 lines
4.6 KiB
Rust
130 lines
4.6 KiB
Rust
//! Administration (admin role only): users, roles, credits.
|
|||
|
|
|
||
|
|
use axum::Json;
|
||
|
|
use axum::extract::{Path, Query, State};
|
||
|
|
use axum::http::StatusCode;
|
||
|
|
use axum_extra::extract::WithRejection;
|
||
|
|
use db::Role;
|
||
|
|
use serde::Deserialize;
|
||
|
|
use serde_json::{Value, json};
|
||
|
|
use time::OffsetDateTime;
|
||
|
|
use uuid::Uuid;
|
||
|
|
|
||
|
|
use super::{Body, IdPath, St};
|
||
|
|
use crate::auth::AdminUser;
|
||
|
|
use crate::error::{ApiError, ApiResult};
|
||
|
|
use crate::views::{rfc3339, rfc3339_opt};
|
||
|
|
|
||
|
|
#[derive(Deserialize)]
|
||
|
|
pub struct UserQuery {
|
||
|
|
/// Part of the e-mail address or display name.
|
||
|
|
q: Option<String>,
|
||
|
|
limit: Option<i64>,
|
||
|
|
offset: Option<i64>,
|
||
|
|
}
|
||
|
|
|
||
|
|
pub async fn list_users(
|
||
|
|
State(state): St,
|
||
|
|
_admin: AdminUser,
|
||
|
|
WithRejection(Query(query), _): WithRejection<Query<UserQuery>, ApiError>,
|
||
|
|
) -> ApiResult<Json<Value>> {
|
||
|
|
let limit = query.limit.unwrap_or(50).clamp(1, 200);
|
||
|
|
let offset = query.offset.unwrap_or(0).max(0);
|
||
|
|
let pattern = query.q.as_deref().map(|q| format!("%{}%", q.trim().replace(['%', '_'], "")));
|
||
|
|
type Row = (Uuid, String, Option<String>, Vec<String>, bool, OffsetDateTime, Option<OffsetDateTime>, i64, i64);
|
||
|
|
let rows: Vec<Row> = sqlx::query_as(
|
||
|
|
"SELECT u.id, u.email, u.display_name, u.roles, u.email_verified_at IS NOT NULL, u.created_at, u.last_login_at, \
|
||
|
|
(SELECT count(*) FROM charts c WHERE c.owner_id = u.id), \
|
||
|
|
(SELECT COALESCE(SUM(delta), 0)::bigint FROM credit_ledger l WHERE l.user_id = u.id) \
|
||
|
|
FROM users u \
|
||
|
|
WHERE $1::text IS NULL OR u.email ILIKE $1 OR u.display_name ILIKE $1 \
|
||
|
|
ORDER BY u.created_at DESC LIMIT $2 OFFSET $3",
|
||
|
|
)
|
||
|
|
.bind(pattern)
|
||
|
|
.bind(limit)
|
||
|
|
.bind(offset)
|
||
|
|
.fetch_all(&state.db)
|
||
|
|
.await?;
|
||
|
|
let users: Vec<Value> = rows
|
||
|
|
.into_iter()
|
||
|
|
.map(|(id, email, name, roles, verified, created, last_login, charts, credits)| {
|
||
|
|
json!({
|
||
|
|
"id": id, "email": email, "display_name": name, "roles": roles, "email_verified": verified,
|
||
|
|
"created_at": rfc3339(created), "last_login_at": rfc3339_opt(last_login),
|
||
|
|
"charts": charts, "credits": credits,
|
||
|
|
})
|
||
|
|
})
|
||
|
|
.collect();
|
||
|
|
Ok(Json(json!({ "users": users, "limit": limit, "offset": offset })))
|
||
|
|
}
|
||
|
|
|
||
|
|
#[derive(Deserialize)]
|
||
|
|
#[serde(deny_unknown_fields)]
|
||
|
|
pub struct UpdateUser {
|
||
|
|
roles: Vec<Role>,
|
||
|
|
}
|
||
|
|
|
||
|
|
pub async fn update_user(
|
||
|
|
State(state): St,
|
||
|
|
AdminUser(admin): AdminUser,
|
||
|
|
WithRejection(Path(id), _): IdPath,
|
||
|
|
WithRejection(Json(req), _): Body<UpdateUser>,
|
||
|
|
) -> ApiResult<Json<Value>> {
|
||
|
|
let mut roles: Vec<&str> = req.roles.iter().map(|r| r.as_str()).collect();
|
||
|
|
roles.sort_unstable();
|
||
|
|
roles.dedup();
|
||
|
|
if roles.is_empty() {
|
||
|
|
return Err(ApiError::BadRequest("at least one role is required".into()));
|
||
|
|
}
|
||
|
|
if id == admin.id() && !roles.contains(&Role::Admin.as_str()) {
|
||
|
|
return Err(ApiError::conflict("own_admin_role", "you cannot remove your own admin role"));
|
||
|
|
}
|
||
|
|
let row: Option<(Uuid, Vec<String>)> =
|
||
|
|
sqlx::query_as("UPDATE users SET roles = $1, updated_at = now() WHERE id = $2 RETURNING id, roles")
|
||
|
|
.bind(&roles)
|
||
|
|
.bind(id)
|
||
|
|
.fetch_optional(&state.db)
|
||
|
|
.await?;
|
||
|
|
let (id, roles) = row.ok_or(ApiError::NotFound("user"))?;
|
||
|
|
tracing::info!(admin = %admin.id(), user = %id, ?roles, "roles changed");
|
||
|
|
Ok(Json(json!({ "id": id, "roles": roles })))
|
||
|
|
}
|
||
|
|
|
||
|
|
#[derive(Deserialize)]
|
||
|
|
#[serde(deny_unknown_fields)]
|
||
|
|
pub struct AdjustCredits {
|
||
|
|
/// Positive to add, negative to take away.
|
||
|
|
delta: i32,
|
||
|
|
note: Option<String>,
|
||
|
|
}
|
||
|
|
|
||
|
|
pub async fn adjust_credits(
|
||
|
|
State(state): St,
|
||
|
|
AdminUser(admin): AdminUser,
|
||
|
|
WithRejection(Path(id), _): IdPath,
|
||
|
|
WithRejection(Json(req), _): Body<AdjustCredits>,
|
||
|
|
) -> ApiResult<(StatusCode, Json<Value>)> {
|
||
|
|
if req.delta == 0 {
|
||
|
|
return Err(ApiError::BadRequest("delta must not be 0".into()));
|
||
|
|
}
|
||
|
|
let exists: Option<(Uuid,)> =
|
||
|
|
sqlx::query_as("SELECT id FROM users WHERE id = $1").bind(id).fetch_optional(&state.db).await?;
|
||
|
|
exists.ok_or(ApiError::NotFound("user"))?;
|
||
|
|
sqlx::query(
|
||
|
|
"INSERT INTO credit_ledger (id, user_id, delta, reason, note, created_by) VALUES ($1, $2, $3, 'admin_adjust', $4, $5)",
|
||
|
|
)
|
||
|
|
.bind(Uuid::now_v7())
|
||
|
|
.bind(id)
|
||
|
|
.bind(req.delta)
|
||
|
|
.bind(req.note.map(|n| n.chars().take(500).collect::<String>()))
|
||
|
|
.bind(admin.id())
|
||
|
|
.execute(&state.db)
|
||
|
|
.await?;
|
||
|
|
let (balance,): (i64,) =
|
||
|
|
sqlx::query_as("SELECT COALESCE(SUM(delta), 0)::bigint FROM credit_ledger WHERE user_id = $1")
|
||
|
|
.bind(id)
|
||
|
|
.fetch_one(&state.db)
|
||
|
|
.await?;
|
||
|
|
Ok((StatusCode::CREATED, Json(json!({ "user_id": id, "balance": balance }))))
|
||
|
|
}
|