feat: edit/delete authorities, blocked when referenced (#30)

This commit is contained in:
2026-06-05 19:46:27 +02:00
parent 83a7202861
commit 47240dafcc
5 changed files with 497 additions and 11 deletions
+121 -4
View File
@@ -3,18 +3,19 @@
use auth::{Authorized, EditCatalogue, ViewInternal};
use axum::{
Json, Router,
extract::{Query, State},
extract::{Path, Query, State},
http::StatusCode,
response::{IntoResponse, Response},
routing::get,
};
use domain::{AuditActor, AuthorityKind, LocalizedLabel, NewAuthority};
use domain::{AuditActor, AuthorityId, AuthorityKind, LocalizedLabel, NewAuthority};
use serde::{Deserialize, Serialize};
use utoipa::ToSchema;
use crate::{
AppState,
admin_objects::LabelView,
admin_vocab::{CreatedId, LabelInput},
admin_vocab::{CreatedId, InUseView, LabelInput},
};
#[derive(Serialize, ToSchema)]
@@ -129,9 +130,125 @@ pub(crate) async fn create_authority(
Ok((StatusCode::CREATED, Json(CreatedId { id: id.to_string() })))
}
#[derive(Deserialize, ToSchema)]
pub(crate) struct UpdateAuthorityRequest {
pub external_uri: Option<String>,
pub labels: Vec<LabelInput>,
}
#[utoipa::path(
patch, path = "/api/admin/authorities/{id}",
request_body = UpdateAuthorityRequest,
params(("id" = String, Path, description = "Authority id (UUID)")),
responses(
(status = 204),
(status = 401),
(status = 403),
(status = 404)
)
)]
pub(crate) async fn update_authority(
auth: Authorized<EditCatalogue>,
State(state): State<AppState>,
Path(id): Path<String>,
Json(req): Json<UpdateAuthorityRequest>,
) -> Result<StatusCode, StatusCode> {
let id = id
.parse::<AuthorityId>()
.map_err(|_| StatusCode::NOT_FOUND)?;
let labels: Vec<LocalizedLabel> = req
.labels
.into_iter()
.map(|l| LocalizedLabel {
lang: l.lang,
label: l.label,
})
.collect();
let mut tx = state
.db
.pool()
.begin()
.await
.map_err(|_| StatusCode::INTERNAL_SERVER_ERROR)?;
let existed = db::authority::update_authority(
&mut tx,
AuditActor::User(auth.user.id.to_uuid()),
id,
req.external_uri.as_deref(),
&labels,
)
.await
.map_err(|_| StatusCode::INTERNAL_SERVER_ERROR)?;
if existed {
tx.commit()
.await
.map_err(|_| StatusCode::INTERNAL_SERVER_ERROR)?;
Ok(StatusCode::NO_CONTENT)
} else {
let _ = tx.rollback().await;
Err(StatusCode::NOT_FOUND)
}
}
#[utoipa::path(
delete, path = "/api/admin/authorities/{id}",
params(("id" = String, Path, description = "Authority id (UUID)")),
responses(
(status = 204),
(status = 401),
(status = 403),
(status = 404),
(status = 409, body = InUseView, description = "Referenced by catalogue objects")
)
)]
pub(crate) async fn delete_authority(
auth: Authorized<EditCatalogue>,
State(state): State<AppState>,
Path(id): Path<String>,
) -> Response {
let Ok(id) = id.parse::<AuthorityId>() else {
return StatusCode::NOT_FOUND.into_response();
};
let Ok(mut tx) = state.db.pool().begin().await else {
return StatusCode::INTERNAL_SERVER_ERROR.into_response();
};
match db::authority::delete_authority(&mut tx, AuditActor::User(auth.user.id.to_uuid()), id)
.await
{
Ok(db::DeleteOutcome::Deleted) => match tx.commit().await {
Ok(()) => StatusCode::NO_CONTENT.into_response(),
Err(_) => StatusCode::INTERNAL_SERVER_ERROR.into_response(),
},
Ok(db::DeleteOutcome::InUse { count }) => {
let _ = tx.rollback().await;
(StatusCode::CONFLICT, Json(InUseView { count })).into_response()
}
Ok(db::DeleteOutcome::NotFound) => {
let _ = tx.rollback().await;
StatusCode::NOT_FOUND.into_response()
}
Err(_) => StatusCode::INTERNAL_SERVER_ERROR.into_response(),
}
}
pub(crate) fn routes() -> Router<AppState> {
Router::new().route(
Router::new()
.route(
"/api/admin/authorities",
get(list_authorities).post(create_authority),
)
.route(
"/api/admin/authorities/{id}",
axum::routing::patch(update_authority).delete(delete_authority),
)
}
+4 -1
View File
@@ -37,7 +37,9 @@ use crate::{
admin_vocab::delete_vocabulary,
admin_search::search_objects,
admin_authorities::list_authorities,
admin_authorities::create_authority
admin_authorities::create_authority,
admin_authorities::update_authority,
admin_authorities::delete_authority
),
components(schemas(
config::ConfigView,
@@ -71,6 +73,7 @@ use crate::{
admin_search::SearchResultsView,
admin_authorities::AuthorityView,
admin_authorities::NewAuthorityRequest,
admin_authorities::UpdateAuthorityRequest,
domain::Visibility,
domain::AuthorityKind,
domain::DataType
+127
View File
@@ -587,3 +587,130 @@ async fn delete_vocabulary_with_terms_is_409(pool: PgPool) {
serde_json::from_slice(&blocked.into_body().collect().await.unwrap().to_bytes()).unwrap();
assert_eq!(body["count"], 1);
}
#[sqlx::test(migrations = "../db/migrations")]
async fn delete_authority_referenced_is_409(pool: PgPool) {
migrate_sessions(&db::Db::from_pool(pool.clone()))
.await
.unwrap();
seed_user(&pool, "ed@example.com", "pw-editor-123", Role::Editor).await;
let app = build_app(state(pool));
let cookie = login(&app, "ed@example.com", "pw-editor-123").await;
// create an authority
let a = send(
&app,
&cookie,
"POST",
"/api/admin/authorities",
Some(r#"{"kind":"person","external_uri":null,"labels":[{"lang":"sv","label":"Astrid"}]}"#),
)
.await;
assert_eq!(a.status(), StatusCode::CREATED);
let aid: serde_json::Value =
serde_json::from_slice(&a.into_body().collect().await.unwrap().to_bytes()).unwrap();
let aid = aid["id"].as_str().unwrap().to_owned();
// create an authority-typed field definition
send(
&app,
&cookie,
"POST",
"/api/admin/field-definitions",
Some(
r#"{"key":"maker","data_type":"authority","vocabulary_id":null,"authority_kind":"person","required":false,"group":null,"labels":[{"lang":"sv","label":"Tillverkare"}]}"#,
),
)
.await;
// create an object
let obj = send(
&app,
&cookie,
"POST",
"/api/admin/objects",
Some(
r#"{"object_number":"T-1","object_name":"test object","number_of_objects":1,"visibility":"draft"}"#,
),
)
.await;
assert_eq!(obj.status(), StatusCode::CREATED);
let obj_json: serde_json::Value =
serde_json::from_slice(&obj.into_body().collect().await.unwrap().to_bytes()).unwrap();
let obj_id = obj_json["id"].as_str().unwrap().to_owned();
// set the object's maker field to the authority id
let fields_body = format!(r#"{{"maker":"{aid}"}}"#);
let set = send(
&app,
&cookie,
"PUT",
&format!("/api/admin/objects/{obj_id}/fields"),
Some(&fields_body),
)
.await;
assert_eq!(set.status(), StatusCode::NO_CONTENT);
// delete the authority — must be blocked
let blocked = send(
&app,
&cookie,
"DELETE",
&format!("/api/admin/authorities/{aid}"),
None,
)
.await;
assert_eq!(blocked.status(), StatusCode::CONFLICT);
let body: serde_json::Value =
serde_json::from_slice(&blocked.into_body().collect().await.unwrap().to_bytes()).unwrap();
assert_eq!(body["count"], 1);
}
#[sqlx::test(migrations = "../db/migrations")]
async fn edit_and_delete_authority(pool: PgPool) {
migrate_sessions(&db::Db::from_pool(pool.clone()))
.await
.unwrap();
seed_user(&pool, "ed@example.com", "pw-editor-123", Role::Editor).await;
let app = build_app(state(pool));
let cookie = login(&app, "ed@example.com", "pw-editor-123").await;
let a = send(
&app,
&cookie,
"POST",
"/api/admin/authorities",
Some(r#"{"kind":"person","external_uri":null,"labels":[{"lang":"sv","label":"Anon"}]}"#),
)
.await;
let aid: serde_json::Value =
serde_json::from_slice(&a.into_body().collect().await.unwrap().to_bytes()).unwrap();
let aid = aid["id"].as_str().unwrap().to_owned();
let patched = send(
&app,
&cookie,
"PATCH",
&format!("/api/admin/authorities/{aid}"),
Some(r#"{"external_uri":"https://viaf.org/1","labels":[{"lang":"sv","label":"Astrid"}]}"#),
)
.await;
assert_eq!(patched.status(), StatusCode::NO_CONTENT);
let deleted = send(
&app,
&cookie,
"DELETE",
&format!("/api/admin/authorities/{aid}"),
None,
)
.await;
assert_eq!(deleted.status(), StatusCode::NO_CONTENT);
}
+109
View File
@@ -124,6 +124,115 @@ where
}
}
/// Update an authority's `external_uri` and labels (full replace), recording an
/// `updated` audit entry. Returns `false` if no such authority. `kind` is immutable.
pub async fn update_authority(
conn: &mut sqlx::PgConnection,
actor: AuditActor,
id: AuthorityId,
external_uri: Option<&str>,
labels: &[LocalizedLabel],
) -> Result<bool, sqlx::Error> {
let updated = sqlx::query("UPDATE authority SET external_uri = $2 WHERE id = $1")
.bind(id.to_uuid())
.bind(external_uri)
.execute(&mut *conn)
.await?
.rows_affected();
if updated == 0 {
return Ok(false);
}
sqlx::query("DELETE FROM authority_label WHERE authority_id = $1")
.bind(id.to_uuid())
.execute(&mut *conn)
.await?;
for label in labels {
sqlx::query("INSERT INTO authority_label (authority_id, lang, label) VALUES ($1, $2, $3)")
.bind(id.to_uuid())
.bind(&label.lang)
.bind(&label.label)
.execute(&mut *conn)
.await?;
}
audit::record(
&mut *conn,
&NewAuditEvent {
actor,
action: AuditAction::Updated,
entity_type: AUTHORITY_ENTITY_TYPE.to_owned(),
entity_id: id.to_uuid(),
changes: Vec::new(),
},
)
.await?;
Ok(true)
}
/// Count catalogue objects referencing `id` through an `authority`-typed field.
pub async fn count_objects_referencing_authority<'e, E>(
executor: E,
id: AuthorityId,
) -> Result<i64, sqlx::Error>
where
E: sqlx::PgExecutor<'e>,
{
sqlx::query_scalar(
"SELECT count(*) FROM object o WHERE EXISTS ( \
SELECT 1 FROM field_definition fd \
WHERE fd.data_type = 'authority' AND o.fields ->> fd.key = $1 )",
)
.bind(id.to_string())
.fetch_one(executor)
.await
}
/// Delete an authority (labels cascade) unless catalogue objects reference it,
/// recording a `deleted` audit entry.
pub async fn delete_authority(
conn: &mut sqlx::PgConnection,
actor: AuditActor,
id: AuthorityId,
) -> Result<crate::DeleteOutcome, sqlx::Error> {
let exists = sqlx::query_scalar::<_, i32>("SELECT 1 FROM authority WHERE id = $1")
.bind(id.to_uuid())
.fetch_optional(&mut *conn)
.await?;
if exists.is_none() {
return Ok(crate::DeleteOutcome::NotFound);
}
let count = count_objects_referencing_authority(&mut *conn, id).await?;
if count > 0 {
return Ok(crate::DeleteOutcome::InUse { count });
}
sqlx::query("DELETE FROM authority WHERE id = $1")
.bind(id.to_uuid())
.execute(&mut *conn)
.await?;
audit::record(
&mut *conn,
&NewAuditEvent {
actor,
action: AuditAction::Deleted,
entity_type: AUTHORITY_ENTITY_TYPE.to_owned(),
entity_id: id.to_uuid(),
changes: Vec::new(),
},
)
.await?;
Ok(crate::DeleteOutcome::Deleted)
}
fn map_authority(row: sqlx::postgres::PgRow) -> Result<Authority, sqlx::Error> {
let kind_str: String = row.try_get("kind")?;
let kind = AuthorityKind::from_db(&kind_str)
+132 -2
View File
@@ -1,7 +1,23 @@
use db::{Db, authority};
use domain::{AuditActor, AuthorityKind, LocalizedLabel, NewAuthority};
use db::{Db, authority, catalog, fields};
use domain::{
AuditActor, AuthorityKind, LocalizedLabel, NewAuthority, NewFieldDefinition, Visibility,
};
use sqlx::PgPool;
fn sample_object_input() -> domain::ObjectInput {
domain::ObjectInput {
object_number: "X.1".into(),
object_name: "Test".into(),
number_of_objects: 1,
brief_description: None,
current_location: None,
current_owner: None,
recorder: None,
recording_date: None,
visibility: Visibility::Draft,
}
}
fn new_person(name_sv: &str, name_en: &str) -> NewAuthority {
NewAuthority {
kind: AuthorityKind::Person,
@@ -131,3 +147,117 @@ async fn authority_with_no_labels_round_trips_empty(pool: PgPool) {
assert_eq!(got.kind, AuthorityKind::Organisation);
assert!(got.labels.is_empty());
}
#[sqlx::test(migrations = "../db/migrations")]
async fn update_authority_changes_labels(pool: PgPool) {
let db = Db::from_pool(pool);
let mut tx = db.pool().begin().await.unwrap();
let id = authority::create_authority(
&mut tx,
AuditActor::System,
&NewAuthority {
kind: AuthorityKind::Person,
external_uri: None,
labels: vec![LocalizedLabel {
lang: "sv".into(),
label: "Anon".into(),
}],
},
)
.await
.unwrap();
let existed = authority::update_authority(
&mut tx,
AuditActor::System,
id,
Some("https://viaf.org/1"),
&[LocalizedLabel {
lang: "sv".into(),
label: "Astrid".into(),
}],
)
.await
.unwrap();
assert!(existed);
tx.commit().await.unwrap();
let a = authority::authority_by_id(db.pool(), id)
.await
.unwrap()
.unwrap();
assert_eq!(a.external_uri.as_deref(), Some("https://viaf.org/1"));
assert_eq!(a.labels[0].label, "Astrid");
}
#[sqlx::test(migrations = "../db/migrations")]
async fn delete_authority_blocks_when_referenced(pool: PgPool) {
use db::DeleteOutcome;
let db = Db::from_pool(pool);
let mut tx = db.pool().begin().await.unwrap();
let id = authority::create_authority(
&mut tx,
AuditActor::System,
&NewAuthority {
kind: AuthorityKind::Person,
external_uri: None,
labels: vec![LocalizedLabel {
lang: "sv".into(),
label: "Astrid".into(),
}],
},
)
.await
.unwrap();
fields::create_field_definition(
&mut tx,
&NewFieldDefinition {
key: "maker".into(),
field_type: domain::FieldType::Authority {
kind: Some(AuthorityKind::Person),
},
required: false,
group_key: None,
labels: vec![LocalizedLabel {
lang: "sv".into(),
label: "Tillverkare".into(),
}],
},
)
.await
.unwrap();
let obj = catalog::create_object(&mut tx, AuditActor::System, &sample_object_input())
.await
.unwrap();
let mut map = serde_json::Map::new();
map.insert("maker".into(), serde_json::Value::String(id.to_string()));
catalog::set_object_fields(&mut tx, AuditActor::System, obj, &map)
.await
.unwrap();
assert_eq!(
authority::delete_authority(&mut tx, AuditActor::System, id)
.await
.unwrap(),
DeleteOutcome::InUse { count: 1 }
);
catalog::set_object_fields(&mut tx, AuditActor::System, obj, &serde_json::Map::new())
.await
.unwrap();
assert_eq!(
authority::delete_authority(&mut tx, AuditActor::System, id)
.await
.unwrap(),
DeleteOutcome::Deleted
);
assert_eq!(
authority::delete_authority(&mut tx, AuditActor::System, id)
.await
.unwrap(),
DeleteOutcome::NotFound
);
}