Skip to main content

sunday_slate/admin/
mod.rs

1//! Admin tools, gated as a subtree.
2//!
3//! Every route under `/admin` sits behind [`require_admin`], so the individual
4//! handlers do not repeat the check. New admin features nest their own router
5//! here rather than wiring their own auth.
6
7pub mod avatars;
8
9use askama::Template;
10use axum::Router;
11use axum::extract::Request;
12use axum::middleware::Next;
13use axum::response::{Html, IntoResponse, Response};
14use axum::routing::get;
15
16use crate::auth::AdminUser;
17use crate::chrome::Chrome;
18use crate::{AppError, AppState};
19
20#[derive(Template)]
21#[template(path = "admin/index.html")]
22struct IndexTemplate {
23    chrome: Chrome,
24}
25
26async fn index() -> Result<impl IntoResponse, AppError> {
27    Ok(Html(
28        IndexTemplate {
29            chrome: Chrome::unlit("Admin Tools"),
30        }
31        .render()?,
32    ))
33}
34
35/// Whether `path` is in the admin subtree — the landing page or anything
36/// nested under it. The one place that rule is written down.
37pub(crate) fn is_admin_path(path: &str) -> bool {
38    ["/admin", "/nfl-data-admin"]
39        .iter()
40        .any(|root| path == *root || path.starts_with(&format!("{root}/")))
41}
42
43/// Reject anyone but a signed-in admin before an admin handler runs. Extracting
44/// [`AdminUser`] here returns its rejection — 403 for a non-admin, the login
45/// redirect for an anonymous request — so the subtree needs no per-handler gate.
46async fn require_admin(_: AdminUser, req: Request, next: Next) -> Response {
47    next.run(req).await
48}
49
50/// The admin subtree: the landing page plus every feature router nested under
51/// it, all behind [`require_admin`].
52pub fn router(state: AppState) -> Router<AppState> {
53    Router::new()
54        .route("/admin", get(index))
55        .nest("/admin/avatars", avatars::router())
56        .route_layer(axum::middleware::from_fn_with_state(state, require_admin))
57}
58
59/// Mount NFL-data administration behind the host's existing global-admin gate.
60pub(crate) fn nfl_data_router(state: AppState) -> Router<AppState> {
61    Router::new()
62        .nest(
63            "/nfl-data-admin",
64            nfl_data::admin_router::<AppState>(
65                std::sync::Arc::clone(&state.nfl),
66                nfl_data::AdminConfig {
67                    season: nfl_data::Season(state.config.season),
68                    now_override: state.config.now_override,
69                },
70            ),
71        )
72        .route_layer(axum::middleware::from_fn_with_state(state, require_admin))
73}
74
75#[cfg(test)]
76mod tests {
77    use crate::tests::TestApp;
78    use crate::tests::factories::{self, UserOptions};
79    use http::StatusCode;
80
81    #[tokio::test]
82    async fn admin_sees_the_tools_landing_page() {
83        let app = TestApp::new().await;
84        let admin = factories::user(
85            &app.pool,
86            UserOptions {
87                is_admin: true,
88                ..Default::default()
89            },
90        )
91        .await;
92        app.login_as(&admin.user).await;
93        let page = app.get("/admin").await;
94        page.assert_status_ok();
95        page.assert_text_contains("Admin Tools");
96        page.assert_text_contains("/admin/avatars");
97    }
98
99    #[tokio::test]
100    async fn non_admin_cannot_open_admin() {
101        let app = TestApp::new().await;
102        let user = factories::user(
103            &app.pool,
104            UserOptions {
105                is_admin: false,
106                ..Default::default()
107            },
108        )
109        .await;
110        app.login_as(&user.user).await;
111        app.get("/admin").await.assert_status(StatusCode::FORBIDDEN);
112    }
113
114    #[tokio::test]
115    async fn anonymous_is_redirected_from_admin() {
116        let app = TestApp::new().await;
117        let resp = app.get("/admin").await;
118        assert!(
119            resp.status_code().is_redirection(),
120            "expected a redirect, got {}",
121            resp.status_code()
122        );
123        assert!(
124            resp.header("location")
125                .to_str()
126                .unwrap()
127                .starts_with("/login")
128        );
129    }
130}