use axum::extract::State; use axum::response::{IntoResponse, Redirect}; use axum::Form; use axum::http::StatusCode; use shared::advent::get_global_unlock_day; use sqlx::PgPool; use crate::session::AxumSessionStore; use crate::templates::HtmlTemplate; use crate::templates::admin::AdminTemplate; fn get_admin_allow_list() -> Vec { std::env::var("ADMIN_DIDS") .unwrap_or_default() .split(',') .map(|s| s.trim().to_string()) .filter(|s| !s.is_empty()) .collect() } fn is_admin(did: Option<&String>) -> bool { let did = match did { Some(d) => d, None => return false, }; let allow_list = get_admin_allow_list(); allow_list.contains(did) } pub async fn admin_page_handler( State(pool): State, session: AxumSessionStore, ) -> impl IntoResponse { let did = session.get_did(); if !is_admin(did.as_ref()) { return (StatusCode::FORBIDDEN, "You are not authorized to access this page.").into_response(); } let current_day = get_global_unlock_day(&pool).await.unwrap_or(1); HtmlTemplate(AdminTemplate { title: "Admin - Global Unlock", current_unlock_day: current_day, is_logged_in: session.logged_in(), message: None, }) .into_response() } #[derive(Debug, serde::Deserialize)] pub struct AdminForm { pub action: String, } pub async fn admin_post_handler( State(pool): State, session: AxumSessionStore, Form(form): Form, ) -> impl IntoResponse { let did = session.get_did(); if !is_admin(did.as_ref()) { return (StatusCode::FORBIDDEN, "You are not authorized to access this page.").into_response(); } let current_day = get_global_unlock_day(&pool).await.unwrap_or(1); let new_day: i32 = match form.action.as_str() { "up" => (current_day as i32 + 1).min(25), "down" => (current_day as i32 - 1).max(1), _ => current_day as i32, }; let result = sqlx::query("UPDATE settings SET unlocked_up_to_day = $1") .bind(new_day) .execute(&pool) .await; match result { Ok(_) => Redirect::to("/admin").into_response(), Err(e) => { log::error!("Failed to update global unlock day: {}", e); HtmlTemplate(AdminTemplate { title: "Admin - Global Unlock", current_unlock_day: current_day, is_logged_in: session.logged_in(), message: Some("Failed to update the unlock day.".to_string()), }) .into_response() } } }