Skip to main content

sunday_slate/auth/
middleware.rs

1//! Install bootstrap guard.
2//!
3//! Redirects a non-bypassed request to the first unmet precondition:
4//! no users → `/setup`; authenticated with no league → `/leagues/new`;
5//! authenticated with no team in the resolved league, when team creation is
6//! theirs to do (`needs_team_creation`) → `/teams/new`.
7
8use crate::auth::MaybeUser;
9use crate::fantasy_teams::{MaybeTeam, store as fantasy_teams, team_creation_target};
10use crate::leagues::{League, MaybeLeague};
11use crate::users::store as users;
12use crate::{AppState, Db, User};
13use axum::extract::Request;
14use axum::extract::State;
15use axum::middleware::Next;
16use axum::response::{IntoResponse, Redirect, Response};
17
18fn is_bypass_path(req: &Request) -> bool {
19    let path = req.uri().path();
20    matches!(
21        path,
22        "/setup"
23            | "/logout"
24            | "/leagues/new"
25            | "/leagues"
26            | "/teams/new"
27            | "/teams"
28            | "/invite"
29            | "/invite/accept"
30            | "/invite/create-user"
31    ) || path.starts_with("/static/")
32        || path.starts_with("/_dev/")
33        || crate::admin::is_admin_path(path)
34}
35
36async fn is_fresh_install(db: &Db) -> bool {
37    users::exists(db.reader())
38        .await
39        .is_ok_and(|users_exist| !users_exist)
40}
41
42/// Redirect to the first unmet bootstrap precondition.
43pub async fn bootstrap(
44    MaybeUser(user): MaybeUser,
45    MaybeLeague(league): MaybeLeague,
46    MaybeTeam(team): MaybeTeam,
47    State(state): State<AppState>,
48    req: Request,
49    next: Next,
50) -> Response {
51    if is_bypass_path(&req) {
52        return next.run(req).await;
53    }
54
55    if user.is_none() {
56        if is_fresh_install(&state.db).await {
57            return Redirect::to("/setup").into_response();
58        }
59        return next.run(req).await;
60    }
61
62    if league.is_none() {
63        return Redirect::to("/leagues/new").into_response();
64    }
65
66    if team.is_none() && needs_team_creation(&state.db, &league.unwrap(), &user.unwrap()).await {
67        return Redirect::to("/teams/new").into_response();
68    }
69
70    next.run(req).await
71}
72
73/// Whether a user with no team in the resolved league must be sent to
74/// `/teams/new`: the admin bootstrapping a league that has no teams yet, or
75/// a user with no team in any league who holds an active invite. Members of
76/// healthy leagues are never bounced by someone else's empty league.
77/// Delegating to `team_creation_target` keeps bounce ⇒ creation-allowed, so
78/// the guard cannot loop with `TeamCreator`'s redirect home.
79async fn needs_team_creation(db: &Db, league: &League, user: &User) -> bool {
80    // The gate: is the missing team this user's to create?
81    let mine = if user.is_admin {
82        !fantasy_teams::has_any(db.reader(), league.id)
83            .await
84            .unwrap_or(true)
85    } else {
86        !fantasy_teams::any_for_user(db.reader(), user.id)
87            .await
88            .unwrap_or(true)
89    };
90    // No pending invite or league here: the guard only cares whether creation
91    // is possible, and any active invite answers that.
92    mine && team_creation_target(db, Some(league.clone()), None, None, user)
93        .await
94        .is_ok_and(|target| target.is_some())
95}