1use std::net::IpAddr;
9
10use async_trait::async_trait;
11use chrono::{DateTime, Duration, Utc};
12use mas_data_model::{Clock, UlidExt as _, UserEmail, UserRecoverySession, UserRecoveryTicket};
13use mas_storage::user::UserRecoveryRepository;
14use rand::Rng;
15use sqlx::PgConnection;
16use ulid::Ulid;
17use uuid::Uuid;
18
19use crate::{DatabaseError, ExecuteExt};
20
21pub struct PgUserRecoveryRepository<'c> {
23 conn: &'c mut PgConnection,
24}
25
26impl<'c> PgUserRecoveryRepository<'c> {
27 pub fn new(conn: &'c mut PgConnection) -> Self {
30 Self { conn }
31 }
32}
33
34struct UserRecoverySessionRow {
35 user_recovery_session_id: Uuid,
36 email: String,
37 user_agent: String,
38 ip_address: Option<IpAddr>,
39 locale: String,
40 created_at: DateTime<Utc>,
41 consumed_at: Option<DateTime<Utc>>,
42}
43
44impl From<UserRecoverySessionRow> for UserRecoverySession {
45 fn from(row: UserRecoverySessionRow) -> Self {
46 UserRecoverySession {
47 id: row.user_recovery_session_id.into(),
48 email: row.email,
49 user_agent: row.user_agent,
50 ip_address: row.ip_address,
51 locale: row.locale,
52 created_at: row.created_at,
53 consumed_at: row.consumed_at,
54 }
55 }
56}
57
58struct UserRecoveryTicketRow {
59 user_recovery_ticket_id: Uuid,
60 user_recovery_session_id: Uuid,
61 user_email_id: Uuid,
62 ticket: String,
63 created_at: DateTime<Utc>,
64 expires_at: DateTime<Utc>,
65}
66
67impl From<UserRecoveryTicketRow> for UserRecoveryTicket {
68 fn from(row: UserRecoveryTicketRow) -> Self {
69 Self {
70 id: row.user_recovery_ticket_id.into(),
71 user_recovery_session_id: row.user_recovery_session_id.into(),
72 user_email_id: row.user_email_id.into(),
73 ticket: row.ticket,
74 created_at: row.created_at,
75 expires_at: row.expires_at,
76 }
77 }
78}
79
80#[async_trait]
81impl UserRecoveryRepository for PgUserRecoveryRepository<'_> {
82 type Error = DatabaseError;
83
84 #[tracing::instrument(
85 name = "db.user_recovery.lookup_session",
86 skip_all,
87 fields(
88 db.query.text,
89 user_recovery_session.id = %id,
90 ),
91 )]
92 async fn lookup_session(
93 &mut self,
94 id: Ulid,
95 ) -> Result<Option<UserRecoverySession>, Self::Error> {
96 let row = sqlx::query_as!(
97 UserRecoverySessionRow,
98 r#"
99 SELECT
100 user_recovery_session_id
101 , email
102 , user_agent
103 , ip_address as "ip_address: IpAddr"
104 , locale
105 , created_at
106 , consumed_at
107 FROM user_recovery_sessions
108 WHERE user_recovery_session_id = $1
109 "#,
110 Uuid::from(id),
111 )
112 .traced()
113 .fetch_optional(&mut *self.conn)
114 .await?;
115
116 let Some(row) = row else {
117 return Ok(None);
118 };
119
120 Ok(Some(row.into()))
121 }
122
123 #[tracing::instrument(
124 name = "db.user_recovery.add_session",
125 skip_all,
126 fields(
127 db.query.text,
128 user_recovery_session.id,
129 user_recovery_session.email = email,
130 user_recovery_session.user_agent = user_agent,
131 user_recovery_session.ip_address = ip_address.map(|ip| ip.to_string()),
132 )
133 )]
134 async fn add_session(
135 &mut self,
136 rng: &mut (dyn Rng + Send),
137 clock: &dyn Clock,
138 email: String,
139 user_agent: String,
140 ip_address: Option<IpAddr>,
141 locale: String,
142 ) -> Result<UserRecoverySession, Self::Error> {
143 let created_at = clock.now();
144 let id = Ulid::from_datetime_with_rng(created_at, rng);
145 tracing::Span::current().record("user_recovery_session.id", tracing::field::display(id));
146 sqlx::query!(
147 r#"
148 INSERT INTO user_recovery_sessions (
149 user_recovery_session_id
150 , email
151 , user_agent
152 , ip_address
153 , locale
154 , created_at
155 )
156 VALUES ($1, $2, $3, $4, $5, $6)
157 "#,
158 Uuid::from(id),
159 &email,
160 &*user_agent,
161 ip_address as Option<IpAddr>,
162 &locale,
163 created_at,
164 )
165 .traced()
166 .execute(&mut *self.conn)
167 .await?;
168
169 let user_recovery_session = UserRecoverySession {
170 id,
171 email,
172 user_agent,
173 ip_address,
174 locale,
175 created_at,
176 consumed_at: None,
177 };
178
179 Ok(user_recovery_session)
180 }
181
182 #[tracing::instrument(
183 name = "db.user_recovery.find_ticket",
184 skip_all,
185 fields(
186 db.query.text,
187 user_recovery_ticket.id = ticket,
188 ),
189 )]
190 async fn find_ticket(
191 &mut self,
192 ticket: &str,
193 ) -> Result<Option<UserRecoveryTicket>, Self::Error> {
194 let row = sqlx::query_as!(
195 UserRecoveryTicketRow,
196 r#"
197 SELECT
198 user_recovery_ticket_id
199 , user_recovery_session_id
200 , user_email_id
201 , ticket
202 , created_at
203 , expires_at
204 FROM user_recovery_tickets
205 WHERE ticket = $1
206 "#,
207 ticket,
208 )
209 .traced()
210 .fetch_optional(&mut *self.conn)
211 .await?;
212
213 let Some(row) = row else {
214 return Ok(None);
215 };
216
217 Ok(Some(row.into()))
218 }
219
220 #[tracing::instrument(
221 name = "db.user_recovery.add_ticket",
222 skip_all,
223 fields(
224 db.query.text,
225 user_recovery_ticket.id,
226 user_recovery_ticket.id = ticket,
227 %user_recovery_session.id,
228 %user_email.id,
229 )
230 )]
231 async fn add_ticket(
232 &mut self,
233 rng: &mut (dyn Rng + Send),
234 clock: &dyn Clock,
235 user_recovery_session: &UserRecoverySession,
236 user_email: &UserEmail,
237 ticket: String,
238 ) -> Result<UserRecoveryTicket, Self::Error> {
239 let created_at = clock.now();
240 let id = Ulid::from_datetime_with_rng(created_at, rng);
241 tracing::Span::current().record("user_recovery_ticket.id", tracing::field::display(id));
242
243 let expires_at = created_at + Duration::minutes(10);
245
246 sqlx::query!(
247 r#"
248 INSERT INTO user_recovery_tickets (
249 user_recovery_ticket_id
250 , user_recovery_session_id
251 , user_email_id
252 , ticket
253 , created_at
254 , expires_at
255 )
256 VALUES ($1, $2, $3, $4, $5, $6)
257 "#,
258 Uuid::from(id),
259 Uuid::from(user_recovery_session.id),
260 Uuid::from(user_email.id),
261 &ticket,
262 created_at,
263 expires_at,
264 )
265 .traced()
266 .execute(&mut *self.conn)
267 .await?;
268
269 let ticket = UserRecoveryTicket {
270 id,
271 user_recovery_session_id: user_recovery_session.id,
272 user_email_id: user_email.id,
273 ticket,
274 created_at,
275 expires_at,
276 };
277
278 Ok(ticket)
279 }
280
281 #[tracing::instrument(
282 name = "db.user_recovery.consume_ticket",
283 skip_all,
284 fields(
285 db.query.text,
286 %user_recovery_ticket.id,
287 user_email.id = %user_recovery_ticket.user_email_id,
288 %user_recovery_session.id,
289 %user_recovery_session.email,
290 ),
291 )]
292 async fn consume_ticket(
293 &mut self,
294 clock: &dyn Clock,
295 user_recovery_ticket: UserRecoveryTicket,
296 mut user_recovery_session: UserRecoverySession,
297 ) -> Result<UserRecoverySession, Self::Error> {
298 let _ = user_recovery_ticket;
300
301 if user_recovery_session.consumed_at.is_some() {
303 return Err(DatabaseError::invalid_operation());
304 }
305
306 let consumed_at = clock.now();
307
308 let res = sqlx::query!(
309 r#"
310 UPDATE user_recovery_sessions
311 SET consumed_at = $1
312 WHERE user_recovery_session_id = $2
313 "#,
314 consumed_at,
315 Uuid::from(user_recovery_session.id),
316 )
317 .traced()
318 .execute(&mut *self.conn)
319 .await?;
320
321 user_recovery_session.consumed_at = Some(consumed_at);
322
323 DatabaseError::ensure_affected_rows(&res, 1)?;
324
325 Ok(user_recovery_session)
326 }
327
328 #[tracing::instrument(
329 name = "db.user_recovery.cleanup",
330 skip_all,
331 fields(
332 db.query.text,
333 since = since.map(tracing::field::display),
334 until = %until,
335 limit = limit,
336 ),
337 )]
338 async fn cleanup(
339 &mut self,
340 since: Option<Ulid>,
341 until: Ulid,
342 limit: usize,
343 ) -> Result<(usize, Option<Ulid>), Self::Error> {
344 let res = sqlx::query_scalar!(
348 r#"
349 WITH to_delete AS (
350 SELECT user_recovery_session_id
351 FROM user_recovery_sessions
352 WHERE ($1::uuid IS NULL OR user_recovery_session_id > $1)
353 AND user_recovery_session_id <= $2
354 ORDER BY user_recovery_session_id
355 LIMIT $3
356 )
357 DELETE FROM user_recovery_sessions
358 USING to_delete
359 WHERE user_recovery_sessions.user_recovery_session_id = to_delete.user_recovery_session_id
360 RETURNING user_recovery_sessions.user_recovery_session_id
361 "#,
362 since.map(Uuid::from),
363 Uuid::from(until),
364 i64::try_from(limit).unwrap_or(i64::MAX)
365 )
366 .traced()
367 .fetch_all(&mut *self.conn)
368 .await?;
369
370 let count = res.len();
371 let max_id = res.into_iter().max();
372
373 Ok((count, max_id.map(Ulid::from)))
374 }
375}