| 1 | |
| 2 | |
| 3 | |
| 4 | |
| 5 | |
| 6 | |
| 7 | |
| 8 | |
| 9 | |
| 10 | |
| 11 | use model::Invite; |
| 12 | use sqlx::any::AnyRow; |
| 13 | use sqlx::{AssertSqlSafe, Row}; |
| 14 | |
| 15 | use crate::{Store, StoreError, new_id, now_ms}; |
| 16 | |
| 17 | |
| 18 | const INVITE_COLUMNS: &str = "id, user_id, token_hash, purpose, expires_at, used_at, created_at"; |
| 19 | |
| 20 | |
| 21 | |
| 22 | #[derive(Debug, Clone)] |
| 23 | pub struct NewInvite { |
| 24 | |
| 25 | pub user_id: String, |
| 26 | |
| 27 | pub token_hash: String, |
| 28 | |
| 29 | pub purpose: String, |
| 30 | |
| 31 | pub expires_at: i64, |
| 32 | } |
| 33 | |
| 34 | impl Store { |
| 35 | |
| 36 | |
| 37 | |
| 38 | |
| 39 | |
| 40 | pub async fn create_invite(&self, new: NewInvite) -> Result<Invite, StoreError> { |
| 41 | let invite = Invite { |
| 42 | id: new_id(), |
| 43 | user_id: new.user_id, |
| 44 | token_hash: new.token_hash, |
| 45 | purpose: new.purpose, |
| 46 | expires_at: new.expires_at, |
| 47 | used_at: None, |
| 48 | created_at: now_ms(), |
| 49 | }; |
| 50 | let sql = "INSERT INTO invites (id, user_id, token_hash, purpose, expires_at, used_at, created_at) \ |
| 51 | VALUES ($1, $2, $3, $4, $5, $6, $7)"; |
| 52 | sqlx::query(sql) |
| 53 | .bind(invite.id.clone()) |
| 54 | .bind(invite.user_id.clone()) |
| 55 | .bind(invite.token_hash.clone()) |
| 56 | .bind(invite.purpose.clone()) |
| 57 | .bind(invite.expires_at) |
| 58 | .bind(invite.used_at) |
| 59 | .bind(invite.created_at) |
| 60 | .execute(&self.pool) |
| 61 | .await?; |
| 62 | Ok(invite) |
| 63 | } |
| 64 | |
| 65 | |
| 66 | |
| 67 | |
| 68 | |
| 69 | |
| 70 | |
| 71 | |
| 72 | pub async fn invite_by_token_hash( |
| 73 | &self, |
| 74 | token_hash: &str, |
| 75 | ) -> Result<Option<Invite>, StoreError> { |
| 76 | let sql = format!("SELECT {INVITE_COLUMNS} FROM invites WHERE token_hash = $1"); |
| 77 | let row = sqlx::query(AssertSqlSafe(sql)) |
| 78 | .bind(token_hash) |
| 79 | .fetch_optional(&self.pool) |
| 80 | .await?; |
| 81 | Ok(row.as_ref().map(map_invite).transpose()?) |
| 82 | } |
| 83 | |
| 84 | |
| 85 | |
| 86 | |
| 87 | |
| 88 | |
| 89 | |
| 90 | pub async fn mark_invite_used(&self, invite_id: &str) -> Result<bool, StoreError> { |
| 91 | let updated = |
| 92 | sqlx::query("UPDATE invites SET used_at = $1 WHERE id = $2 AND used_at IS NULL") |
| 93 | .bind(now_ms()) |
| 94 | .bind(invite_id) |
| 95 | .execute(&self.pool) |
| 96 | .await? |
| 97 | .rows_affected(); |
| 98 | Ok(updated > 0) |
| 99 | } |
| 100 | } |
| 101 | |
| 102 | |
| 103 | fn map_invite(row: &AnyRow) -> Result<Invite, sqlx::Error> { |
| 104 | Ok(Invite { |
| 105 | id: row.try_get("id")?, |
| 106 | user_id: row.try_get("user_id")?, |
| 107 | token_hash: row.try_get("token_hash")?, |
| 108 | purpose: row.try_get("purpose")?, |
| 109 | expires_at: row.try_get("expires_at")?, |
| 110 | used_at: row.try_get("used_at")?, |
| 111 | created_at: row.try_get("created_at")?, |
| 112 | }) |
| 113 | } |