Admin: paged user list with a dialog; creators manage famous people
- The user list pages (25 per page, with the total from the backend); roles, packages and single units are set in a dialog instead of in the row. - Creators may add, edit and publish famous people and rewrite their portraits (own regenerate route); they delete only their own. The rest of the admin stays closed to them; the header links them to their page. - No free-horoscope offer on the star sign and famous people lists. - .table-wrap is a containing block, so .sr-only text inside it no longer widens the page on phones. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> Claude-Session: https://claude.ai/code/session_012vLHzh5qUhFtmJhzkcTbXL
This commit is contained in:
@@ -85,6 +85,28 @@ impl FromRequestParts<Arc<AppState>> for AdminUser {
|
||||
}
|
||||
}
|
||||
|
||||
/// Guard: may manage the famous people (the admin or the creator role).
|
||||
pub struct CelebrityEditor(pub AuthUser);
|
||||
|
||||
impl CelebrityEditor {
|
||||
pub fn is_admin(&self) -> bool {
|
||||
self.0.user.has_role(Role::Admin)
|
||||
}
|
||||
}
|
||||
|
||||
impl FromRequestParts<Arc<AppState>> for CelebrityEditor {
|
||||
type Rejection = ApiError;
|
||||
|
||||
async fn from_request_parts(parts: &mut Parts, state: &Arc<AppState>) -> Result<Self, Self::Rejection> {
|
||||
let user = AuthUser::from_request_parts(parts, state).await?;
|
||||
if user.user.has_role(Role::Creator) {
|
||||
return Ok(CelebrityEditor(user));
|
||||
}
|
||||
user.require(Role::Admin)?;
|
||||
Ok(CelebrityEditor(user))
|
||||
}
|
||||
}
|
||||
|
||||
pub fn user_agent(parts_headers: &axum::http::HeaderMap) -> Option<String> {
|
||||
parts_headers.get(USER_AGENT).and_then(|v| v.to_str().ok()).map(|s| s.chars().take(300).collect())
|
||||
}
|
||||
|
||||
@@ -60,11 +60,17 @@ pub async fn list_users(
|
||||
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(&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)| {
|
||||
@@ -78,7 +84,7 @@ pub async fn list_users(
|
||||
})
|
||||
})
|
||||
.collect();
|
||||
Ok(Json(json!({ "users": users, "limit": limit, "offset": offset })))
|
||||
Ok(Json(json!({ "users": users, "total": total, "limit": limit, "offset": offset })))
|
||||
}
|
||||
|
||||
#[derive(Deserialize)]
|
||||
|
||||
@@ -410,6 +410,11 @@ pub async fn regenerate(
|
||||
_admin: crate::auth::AdminUser,
|
||||
WithRejection(Path(id), _): IdPath,
|
||||
) -> ApiResult<Json<Value>> {
|
||||
Ok(Json(regenerate_in_place(&state, id).await?))
|
||||
}
|
||||
|
||||
/// See [`regenerate`]; also used for the famous people's analyses.
|
||||
pub(super) async fn regenerate_in_place(state: &AppState, id: Uuid) -> Result<Value, ApiError> {
|
||||
let row = find_analysis(&state.db, id).await?.ok_or(ApiError::NotFound("analysis"))?;
|
||||
if row.status == "pending" || row.status == "running" {
|
||||
return Err(ApiError::conflict("analysis_in_progress", "Ez az elemzés éppen készül."));
|
||||
@@ -446,5 +451,5 @@ pub async fn regenerate(
|
||||
sqlx::query("SELECT pg_notify('analyses', '')").execute(&mut *tx).await?;
|
||||
tx.commit().await?;
|
||||
tracing::info!(%id, kind, "analysis regenerated");
|
||||
Ok(Json(row.view()))
|
||||
Ok(row.view())
|
||||
}
|
||||
|
||||
@@ -23,7 +23,7 @@ use super::analyses::{ANALYSIS_COLUMNS, AnalysisRow, Target, queue};
|
||||
use super::charts::{CHART_COLUMNS, ChartRow, calculate, find_chart};
|
||||
use super::{Body, IdPath, St, double_option};
|
||||
use crate::AppState;
|
||||
use crate::auth::{AdminUser, AuthUser};
|
||||
use crate::auth::{AuthUser, CelebrityEditor};
|
||||
use crate::error::{ApiError, ApiResult};
|
||||
use crate::views::{chart_highlights, public_chart, rfc3339, rfc3339_opt};
|
||||
|
||||
@@ -43,12 +43,13 @@ struct CelebrityRow {
|
||||
focus_x: f32,
|
||||
focus_y: f32,
|
||||
published_at: Option<OffsetDateTime>,
|
||||
created_by: Option<Uuid>,
|
||||
created_at: OffsetDateTime,
|
||||
updated_at: OffsetDateTime,
|
||||
}
|
||||
|
||||
const COLUMNS: &str = "id, chart_id, name, subtitle, slug, photo_key, photo_width, photo_height, focus_x, focus_y, \
|
||||
published_at, created_at, updated_at";
|
||||
published_at, created_by, created_at, updated_at";
|
||||
|
||||
impl CelebrityRow {
|
||||
fn photo(&self) -> Value {
|
||||
@@ -161,6 +162,7 @@ async fn admin_view(db: &PgPool, row: &CelebrityRow) -> Result<Value, ApiError>
|
||||
let chart = find_chart(db, row.chart_id).await?.ok_or(ApiError::NotFound("celebrity"))?;
|
||||
let analysis = latest_analysis(db, row.chart_id).await?;
|
||||
let mut view = row.base();
|
||||
view["created_by"] = json!(row.created_by);
|
||||
view["birth_data"] = chart.birth_data.clone();
|
||||
view["birth"] = public_chart(&chart.result, true)["birth"].clone();
|
||||
view["highlights"] = chart_highlights(&chart.result);
|
||||
@@ -174,7 +176,7 @@ async fn admin_view(db: &PgPool, row: &CelebrityRow) -> Result<Value, ApiError>
|
||||
type ListRow =
|
||||
(Uuid, Uuid, String, Option<String>, String, Option<OffsetDateTime>, Option<String>, Value, Option<String>);
|
||||
|
||||
pub async fn list(State(state): St, _admin: AdminUser) -> ApiResult<Json<Value>> {
|
||||
pub async fn list(State(state): St, _editor: CelebrityEditor) -> ApiResult<Json<Value>> {
|
||||
let rows: Vec<ListRow> = sqlx::query_as(
|
||||
"SELECT c.id, c.chart_id, c.name, c.subtitle, c.slug, c.published_at, c.photo_key, ch.result, \
|
||||
(SELECT a.status FROM analyses a WHERE a.chart_id = c.chart_id AND a.kind = 'celebrity' \
|
||||
@@ -210,7 +212,7 @@ pub struct CreateCelebrity {
|
||||
/// Adds a famous person: calculates the chart and queues the analysis.
|
||||
pub async fn create(
|
||||
State(state): St,
|
||||
AdminUser(admin): AdminUser,
|
||||
CelebrityEditor(admin): CelebrityEditor,
|
||||
WithRejection(Json(req), _): Body<CreateCelebrity>,
|
||||
) -> ApiResult<(StatusCode, Json<Value>)> {
|
||||
let name = clean_name(&req.name)?;
|
||||
@@ -249,7 +251,7 @@ pub async fn create(
|
||||
|
||||
pub async fn get_one(
|
||||
State(state): St,
|
||||
_admin: AdminUser,
|
||||
_editor: CelebrityEditor,
|
||||
WithRejection(Path(id), _): IdPath,
|
||||
) -> ApiResult<Json<Value>> {
|
||||
let row = find(&state.db, id).await?;
|
||||
@@ -273,7 +275,7 @@ pub struct UpdateCelebrity {
|
||||
|
||||
pub async fn update(
|
||||
State(state): St,
|
||||
AdminUser(admin): AdminUser,
|
||||
CelebrityEditor(admin): CelebrityEditor,
|
||||
WithRejection(Path(id), _): IdPath,
|
||||
WithRejection(Json(req), _): Body<UpdateCelebrity>,
|
||||
) -> ApiResult<Json<Value>> {
|
||||
@@ -353,10 +355,10 @@ pub async fn update(
|
||||
}
|
||||
|
||||
/// Queues the analysis again when there is none or the last one failed
|
||||
/// (rewriting a finished one: `POST /v1/admin/analyses/{id}/regenerate`).
|
||||
/// (rewriting a finished one: [`regenerate_analysis`]).
|
||||
pub async fn request_analysis(
|
||||
State(state): St,
|
||||
AdminUser(admin): AdminUser,
|
||||
CelebrityEditor(admin): CelebrityEditor,
|
||||
WithRejection(Path(id), _): IdPath,
|
||||
) -> ApiResult<Json<Value>> {
|
||||
let row = find(&state.db, id).await?;
|
||||
@@ -365,6 +367,17 @@ pub async fn request_analysis(
|
||||
Ok(Json(admin_view(&state.db, &row).await?))
|
||||
}
|
||||
|
||||
/// Writes the finished (or failed) analysis again with the current prompt.
|
||||
pub async fn regenerate_analysis(
|
||||
State(state): St,
|
||||
_editor: CelebrityEditor,
|
||||
WithRejection(Path(id), _): IdPath,
|
||||
) -> ApiResult<Json<Value>> {
|
||||
let row = find(&state.db, id).await?;
|
||||
let analysis = latest_analysis(&state.db, row.chart_id).await?.ok_or(ApiError::NotFound("analysis"))?;
|
||||
Ok(Json(super::analyses::regenerate_in_place(&state, analysis.id).await?))
|
||||
}
|
||||
|
||||
fn storage(state: &AppState) -> Result<&crate::storage::Storage, ApiError> {
|
||||
state
|
||||
.storage
|
||||
@@ -385,7 +398,7 @@ async fn delete_photo(state: &AppState, key: &str) {
|
||||
/// WebP); it replaces the previous one. The face point is reset.
|
||||
pub async fn upload_photo(
|
||||
State(state): St,
|
||||
AdminUser(admin): AdminUser,
|
||||
CelebrityEditor(admin): CelebrityEditor,
|
||||
WithRejection(Path(id), _): IdPath,
|
||||
body: Bytes,
|
||||
) -> ApiResult<Json<Value>> {
|
||||
@@ -422,7 +435,7 @@ pub async fn upload_photo(
|
||||
|
||||
pub async fn remove_photo(
|
||||
State(state): St,
|
||||
_admin: AdminUser,
|
||||
_editor: CelebrityEditor,
|
||||
WithRejection(Path(id), _): IdPath,
|
||||
) -> ApiResult<Json<Value>> {
|
||||
let row = find(&state.db, id).await?;
|
||||
@@ -442,10 +455,14 @@ pub async fn remove_photo(
|
||||
/// Deletes the famous person with their chart, analysis and photo.
|
||||
pub async fn remove(
|
||||
State(state): St,
|
||||
AdminUser(admin): AdminUser,
|
||||
editor: CelebrityEditor,
|
||||
WithRejection(Path(id), _): IdPath,
|
||||
) -> ApiResult<StatusCode> {
|
||||
let row = find(&state.db, id).await?;
|
||||
if !editor.is_admin() && row.created_by != Some(editor.0.id()) {
|
||||
return Err(ApiError::Forbidden("only an admin may delete someone else's famous person".into()));
|
||||
}
|
||||
let admin = editor.0;
|
||||
sqlx::query("DELETE FROM charts WHERE id = $1").bind(row.chart_id).execute(&state.db).await?;
|
||||
if let Some(key) = &row.photo_key {
|
||||
delete_photo(&state, key).await;
|
||||
@@ -474,7 +491,7 @@ pub async fn public_list(State(state): St) -> ApiResult<Json<Value>> {
|
||||
Ok(Json(json!({ "celebrities": items })))
|
||||
}
|
||||
|
||||
/// Public: one famous person's page (a draft only for admins).
|
||||
/// Public: one famous person's page (a draft only for admins and creators).
|
||||
pub async fn public_view(
|
||||
State(state): St,
|
||||
auth: Result<AuthUser, ApiError>,
|
||||
@@ -485,7 +502,7 @@ pub async fn public_view(
|
||||
.fetch_optional(&state.db)
|
||||
.await?
|
||||
.ok_or(ApiError::NotFound("celebrity"))?;
|
||||
let admin = auth.is_ok_and(|a| a.user.has_role(db::Role::Admin));
|
||||
let admin = auth.is_ok_and(|a| a.user.has_role(db::Role::Admin) || a.user.has_role(db::Role::Creator));
|
||||
if row.published_at.is_none() && !admin {
|
||||
return Err(ApiError::NotFound("celebrity"));
|
||||
}
|
||||
|
||||
@@ -160,6 +160,7 @@ pub fn router(state: Arc<AppState>) -> Router {
|
||||
get(celebrities::get_one).patch(celebrities::update).delete(celebrities::remove),
|
||||
)
|
||||
.route("/v1/admin/celebrities/{id}/analysis", post(celebrities::request_analysis))
|
||||
.route("/v1/admin/celebrities/{id}/analysis/regenerate", post(celebrities::regenerate_analysis))
|
||||
.route(
|
||||
"/v1/admin/celebrities/{id}/photo",
|
||||
axum::routing::put(celebrities::upload_photo)
|
||||
|
||||
@@ -3099,3 +3099,65 @@ async fn admins_publish_famous_people_with_a_photo(pool: PgPool) {
|
||||
assert_eq!(left["celebrities"].as_array().unwrap().len(), 1);
|
||||
assert_eq!(left["celebrities"][0]["id"].as_str(), Some(second.as_str()));
|
||||
}
|
||||
|
||||
#[sqlx::test(migrator = "db::MIGRATOR")]
|
||||
async fn creators_add_famous_people_but_nothing_else_of_the_admin(pool: PgPool) {
|
||||
let app = TestApp::new(pool.clone()).await;
|
||||
let admin = app.register("admin@example.com", "Admin").await;
|
||||
let writer = app.register("szerzo@example.com", "Szerző").await;
|
||||
sqlx::query("UPDATE users SET roles = '{user,creator}' WHERE email = 'szerzo@example.com'")
|
||||
.execute(&pool)
|
||||
.await
|
||||
.unwrap();
|
||||
let birth = json!({"date": "1926-06-01", "time": "09:30", "country": "HU", "place": "Szeged"});
|
||||
|
||||
// the famous people: add, edit, see the draft, rewrite the analysis, delete their own
|
||||
let r = app.post("/v1/admin/celebrities", Some(&writer), json!({"name": "Teszt Elek", "birth": birth})).await;
|
||||
assert_eq!(r.status, StatusCode::CREATED, "{}", r.body);
|
||||
let id = r.body["id"].as_str().unwrap().to_string();
|
||||
let analysis_id = r.body["analysis"]["id"].as_str().unwrap().to_string();
|
||||
assert!(r.body["created_by"].is_string());
|
||||
let r = app.call("PATCH", &format!("/v1/admin/celebrities/{id}"), Some(&writer), Some(json!({"subtitle": "író"}))).await;
|
||||
assert_eq!(r.status, StatusCode::OK, "{}", r.body);
|
||||
assert_eq!(app.get("/v1/public/celebrities/teszt-elek", Some(&writer)).await.status, StatusCode::OK);
|
||||
let regenerate = format!("/v1/admin/celebrities/{id}/analysis/regenerate");
|
||||
let r = app.post(®enerate, Some(&writer), json!({})).await;
|
||||
assert_eq!(r.status, StatusCode::CONFLICT, "still pending: {}", r.body);
|
||||
sqlx::query("UPDATE analyses SET status = 'done', content = '{}', completed_at = now() WHERE id = $1::uuid")
|
||||
.bind(&analysis_id)
|
||||
.execute(&pool)
|
||||
.await
|
||||
.unwrap();
|
||||
let r = app.post(®enerate, Some(&writer), json!({})).await;
|
||||
assert_eq!((r.status, r.body["status"].as_str()), (StatusCode::OK, Some("pending")), "{}", r.body);
|
||||
assert_eq!(r.body["id"].as_str(), Some(analysis_id.as_str()));
|
||||
|
||||
// someone else's famous person: edited, but only an admin deletes it
|
||||
let r = app.post("/v1/admin/celebrities", Some(&admin), json!({"name": "Admin Ádám", "birth": birth})).await;
|
||||
let others = r.body["id"].as_str().unwrap().to_string();
|
||||
let r = app.call("DELETE", &format!("/v1/admin/celebrities/{others}"), Some(&writer), None).await;
|
||||
assert_eq!(r.status, StatusCode::FORBIDDEN);
|
||||
let r = app.call("DELETE", &format!("/v1/admin/celebrities/{id}"), Some(&writer), None).await;
|
||||
assert_eq!(r.status, StatusCode::NO_CONTENT);
|
||||
|
||||
// the rest of the admin stays closed
|
||||
for uri in ["/v1/admin/users", "/v1/admin/prompts", "/v1/admin/errors"] {
|
||||
assert_eq!(app.get(uri, Some(&writer)).await.status, StatusCode::FORBIDDEN, "{uri}");
|
||||
}
|
||||
let r = app.post(&format!("/v1/admin/analyses/{analysis_id}/regenerate"), Some(&writer), json!({})).await;
|
||||
assert_eq!(r.status, StatusCode::FORBIDDEN);
|
||||
}
|
||||
|
||||
#[sqlx::test(migrator = "db::MIGRATOR")]
|
||||
async fn the_user_list_pages_with_a_total(pool: PgPool) {
|
||||
let app = TestApp::new(pool.clone()).await;
|
||||
let admin = app.register("admin@example.com", "Admin").await;
|
||||
for i in 0..4 {
|
||||
app.register(&format!("lap{i}@example.com"), "Lapozó").await;
|
||||
}
|
||||
let r = app.get("/v1/admin/users?limit=2&offset=2", Some(&admin)).await;
|
||||
assert_eq!(r.status, StatusCode::OK, "{}", r.body);
|
||||
assert_eq!((r.body["total"].as_i64(), r.body["users"].as_array().unwrap().len()), (Some(5), 2));
|
||||
let r = app.get("/v1/admin/users?q=lap&limit=3&offset=3", Some(&admin)).await;
|
||||
assert_eq!((r.body["total"].as_i64(), r.body["users"].as_array().unwrap().len()), (Some(4), 1));
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user