1use std::sync::LazyLock;
2
3use sqlx::Sqlite;
4use time::PrimitiveDateTime;
5
6use crate::auth::password;
7use crate::invites::model::{InviteToken, PendingInvite};
8use crate::{AppError, Db};
9
10#[derive(sqlx::FromRow)]
12struct ActiveInviteRow {
13 id: i64,
14 league_id: i64,
15 email: String,
16 token_hash: String,
17 league_name: String,
18}
19
20#[derive(Debug, Clone)]
22pub struct VerifiedInvite {
23 pub invite_id: i64,
24 pub league_id: i64,
25 pub email: String,
26 pub league_name: String,
27}
28
29pub async fn upsert<'e, E>(
32 ex: E,
33 league_id: i64,
34 email: &str,
35 token_hash: &str,
36) -> Result<i64, sqlx::Error>
37where
38 E: sqlx::Executor<'e, Database = Sqlite>,
39{
40 let email = email.to_lowercase();
41 sqlx::query_scalar!(
42 "INSERT INTO invites (league_id, email, token_hash, expires_at) \
43 VALUES (?1, ?2, ?3, datetime('now','subsec','+14 days')) \
44 ON CONFLICT (league_id, email) WHERE accepted_at IS NULL DO UPDATE SET \
45 token_hash = excluded.token_hash, \
46 expires_at = excluded.expires_at, \
47 created_at = datetime('now','subsec') \
48 RETURNING id",
49 league_id,
50 email,
51 token_hash,
52 )
53 .fetch_one(ex)
54 .await
55}
56
57pub async fn reissue<'e, E>(
68 ex: E,
69 id: i64,
70 league_id: i64,
71 token_hash: &str,
72) -> Result<Option<String>, sqlx::Error>
73where
74 E: sqlx::Executor<'e, Database = Sqlite>,
75{
76 sqlx::query_scalar!(
77 r#"UPDATE invites
78 SET token_hash = ?3,
79 expires_at = datetime('now','subsec','+14 days')
80 WHERE id = ?1 AND league_id = ?2 AND accepted_at IS NULL
81 RETURNING email AS "email!: String""#,
82 id,
83 league_id,
84 token_hash,
85 )
86 .fetch_optional(ex)
87 .await
88}
89
90pub async fn mark_accepted<'e, E>(ex: E, id: i64) -> Result<(), sqlx::Error>
92where
93 E: sqlx::Executor<'e, Database = Sqlite>,
94{
95 sqlx::query!(
96 "UPDATE invites SET accepted_at = datetime('now','subsec') WHERE id = ?1",
97 id,
98 )
99 .execute(ex)
100 .await?;
101 Ok(())
102}
103
104pub async fn list_for_league<'e, E>(
106 ex: E,
107 league_id: i64,
108) -> Result<Vec<PendingInvite>, sqlx::Error>
109where
110 E: sqlx::Executor<'e, Database = Sqlite>,
111{
112 sqlx::query_as!(
113 PendingInvite,
114 r#"SELECT id AS "id!: i64",
115 email AS "email!: String",
116 expires_at AS "expires_at!: PrimitiveDateTime",
117 accepted_at AS "accepted_at: PrimitiveDateTime"
118 FROM invites
119 WHERE league_id = ?1
120 ORDER BY (accepted_at IS NOT NULL), created_at DESC"#,
121 league_id,
122 )
123 .fetch_all(ex)
124 .await
125}
126
127pub async fn revoke<'e, E>(ex: E, id: i64, league_id: i64) -> Result<(), sqlx::Error>
129where
130 E: sqlx::Executor<'e, Database = Sqlite>,
131{
132 sqlx::query!(
133 "DELETE FROM invites WHERE id = ?1 AND league_id = ?2 AND accepted_at IS NULL",
134 id,
135 league_id,
136 )
137 .execute(ex)
138 .await?;
139 Ok(())
140}
141
142pub async fn is_member<'e, E>(ex: E, league_id: i64, email: &str) -> Result<bool, sqlx::Error>
144where
145 E: sqlx::Executor<'e, Database = Sqlite>,
146{
147 let email = email.to_lowercase();
148 sqlx::query_scalar!(
149 r#"SELECT EXISTS(
150 SELECT 1 FROM fantasy_teams ft
151 JOIN users u ON u.id = ft.user_id
152 WHERE ft.league_id = ?1 AND u.email = ?2
153 ) AS "exists!: bool""#,
154 league_id,
155 email,
156 )
157 .fetch_one(ex)
158 .await
159}
160
161pub async fn league_id_of<'e, E>(ex: E, invite_id: i64) -> Result<Option<i64>, sqlx::Error>
163where
164 E: sqlx::Executor<'e, Database = Sqlite>,
165{
166 sqlx::query_scalar!(
167 r#"SELECT league_id AS "league_id!: i64" FROM invites WHERE id = ?1"#,
168 invite_id,
169 )
170 .fetch_optional(ex)
171 .await
172}
173
174pub struct ActiveInvite {
176 pub id: i64,
177 pub league_id: i64,
178}
179
180pub async fn find_active_by_id<'e, E>(
183 ex: E,
184 invite_id: i64,
185 email: &str,
186) -> Result<Option<ActiveInvite>, sqlx::Error>
187where
188 E: sqlx::Executor<'e, Database = Sqlite>,
189{
190 let email = email.to_lowercase();
191 sqlx::query_as!(
192 ActiveInvite,
193 r#"SELECT id AS "id!: i64", league_id AS "league_id!: i64"
194 FROM invites
195 WHERE id = ?1 AND email = ?2
196 AND accepted_at IS NULL
197 AND expires_at > datetime('now','subsec')"#,
198 invite_id,
199 email,
200 )
201 .fetch_optional(ex)
202 .await
203}
204
205pub async fn find_active_any<'e, E>(ex: E, email: &str) -> Result<Option<ActiveInvite>, sqlx::Error>
208where
209 E: sqlx::Executor<'e, Database = Sqlite>,
210{
211 let email = email.to_lowercase();
212 sqlx::query_as!(
213 ActiveInvite,
214 r#"SELECT id AS "id!: i64", league_id AS "league_id!: i64"
215 FROM invites
216 WHERE email = ?1
217 AND accepted_at IS NULL
218 AND expires_at > datetime('now','subsec')
219 ORDER BY created_at DESC
220 LIMIT 1"#,
221 email,
222 )
223 .fetch_optional(ex)
224 .await
225}
226
227async fn find_active<'e, E>(ex: E, id: i64) -> Result<Option<ActiveInviteRow>, sqlx::Error>
228where
229 E: sqlx::Executor<'e, Database = Sqlite>,
230{
231 sqlx::query_as!(
232 ActiveInviteRow,
233 r#"SELECT i.id AS "id!: i64",
234 i.league_id AS "league_id!: i64",
235 i.email AS "email!: String",
236 i.token_hash AS "token_hash!: String",
237 l.name AS "league_name!: String"
238 FROM invites i
239 JOIN leagues l ON l.id = i.league_id
240 WHERE i.id = ?1
241 AND i.accepted_at IS NULL
242 AND i.expires_at > datetime('now','subsec')"#,
243 id,
244 )
245 .fetch_optional(ex)
246 .await
247}
248
249static DUMMY_HASH: LazyLock<String> = LazyLock::new(|| password::hash("dummy"));
251
252pub async fn verify(db: &Db, raw: &str) -> Result<Option<VerifiedInvite>, AppError> {
254 let parsed = raw.parse::<InviteToken>().ok();
255 let row = match &parsed {
256 Some(token) => find_active(db.reader(), token.id).await?,
257 None => None,
258 };
259
260 let secret = parsed.as_ref().map(|t| t.secret.as_str()).unwrap_or("");
261 let stored_hash = row
262 .as_ref()
263 .map_or(DUMMY_HASH.as_str(), |r| r.token_hash.as_str());
264 if password::verify(secret, stored_hash)
265 && let Some(row) = row
266 {
267 return Ok(Some(VerifiedInvite {
268 invite_id: row.id,
269 league_id: row.league_id,
270 email: row.email,
271 league_name: row.league_name,
272 }));
273 }
274 Ok(None)
275}
276
277#[cfg(test)]
278mod tests {
279 use super::*;
280 use crate::auth::password;
281 use sqlx::SqlitePool;
282
283 async fn seed_league(pool: &SqlitePool, name: &str) -> i64 {
284 sqlx::query_scalar("INSERT INTO leagues (name) VALUES (?1) RETURNING id")
285 .bind(name)
286 .fetch_one(pool)
287 .await
288 .expect("seed league")
289 }
290
291 async fn seed_user(pool: &SqlitePool, email: &str) -> i64 {
292 sqlx::query_scalar("INSERT INTO users (email, password_hash) VALUES (?1, ?2) RETURNING id")
293 .bind(email)
294 .bind("hash")
295 .fetch_one(pool)
296 .await
297 .expect("seed user")
298 }
299
300 async fn seed_team(pool: &SqlitePool, league_id: i64, user_id: i64) -> i64 {
301 sqlx::query_scalar(
302 "INSERT INTO fantasy_teams (league_id, user_id, name, owner_name, is_commissioner) \
303 VALUES (?1, ?2, ?3, ?4, ?5) RETURNING id",
304 )
305 .bind(league_id)
306 .bind(user_id)
307 .bind("Team")
308 .bind("Owner")
309 .bind(false)
310 .fetch_one(pool)
311 .await
312 .expect("seed team")
313 }
314
315 #[sqlx::test]
316 async fn upsert_replaces_outstanding_invite(pool: SqlitePool) {
317 let league = seed_league(&pool, "L").await;
318 let id1 = upsert(&pool, league, "a@b.com", "h1").await.expect("first");
319 let id2 = upsert(&pool, league, "a@b.com", "h2")
320 .await
321 .expect("second");
322 assert_eq!(id1, id2, "re-invite reuses the outstanding row");
323 let count: i64 = sqlx::query_scalar("SELECT COUNT(*) FROM invites")
324 .fetch_one(&pool)
325 .await
326 .expect("count");
327 assert_eq!(count, 1);
328 }
329
330 #[sqlx::test]
331 async fn upsert_sets_a_fourteen_day_expiry(pool: SqlitePool) {
332 let league = seed_league(&pool, "L").await;
333 let id = upsert(&pool, league, "a@b.com", "h").await.expect("upsert");
334 let days: f64 = sqlx::query_scalar(
335 "SELECT julianday(expires_at) - julianday('now') FROM invites WHERE id = ?1",
336 )
337 .bind(id)
338 .fetch_one(&pool)
339 .await
340 .expect("expiry");
341 assert!(
342 (days - 14.0).abs() < 0.01,
343 "expiry is {days} days out, want 14"
344 );
345 }
346
347 #[sqlx::test]
348 async fn verify_roundtrips_and_rejects_bad_secret(pool: SqlitePool) {
349 let league = seed_league(&pool, "Sunday Funday").await;
350 let secret = "s3cr3t";
351 let hash = password::hash(secret);
352 let id = upsert(&pool, league, "a@b.com", &hash)
353 .await
354 .expect("upsert");
355 let db = Db::test(pool.clone());
356
357 let good = verify(&db, &format!("{id}.{secret}"))
358 .await
359 .expect("verify");
360 let good = good.expect("valid");
361 assert_eq!(good.email, "a@b.com");
362 assert_eq!(good.league_name, "Sunday Funday");
363
364 assert!(
365 verify(&db, &format!("{id}.wrong"))
366 .await
367 .expect("verify")
368 .is_none()
369 );
370 assert!(verify(&db, "not-a-token").await.expect("verify").is_none());
371 }
372
373 #[sqlx::test]
374 async fn reissue_replaces_the_hash_and_restarts_the_expiry(pool: SqlitePool) {
375 let league = seed_league(&pool, "L").await;
376 let id = upsert(&pool, league, "a@b.com", "old-hash")
377 .await
378 .expect("upsert");
379 sqlx::query(
380 "UPDATE invites SET expires_at = datetime('now','subsec','+1 hour') WHERE id = ?1",
381 )
382 .bind(id)
383 .execute(&pool)
384 .await
385 .expect("shorten expiry");
386
387 assert_eq!(
388 reissue(&pool, id, league, "new-hash")
389 .await
390 .expect("reissue")
391 .as_deref(),
392 Some("a@b.com")
393 );
394
395 let (hash, days): (String, f64) = sqlx::query_as(
396 "SELECT token_hash, julianday(expires_at) - julianday('now') FROM invites WHERE id = ?1",
397 )
398 .bind(id)
399 .fetch_one(&pool)
400 .await
401 .expect("row");
402 assert_eq!(hash, "new-hash");
403 assert!(
404 (days - 14.0).abs() < 0.01,
405 "expiry is {days} days out, want 14"
406 );
407 }
408
409 #[sqlx::test]
410 async fn reissue_refuses_an_accepted_invite(pool: SqlitePool) {
411 let league = seed_league(&pool, "L").await;
412 let id = upsert(&pool, league, "a@b.com", "old-hash")
413 .await
414 .expect("upsert");
415 mark_accepted(&pool, id).await.expect("accept");
416
417 assert!(
418 reissue(&pool, id, league, "new-hash")
419 .await
420 .expect("reissue")
421 .is_none()
422 );
423
424 let hash: String = sqlx::query_scalar("SELECT token_hash FROM invites WHERE id = ?1")
425 .bind(id)
426 .fetch_one(&pool)
427 .await
428 .expect("row");
429 assert_eq!(hash, "old-hash", "accepted invite must keep its hash");
430 }
431
432 #[sqlx::test]
433 async fn reissue_refuses_an_invite_from_another_league(pool: SqlitePool) {
434 let mine = seed_league(&pool, "Mine").await;
435 let theirs = seed_league(&pool, "Theirs").await;
436 let id = upsert(&pool, theirs, "a@b.com", "old-hash")
437 .await
438 .expect("upsert");
439
440 assert!(
441 reissue(&pool, id, mine, "new-hash")
442 .await
443 .expect("reissue")
444 .is_none()
445 );
446
447 let hash: String = sqlx::query_scalar("SELECT token_hash FROM invites WHERE id = ?1")
448 .bind(id)
449 .fetch_one(&pool)
450 .await
451 .expect("row");
452 assert_eq!(
453 hash, "old-hash",
454 "cross-league reissue must not touch the row"
455 );
456 }
457
458 #[sqlx::test]
459 async fn revoke_deletes_outstanding_invite_for_league(pool: SqlitePool) {
460 let league = seed_league(&pool, "L").await;
461 let id = upsert(&pool, league, "a@b.com", "h").await.expect("upsert");
462 revoke(&pool, id, league).await.expect("revoke");
463 let count: i64 = sqlx::query_scalar("SELECT COUNT(*) FROM invites")
464 .fetch_one(&pool)
465 .await
466 .expect("count");
467 assert_eq!(count, 0);
468 }
469
470 #[sqlx::test]
471 async fn is_member_true_when_user_has_team_in_league(pool: SqlitePool) {
472 let league = seed_league(&pool, "L").await;
473 let user = seed_user(&pool, "member@example.com").await;
474 seed_team(&pool, league, user).await;
475 assert!(
476 is_member(&pool, league, "member@example.com")
477 .await
478 .expect("is_member")
479 );
480 assert!(
481 !is_member(&pool, league, "other@example.com")
482 .await
483 .expect("is_member other")
484 );
485 }
486
487 #[sqlx::test]
488 async fn list_for_league_returns_invites_newest_first(pool: SqlitePool) {
489 let league = seed_league(&pool, "L").await;
490 let id1: i64 = sqlx::query_scalar(
491 "INSERT INTO invites (league_id, email, token_hash, expires_at, created_at) \
492 VALUES (?1, ?2, ?3, datetime('now','+48 hours'), datetime('now','subsec','-1 hour')) \
493 RETURNING id",
494 )
495 .bind(league)
496 .bind("a@b.com")
497 .bind("h1")
498 .fetch_one(&pool)
499 .await
500 .expect("id1");
501 let id2: i64 = sqlx::query_scalar(
502 "INSERT INTO invites (league_id, email, token_hash, expires_at, created_at) \
503 VALUES (?1, ?2, ?3, datetime('now','+48 hours'), datetime('now','subsec')) \
504 RETURNING id",
505 )
506 .bind(league)
507 .bind("c@d.com")
508 .bind("h2")
509 .fetch_one(&pool)
510 .await
511 .expect("id2");
512 let list = list_for_league(&pool, league).await.expect("list");
513 assert_eq!(list.len(), 2);
514 assert_eq!(list[0].id, id2);
515 assert_eq!(list[1].id, id1);
516 }
517
518 #[sqlx::test]
519 async fn list_for_league_sinks_accepted_invites_below_pending(pool: SqlitePool) {
520 let league = seed_league(&pool, "L").await;
521 let id1: i64 = sqlx::query_scalar(
522 "INSERT INTO invites (league_id, email, token_hash, expires_at, created_at) \
523 VALUES (?1, ?2, ?3, datetime('now','+48 hours'), datetime('now','subsec','-1 hour')) \
524 RETURNING id",
525 )
526 .bind(league)
527 .bind("a@b.com")
528 .bind("h1")
529 .fetch_one(&pool)
530 .await
531 .expect("id1");
532 let id2: i64 = sqlx::query_scalar(
533 "INSERT INTO invites (league_id, email, token_hash, expires_at, created_at) \
534 VALUES (?1, ?2, ?3, datetime('now','+48 hours'), datetime('now','subsec')) \
535 RETURNING id",
536 )
537 .bind(league)
538 .bind("c@d.com")
539 .bind("h2")
540 .fetch_one(&pool)
541 .await
542 .expect("id2");
543
544 mark_accepted(&pool, id2).await.expect("mark_accepted");
547
548 let list = list_for_league(&pool, league).await.expect("list");
549 assert_eq!(list.len(), 2);
550 assert_eq!(list[0].id, id1);
551 assert_eq!(list[1].id, id2);
552 }
553
554 #[sqlx::test]
555 async fn expired_invite_is_not_active_or_verifiable(pool: SqlitePool) {
556 let league = seed_league(&pool, "L").await;
557 let secret = "s3cr3t";
558 let hash = password::hash(secret);
559 let id = upsert(&pool, league, "a@b.com", &hash)
560 .await
561 .expect("upsert");
562
563 sqlx::query("UPDATE invites SET expires_at = datetime('now','-1 second') WHERE id = ?1")
564 .bind(id)
565 .execute(&pool)
566 .await
567 .expect("expire invite");
568
569 assert!(
570 find_active_any(&pool, "a@b.com")
571 .await
572 .expect("find_active_any")
573 .is_none()
574 );
575 let db = Db::test(pool.clone());
576 assert!(
577 verify(&db, &format!("{id}.{secret}"))
578 .await
579 .expect("verify")
580 .is_none()
581 );
582 }
583
584 #[sqlx::test]
585 async fn find_active_any_prefers_the_most_recent_and_skips_accepted(pool: SqlitePool) {
586 let league_a = seed_league(&pool, "A").await;
587 let league_b = seed_league(&pool, "B").await;
588 assert!(
589 find_active_any(&pool, "a@b.com")
590 .await
591 .expect("find")
592 .is_none()
593 );
594 let first = upsert(&pool, league_a, "a@b.com", "h1")
595 .await
596 .expect("invite");
597 sqlx::query(
599 "UPDATE invites SET created_at = datetime('now','subsec','-1 hour') WHERE id = ?1",
600 )
601 .bind(first)
602 .execute(&pool)
603 .await
604 .expect("age first invite");
605 let second = upsert(&pool, league_b, "A@B.com", "h2")
606 .await
607 .expect("invite");
608 let found = find_active_any(&pool, "a@b.com")
609 .await
610 .expect("find")
611 .expect("some");
612 assert_eq!((found.id, found.league_id), (second, league_b));
613 mark_accepted(&pool, second).await.expect("accept");
614 let found = find_active_any(&pool, "a@b.com")
615 .await
616 .expect("find")
617 .expect("some");
618 assert_eq!(found.id, first);
619 }
620}