Skip to main content

sunday_slate/fantasy_teams/
extract.rs

1use crate::auth::CurrentUser;
2use crate::fantasy_teams::FantasyTeam;
3use crate::fantasy_teams::store as fantasy_teams;
4use crate::invites::store as invites;
5use crate::leagues::store as leagues_store;
6use crate::leagues::{League, MaybeLeague};
7use crate::{AppError, AppState, Db, User};
8use axum::extract::{FromRequestParts, Path};
9use axum::http::request::Parts;
10use axum::response::{IntoResponse, Redirect, Response};
11use tower_sessions::Session;
12
13pub struct NoTeam;
14
15impl FromRequestParts<AppState> for NoTeam {
16    type Rejection = Response;
17    async fn from_request_parts(parts: &mut Parts, state: &AppState) -> Result<Self, Response> {
18        let MaybeTeam(team) = MaybeTeam::from_request_parts(parts, state).await?;
19        match team {
20            Some(_) => Err(AppError::Unauthorized.into_response()),
21            None => Ok(NoTeam),
22        }
23    }
24}
25
26/// The signed-in user's team in the resolved league, read from the request
27/// extension cached by the `leagues::resolve` middleware. `None` when signed
28/// out, teamless in the league, or when the middleware did not run.
29pub struct MaybeTeam(pub Option<FantasyTeam>);
30
31impl FromRequestParts<AppState> for MaybeTeam {
32    type Rejection = Response;
33    async fn from_request_parts(parts: &mut Parts, _state: &AppState) -> Result<Self, Response> {
34        Ok(MaybeTeam(
35            parts
36                .extensions
37                .get::<Option<FantasyTeam>>()
38                .cloned()
39                .flatten(),
40        ))
41    }
42}
43
44/// The current user's team in the current league. A guard for team-scoped
45/// pages: absence rejects with `Unauthorized`. Onboarding a user who has no
46/// team is the bootstrap middleware's job — it redirects to `/teams/new`
47/// before a team-scoped handler runs.
48pub struct CurrentTeam(pub FantasyTeam);
49
50impl FromRequestParts<AppState> for CurrentTeam {
51    type Rejection = Response;
52    async fn from_request_parts(parts: &mut Parts, state: &AppState) -> Result<Self, Response> {
53        let MaybeTeam(team) = MaybeTeam::from_request_parts(parts, state).await?;
54        Ok(CurrentTeam(
55            team.ok_or_else(|| AppError::Unauthorized.into_response())?,
56        ))
57    }
58}
59
60/// The current user's team, when it is the team named by the route's `{id}`.
61/// Any other id — including a viewer with no team in the resolved league,
62/// such as the site admin visiting another league — is `NotFound`.
63pub struct OwnedTeam(pub FantasyTeam);
64
65impl FromRequestParts<AppState> for OwnedTeam {
66    type Rejection = Response;
67    async fn from_request_parts(parts: &mut Parts, state: &AppState) -> Result<Self, Response> {
68        let Path(id) = Path::<i64>::from_request_parts(parts, state)
69            .await
70            .map_err(IntoResponse::into_response)?;
71        let MaybeTeam(team) = MaybeTeam::from_request_parts(parts, state).await?;
72        match team {
73            Some(team) if team.id == id => Ok(OwnedTeam(team)),
74            _ => Err(AppError::NotFound.into_response()),
75        }
76    }
77}
78
79/// Resolve where `user` may create a team, and the invite consumed by doing
80/// so (`None` invite for the site admin's commissioner bootstrap). The single
81/// source of truth for team-creation authorization, shared by the bootstrap
82/// guard and the `TeamCreator` extractor.
83///
84/// The admin creates in the league they just created (`pending_league`,
85/// session-carried), else the ambient (resolved) league. A non-admin creates
86/// in the league of the invite they accepted (`pending_invite`,
87/// session-carried, ignored when no longer active for their email), else
88/// their most recent active invite. Someone who already has a team in the
89/// target league gets `Ok(None)`, as does a non-admin with no active invite.
90pub async fn team_creation_target(
91    db: &Db,
92    ambient: Option<League>,
93    pending_invite: Option<i64>,
94    pending_league: Option<i64>,
95    user: &User,
96) -> Result<Option<(League, Option<i64>)>, AppError> {
97    let (league, invite_id) = if user.is_admin {
98        let league = match pending_league {
99            Some(id) => leagues_store::by_id(db.reader(), id).await?.or(ambient),
100            None => ambient,
101        };
102        let Some(league) = league else {
103            return Ok(None);
104        };
105        (league, None)
106    } else {
107        let invite = match pending_invite {
108            Some(id) => invites::find_active_by_id(db.reader(), id, &user.email).await?,
109            None => None,
110        };
111        let invite = match invite {
112            Some(invite) => Some(invite),
113            None => invites::find_active_any(db.reader(), &user.email).await?,
114        };
115        let Some(invite) = invite else {
116            return Ok(None);
117        };
118        let league = leagues_store::by_id(db.reader(), invite.league_id)
119            .await?
120            .expect("invites.league_id is a foreign key into leagues");
121        (league, Some(invite.id))
122    };
123
124    if fantasy_teams::team_for_user(db.reader(), league.id, user.id)
125        .await?
126        .is_some()
127    {
128        return Ok(None);
129    }
130    Ok(Some((league, invite_id)))
131}
132
133pub struct TeamCreator {
134    pub user: User,
135    pub league: League,
136    pub invite_id: Option<i64>,
137}
138
139impl FromRequestParts<AppState> for TeamCreator {
140    type Rejection = Response;
141    async fn from_request_parts(parts: &mut Parts, state: &AppState) -> Result<Self, Response> {
142        let MaybeLeague(ambient) = MaybeLeague::from_request_parts(parts, state).await?;
143        let CurrentUser(user) = CurrentUser::from_request_parts(parts, state).await?;
144        let (pending_invite, pending_league) = match Session::from_request_parts(parts, state).await
145        {
146            Ok(session) => (
147                crate::invites::pending(&session).await,
148                crate::leagues::pending_creation(&session).await,
149            ),
150            Err(_) => (None, None),
151        };
152
153        match team_creation_target(&state.db, ambient, pending_invite, pending_league, &user)
154            .await
155            .map_err(|e| e.into_response())?
156        {
157            Some((league, invite_id)) => Ok(TeamCreator {
158                user,
159                league,
160                invite_id,
161            }),
162            // Already has a team (or no invite) — nothing to create; send home.
163            None => Err(Redirect::to("/").into_response()),
164        }
165    }
166}
167
168#[cfg(test)]
169mod tests {
170    use super::*;
171    use crate::leagues::store as leagues;
172    use crate::users::store as users;
173    use sqlx::SqlitePool;
174
175    async fn seed_league(pool: &SqlitePool) -> League {
176        leagues::create(pool, "Sunday Funday")
177            .await
178            .expect("create league")
179    }
180
181    async fn make_user(pool: &SqlitePool, email: &str, is_admin: bool) -> User {
182        users::create(pool, email, "hash", is_admin)
183            .await
184            .expect("create user")
185    }
186
187    async fn give_team(pool: &SqlitePool, league_id: i64, user: &User) {
188        fantasy_teams::create(pool, league_id, user.id, "Champs", "Owner", user.is_admin)
189            .await
190            .expect("create team");
191    }
192
193    async fn give_invite(pool: &SqlitePool, league_id: i64, email: &str) -> i64 {
194        invites::upsert(pool, league_id, email, "token-hash")
195            .await
196            .expect("create invite")
197    }
198
199    #[sqlx::test]
200    async fn admin_without_team_and_ambient_league_creates_without_invite(pool: SqlitePool) {
201        let league = seed_league(&pool).await;
202        let admin = make_user(&pool, "admin@test.local", true).await;
203        let db = Db::test(pool.clone());
204        let target = team_creation_target(&db, Some(league.clone()), None, None, &admin)
205            .await
206            .expect("target")
207            .expect("some");
208        assert_eq!(target.0.id, league.id);
209        assert_eq!(target.1, None, "admin bootstrap consumes no invite");
210    }
211
212    #[sqlx::test]
213    async fn admin_with_team_in_ambient_league_is_none(pool: SqlitePool) {
214        let league = seed_league(&pool).await;
215        let admin = make_user(&pool, "admin@test.local", true).await;
216        give_team(&pool, league.id, &admin).await;
217        let db = Db::test(pool.clone());
218        let target = team_creation_target(&db, Some(league), None, None, &admin)
219            .await
220            .expect("target");
221        assert!(
222            target.is_none(),
223            "an admin who already has a team cannot create another"
224        );
225    }
226
227    #[sqlx::test]
228    async fn invitee_with_active_invite_targets_the_invite_league(pool: SqlitePool) {
229        let league = seed_league(&pool).await;
230        let invitee = make_user(&pool, "invitee@test.local", false).await;
231        let invite_id = give_invite(&pool, league.id, "invitee@test.local").await;
232        let db = Db::test(pool.clone());
233        // The invite carries the league, so the ambient league doesn't matter.
234        let target = team_creation_target(&db, None, None, None, &invitee)
235            .await
236            .expect("target")
237            .expect("some");
238        assert_eq!(target.0.id, league.id);
239        assert_eq!(target.1, Some(invite_id));
240    }
241
242    #[sqlx::test]
243    async fn non_admin_without_invite_is_none(pool: SqlitePool) {
244        let league = seed_league(&pool).await;
245        let stranger = make_user(&pool, "stranger@test.local", false).await;
246        let db = Db::test(pool.clone());
247        let target = team_creation_target(&db, Some(league), None, None, &stranger)
248            .await
249            .expect("target");
250        assert!(target.is_none());
251    }
252
253    #[sqlx::test]
254    async fn non_admin_with_team_in_invite_league_is_none(pool: SqlitePool) {
255        let league = seed_league(&pool).await;
256        let member = make_user(&pool, "member@test.local", false).await;
257        give_team(&pool, league.id, &member).await;
258        give_invite(&pool, league.id, "member@test.local").await;
259        let db = Db::test(pool.clone());
260        let target = team_creation_target(&db, Some(league), None, None, &member)
261            .await
262            .expect("target");
263        assert!(target.is_none());
264    }
265
266    #[sqlx::test]
267    async fn invitee_target_is_the_invite_league_not_the_ambient(pool: SqlitePool) {
268        let league_a = leagues::create(&pool, "League A").await.expect("league");
269        let league_b = leagues::create(&pool, "League B").await.expect("league");
270        let invitee = make_user(&pool, "invitee@test.local", false).await;
271        let invite_id = give_invite(&pool, league_b.id, "invitee@test.local").await;
272        let db = Db::test(pool.clone());
273        let target = team_creation_target(&db, Some(league_a), None, None, &invitee)
274            .await
275            .expect("target")
276            .expect("some");
277        assert_eq!(target.0.id, league_b.id);
278        assert_eq!(target.1, Some(invite_id));
279    }
280
281    #[sqlx::test]
282    async fn pending_invite_overrides_the_newest_invite(pool: SqlitePool) {
283        let league_a = leagues::create(&pool, "League A").await.expect("league");
284        let league_b = leagues::create(&pool, "League B").await.expect("league");
285        let invitee = make_user(&pool, "invitee@test.local", false).await;
286        let older = give_invite(&pool, league_a.id, "invitee@test.local").await;
287        sqlx::query(
288            "UPDATE invites SET created_at = datetime('now','subsec','-1 hour') WHERE id = ?1",
289        )
290        .bind(older)
291        .execute(&pool)
292        .await
293        .expect("age invite");
294        give_invite(&pool, league_b.id, "invitee@test.local").await;
295        let db = Db::test(pool.clone());
296        let target = team_creation_target(&db, None, Some(older), None, &invitee)
297            .await
298            .expect("target")
299            .expect("some");
300        assert_eq!(target.0.id, league_a.id);
301        assert_eq!(target.1, Some(older));
302    }
303
304    #[sqlx::test]
305    async fn stale_pending_invite_falls_back_to_the_newest(pool: SqlitePool) {
306        let league_a = leagues::create(&pool, "League A").await.expect("league");
307        let league_b = leagues::create(&pool, "League B").await.expect("league");
308        let invitee = make_user(&pool, "invitee@test.local", false).await;
309        let older = give_invite(&pool, league_a.id, "invitee@test.local").await;
310        sqlx::query(
311            "UPDATE invites SET created_at = datetime('now','subsec','-1 hour') WHERE id = ?1",
312        )
313        .bind(older)
314        .execute(&pool)
315        .await
316        .expect("age invite");
317        let newer = give_invite(&pool, league_b.id, "invitee@test.local").await;
318        invites::mark_accepted(&pool, older).await.expect("accept");
319        let db = Db::test(pool.clone());
320        let target = team_creation_target(&db, None, Some(older), None, &invitee)
321            .await
322            .expect("target")
323            .expect("some");
324        assert_eq!(target.0.id, league_b.id);
325        assert_eq!(target.1, Some(newer));
326    }
327}