use axum::body::Bytes;
use axum::extract::State;
use axum::http::HeaderMap;
use axum::{Extension, Json};
use serde_json::{json, Value};
use super::{config_err, parse_config_value, CurrentUser};
use crate::error::ApiError;
use crate::AppState;
const MAIL_KEY: &str = "mail";
const USERS_CONFIG_KEY: &str = "usersConfig";
async fn get_section(state: &AppState, key: &str) -> Result<Json<Value>, ApiError> {
let value = state.app.config_service().get(key).await?;
Ok(Json(value.unwrap_or(Value::Null)))
}
async fn set_section(
state: &AppState,
user: &Option<sbol_db_core::User>,
key: &str,
headers: &HeaderMap,
body: &[u8],
) -> Result<Json<Value>, ApiError> {
let Some(caller) = user.as_ref() else {
return Err(ApiError::Unauthorized(
"authentication is required".to_owned(),
));
};
let is_admin = caller.is_admin;
let value = parse_config_value(headers, body)?;
state
.app
.config_service()
.set(is_admin, key, &value)
.await
.map_err(config_err)?;
Ok(Json(json!({ "status": "ok" })))
}
pub async fn get_mail(State(state): State<AppState>) -> Result<Json<Value>, ApiError> {
get_section(&state, MAIL_KEY).await
}
pub async fn set_mail(
State(state): State<AppState>,
Extension(CurrentUser(user)): Extension<CurrentUser>,
headers: HeaderMap,
body: Bytes,
) -> Result<Json<Value>, ApiError> {
set_section(&state, &user, MAIL_KEY, &headers, &body).await
}
pub async fn get_theme(State(state): State<AppState>) -> Result<Json<Value>, ApiError> {
Ok(Json(crate::instance::legacy_theme(&state).await?))
}
pub async fn set_theme(
State(state): State<AppState>,
Extension(CurrentUser(user)): Extension<CurrentUser>,
headers: HeaderMap,
body: Bytes,
) -> Result<Json<Value>, ApiError> {
set_section(&state, &user, crate::instance::THEME_KEY, &headers, &body).await
}
pub async fn get_users_config(State(state): State<AppState>) -> Result<Json<Value>, ApiError> {
get_section(&state, USERS_CONFIG_KEY).await
}
pub async fn set_users_config(
State(state): State<AppState>,
Extension(CurrentUser(user)): Extension<CurrentUser>,
headers: HeaderMap,
body: Bytes,
) -> Result<Json<Value>, ApiError> {
set_section(&state, &user, USERS_CONFIG_KEY, &headers, &body).await
}
pub async fn log() -> Json<Value> {
Json(json!({ "entries": [] }))
}