Files
sorsfonalak/services/backend/src/routes/admin.rs
T

243 lines
9.3 KiB
Rust
Raw Normal View History

//! Administration (admin role only): users, roles, credits. A package or
//! units given to a user are announced to them in an e-mail (`gift`).
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 sqlx::PgConnection;
use time::OffsetDateTime;
use uuid::Uuid;
use super::{Body, IdPath, St};
use crate::auth::AdminUser;
use crate::credits::{self, Unit};
use crate::error::{ApiError, ApiResult};
use crate::packages::{self, Source};
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,
i64,
i64,
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 AND c.kind <> 'celebrity'), \
(SELECT COALESCE(SUM(delta), 0)::bigint FROM credit_ledger l WHERE l.user_id = u.id AND l.unit = 'natal'), \
(SELECT COALESCE(SUM(delta), 0)::bigint FROM credit_ledger l WHERE l.user_id = u.id AND l.unit = 'synastry'), \
(SELECT COALESCE(SUM(delta), 0)::bigint FROM credit_ledger l WHERE l.user_id = u.id AND l.unit = 'forecast'), \
(SELECT COALESCE(SUM(delta), 0)::bigint FROM credit_ledger l WHERE l.user_id = u.id AND l.unit = 'question'), \
(SELECT COALESCE(SUM(delta), 0)::bigint FROM credit_ledger l WHERE l.user_id = u.id AND l.unit = 'tarot') \
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 total: i64 = sqlx::query_scalar(
"SELECT count(*) FROM users u WHERE $1::text IS NULL OR u.email ILIKE $1 OR u.display_name ILIKE $1",
)
.bind(&pattern)
.fetch_one(&state.db)
.await?;
let users: Vec<Value> = rows
.into_iter()
.map(|(id, email, name, roles, verified, created, last_login, charts, natal, synastry, forecast, question, tarot)| {
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,
"analyses_left": {
"natal": natal, "synastry": synastry, "forecast": forecast, "question": question, "tarot": tarot,
},
})
})
.collect();
Ok(Json(json!({ "users": users, "total": total, "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 {
unit: Unit,
/// 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"))?;
let mut tx = state.db.begin().await?;
sqlx::query(
"INSERT INTO credit_ledger (id, user_id, unit, delta, reason, note, created_by) \
VALUES ($1, $2, $3, $4, 'admin_adjust', $5, $6)",
)
.bind(Uuid::now_v7())
.bind(id)
.bind(req.unit.as_str())
.bind(req.delta)
.bind(req.note.map(|n| n.chars().take(500).collect::<String>()))
.bind(admin.id())
.execute(&mut *tx)
.await?;
// Only a gift is announced, not taking units away.
if req.delta > 0 {
queue_gift(&mut tx, &state.config.public_base_url, id, Gift::Units(req.unit, req.delta)).await?;
}
let balance = credits::balance(&mut tx, id).await?;
tx.commit().await?;
Ok((StatusCode::CREATED, Json(json!({ "user_id": id, "analyses_left": balance.view() }))))
}
#[derive(Deserialize)]
#[serde(deny_unknown_fields)]
pub struct GrantPackage {
package: String,
note: Option<String>,
}
/// Gives a user a package from the catalog (a gift: no payment, price 0).
pub async fn grant_package(
State(state): St,
AdminUser(admin): AdminUser,
WithRejection(Path(id), _): IdPath,
WithRejection(Json(req), _): Body<GrantPackage>,
) -> ApiResult<(StatusCode, Json<Value>)> {
let package = packages::find(&req.package).ok_or(ApiError::NotFound("package"))?;
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"))?;
let note = req.note.map(|n| n.trim().chars().take(500).collect::<String>()).filter(|n| !n.is_empty());
let mut tx = state.db.begin().await?;
let order = packages::grant(&mut tx, id, package, Source::Admin, Some(admin.id()), note.as_deref()).await?;
queue_gift(&mut tx, &state.config.public_base_url, id, Gift::Package(package)).await?;
let balance = credits::balance(&mut tx, id).await?;
tx.commit().await?;
tracing::info!(admin = %admin.id(), user = %id, package = package.id, "package granted");
Ok((
StatusCode::CREATED,
Json(json!({
"order_id": order, "user_id": id, "package": package.id,
"analyses_left": balance.view(),
})),
))
}
/// What an administrator gave a user.
enum Gift {
Package(&'static packages::Package),
Units(Unit, i32),
}
/// Queues the "you got a gift" e-mail for the user.
async fn queue_gift(conn: &mut PgConnection, base: &str, user_id: Uuid, gift: Gift) -> Result<(), ApiError> {
let (email, locale, name): (String, String, Option<String>) =
sqlx::query_as("SELECT email, locale, display_name FROM users WHERE id = $1")
.bind(user_id)
.fetch_one(&mut *conn)
.await?;
let hu = locale.eq_ignore_ascii_case("hu");
let (what, contents) = match gift {
Gift::Package(p) if hu => (format!("a(z) „{}” csomagot", p.name), Some(p.contents_text())),
Gift::Package(p) => (format!("the “{}” package", p.name), Some(p.contents_text())),
Gift::Units(unit, n) => (format!("{n} {}", unit_name(unit, hu)), None),
};
let payload = json!({
"url": format!("{base}/csomagok"), "display_name": name, "gift": what, "contents": contents,
});
super::auth::queue_email_to(conn, Some(user_id), &email, "gift", &locale, payload).await
}
/// A unit's name after a number, as the object of the sentence ("2 kérdést").
fn unit_name(unit: Unit, hu: bool) -> &'static str {
match (unit, hu) {
(Unit::Natal, true) => "részletes képletelemzést",
(Unit::Synastry, true) => "kapcsolati elemzést",
(Unit::Forecast, true) => "éves előrejelzést",
(Unit::Person, true) => "személyhelyet",
(Unit::Question, true) => "kérdést",
(Unit::Tarot, true) => "kártyajóslást",
(Unit::Natal, false) => "detailed chart analysis(es)",
(Unit::Synastry, false) => "relationship analysis(es)",
(Unit::Forecast, false) => "yearly forecast(s)",
(Unit::Person, false) => "person slot(s)",
(Unit::Question, false) => "question(s)",
(Unit::Tarot, false) => "tarot reading(s)",
}
}