97 lines
2.8 KiB
Rust
97 lines
2.8 KiB
Rust
//! Customer directory administration. Customer IDs are the existing tenant IDs.
|
|
use crate::{auth::Principal, jobs::Error};
|
|
use axum::{
|
|
Json,
|
|
extract::{Path, State},
|
|
http::{HeaderMap, StatusCode},
|
|
};
|
|
use serde::Deserialize;
|
|
use serde_json::{Value, json};
|
|
use sqlx::{Postgres, Transaction};
|
|
use uuid::Uuid;
|
|
|
|
pub fn database_error(e: sqlx::Error) -> Error {
|
|
match e.as_database_error().and_then(|e| e.code()).as_deref() {
|
|
Some("23505") => Error(StatusCode::CONFLICT, "CUSTOMER_ALREADY_EXISTS"),
|
|
Some("42501") => Error(StatusCode::FORBIDDEN, "FORBIDDEN"),
|
|
Some("22023") => Error(StatusCode::BAD_REQUEST, "VALIDATION_ERROR"),
|
|
_ => e.into(),
|
|
}
|
|
}
|
|
|
|
pub async fn can_manage(
|
|
p: &Principal,
|
|
tx: &mut Transaction<'_, Postgres>,
|
|
) -> Result<bool, sqlx::Error> {
|
|
if p.testsimulation
|
|
|| p.session_hash.is_none()
|
|
|| p.csrf.is_none()
|
|
|| !p.name.starts_with("local:")
|
|
{
|
|
return Ok(false);
|
|
}
|
|
sqlx::query_scalar("SELECT is_customer_admin($1)")
|
|
.bind(&p.name)
|
|
.fetch_one(&mut **tx)
|
|
.await
|
|
}
|
|
|
|
#[derive(Deserialize)]
|
|
#[serde(deny_unknown_fields)]
|
|
pub struct Input {
|
|
name: String,
|
|
}
|
|
|
|
pub async fn create(
|
|
State(state): State<crate::State>,
|
|
headers: HeaderMap,
|
|
Json(input): Json<Input>,
|
|
) -> Result<Json<Value>, Error> {
|
|
manage(&state, &headers, input, None).await
|
|
}
|
|
pub async fn rename(
|
|
State(state): State<crate::State>,
|
|
Path(id): Path<Uuid>,
|
|
headers: HeaderMap,
|
|
Json(input): Json<Input>,
|
|
) -> Result<Json<Value>, Error> {
|
|
manage(&state, &headers, input, Some(id)).await
|
|
}
|
|
async fn manage(
|
|
state: &crate::State,
|
|
headers: &HeaderMap,
|
|
input: Input,
|
|
existing: Option<Uuid>,
|
|
) -> Result<Json<Value>, Error> {
|
|
let p = state
|
|
.auth
|
|
.principal(state, headers, true)
|
|
.await
|
|
.map_err(|s| Error(s, crate::auth::error_code(s)))?;
|
|
if input.name.is_empty()
|
|
|| input.name.trim() != input.name
|
|
|| input.name.chars().count() > 120
|
|
|| input.name.chars().any(char::is_control)
|
|
{
|
|
return Err(Error(StatusCode::BAD_REQUEST, "VALIDATION_ERROR"));
|
|
}
|
|
if existing.is_some_and(|id| id != p.tenant) {
|
|
return Err(Error(StatusCode::NOT_FOUND, "NOT_FOUND"));
|
|
}
|
|
let mut tx = rmm_persistence::tenant_tx(&state.pool, p.tenant).await?;
|
|
if !can_manage(&p, &mut tx).await? {
|
|
return Err(Error(StatusCode::FORBIDDEN, "CUSTOMER_ADMIN_REQUIRED"));
|
|
}
|
|
let id = existing.unwrap_or_else(Uuid::new_v4);
|
|
sqlx::query("SELECT manage_customer($1,$2,$3,$4)")
|
|
.bind(&p.name)
|
|
.bind(id)
|
|
.bind(&input.name)
|
|
.bind(existing.is_none())
|
|
.execute(&mut *tx)
|
|
.await
|
|
.map_err(database_error)?;
|
|
tx.commit().await?;
|
|
Ok(Json(json!({"tenant_id":id,"name":input.name})))
|
|
}
|