feat: registration settings

This commit is contained in:
Per Stark
2025-01-27 22:16:17 +01:00
parent f329987818
commit c6bc0c44f3
6 changed files with 87 additions and 7 deletions

View File

@@ -1,6 +1,7 @@
use axum::{
extract::State,
response::{IntoResponse, Redirect},
Form,
};
use axum_session_auth::AuthSession;
use axum_session_surreal::SessionSurrealPool;
@@ -13,6 +14,8 @@ use crate::{
storage::types::{analytics::Analytics, system_settings::SystemSettings, user::User},
};
use super::render_block;
page_data!(AdminPanelData, "auth/admin_panel.html", {
user: User,
settings: SystemSettings,
@@ -24,7 +27,7 @@ pub async fn show_admin_panel(
State(state): State<AppState>,
auth: AuthSession<User, String, SessionSurrealPool<Any>, Surreal<Any>>,
) -> Result<impl IntoResponse, HtmlError> {
// Early return if the user is not authenticated
// Early return if the user is not authenticated and admin
let user = match auth.current_user {
Some(user) if user.admin => user,
_ => return Ok(Redirect::to("/").into_response()),
@@ -55,3 +58,61 @@ pub async fn show_admin_panel(
Ok(output.into_response())
}
fn checkbox_to_bool<'de, D>(deserializer: D) -> Result<bool, D::Error>
where
D: serde::Deserializer<'de>,
{
match String::deserialize(deserializer) {
Ok(string) => Ok(string == "on"),
Err(_) => Ok(false),
}
}
#[derive(Deserialize)]
pub struct RegistrationToggleInput {
#[serde(default)]
#[serde(deserialize_with = "checkbox_to_bool")]
registration_open: bool,
}
#[derive(Serialize)]
pub struct RegistrationToggleData {
settings: SystemSettings,
}
pub async fn toggle_registration_status(
State(state): State<AppState>,
auth: AuthSession<User, String, SessionSurrealPool<Any>, Surreal<Any>>,
Form(input): Form<RegistrationToggleInput>,
) -> Result<impl IntoResponse, HtmlError> {
// Early return if the user is not authenticated and admin
let _user = match auth.current_user {
Some(user) if user.admin => user,
_ => return Ok(Redirect::to("/").into_response()),
};
let current_settings = SystemSettings::get_current(&state.surreal_db_client)
.await
.map_err(|e| HtmlError::new(e, state.templates.clone()))?;
let new_settings = SystemSettings {
registrations_enabled: input.registration_open,
..current_settings.clone()
};
SystemSettings::update(&state.surreal_db_client, new_settings.clone())
.await
.map_err(|e| HtmlError::new(e, state.templates.clone()))?;
let output = render_block(
AdminPanelData::template_name(),
"registration_status_input",
RegistrationToggleData {
settings: new_settings,
},
state.templates.clone(),
)?;
Ok(output.into_response())
}