1use time::OffsetDateTime;
4
5use crate::context::AuthContext;
6use crate::crypto::random::generate_random_string;
7use crate::db::{
8 Create, DbAdapter, DbRecord, DbValue, Delete, DeleteMany, FindMany, Sort, SortDirection,
9 Update, Verification, Where, WhereOperator,
10};
11use crate::error::OpenAuthError;
12use crate::options::SecondaryStorage;
13use std::sync::Arc;
14
15const VERIFICATION_MODEL: &str = "verification";
16const DEFAULT_ID_LENGTH: usize = 32;
17const VERIFICATION_FIELDS: [&str; 6] = [
18 "id",
19 "identifier",
20 "value",
21 "expires_at",
22 "created_at",
23 "updated_at",
24];
25
26#[derive(Debug, Clone, PartialEq, Eq)]
27pub struct CreateVerificationInput {
28 pub id: Option<String>,
29 pub identifier: String,
30 pub value: String,
31 pub expires_at: OffsetDateTime,
32}
33
34impl CreateVerificationInput {
35 pub fn new(
36 identifier: impl Into<String>,
37 value: impl Into<String>,
38 expires_at: OffsetDateTime,
39 ) -> Self {
40 Self {
41 id: None,
42 identifier: identifier.into(),
43 value: value.into(),
44 expires_at,
45 }
46 }
47
48 #[must_use]
49 pub fn id(mut self, id: impl Into<String>) -> Self {
50 self.id = Some(id.into());
51 self
52 }
53}
54
55#[derive(Debug, Clone, Default, PartialEq, Eq)]
56pub struct UpdateVerificationInput {
57 pub value: Option<String>,
58 pub expires_at: Option<OffsetDateTime>,
59}
60
61impl UpdateVerificationInput {
62 pub fn new() -> Self {
63 Self::default()
64 }
65
66 #[must_use]
67 pub fn value(mut self, value: impl Into<String>) -> Self {
68 self.value = Some(value.into());
69 self
70 }
71
72 #[must_use]
73 pub fn expires_at(mut self, expires_at: OffsetDateTime) -> Self {
74 self.expires_at = Some(expires_at);
75 self
76 }
77}
78
79#[derive(Clone, Copy)]
80pub struct DbVerificationStore<'a> {
81 adapter: &'a dyn DbAdapter,
82}
83
84impl<'a> DbVerificationStore<'a> {
85 pub fn new(adapter: &'a dyn DbAdapter) -> Self {
86 Self { adapter }
87 }
88
89 pub async fn create_verification(
90 &self,
91 input: CreateVerificationInput,
92 ) -> Result<Verification, OpenAuthError> {
93 let now = OffsetDateTime::now_utc();
94 let id = input
95 .id
96 .unwrap_or_else(|| generate_random_string(DEFAULT_ID_LENGTH));
97
98 let record = self
99 .adapter
100 .create(
101 Create::new(VERIFICATION_MODEL)
102 .data("id", DbValue::String(id))
103 .data("identifier", DbValue::String(input.identifier))
104 .data("value", DbValue::String(input.value))
105 .data("expires_at", DbValue::Timestamp(input.expires_at))
106 .data("created_at", DbValue::Timestamp(now))
107 .data("updated_at", DbValue::Timestamp(now))
108 .select(VERIFICATION_FIELDS)
109 .force_allow_id(),
110 )
111 .await?;
112
113 verification_from_record(record)
114 }
115
116 pub async fn find_verification(
117 &self,
118 identifier: &str,
119 ) -> Result<Option<Verification>, OpenAuthError> {
120 self.delete_expired_verifications().await?;
121
122 let Some(record) = self
123 .adapter
124 .find_many(
125 FindMany::new(VERIFICATION_MODEL)
126 .where_clause(identifier_where(identifier))
127 .sort_by(Sort::new("created_at", SortDirection::Desc))
128 .limit(1)
129 .select(VERIFICATION_FIELDS),
130 )
131 .await?
132 .into_iter()
133 .next()
134 else {
135 return Ok(None);
136 };
137
138 let verification = verification_from_record(record)?;
139 if verification.expires_at <= OffsetDateTime::now_utc() {
140 self.delete_expired_verifications().await?;
141 return Ok(None);
142 }
143
144 Ok(Some(verification))
145 }
146
147 pub async fn find_verification_including_expired(
148 &self,
149 identifier: &str,
150 ) -> Result<Option<Verification>, OpenAuthError> {
151 self.adapter
152 .find_many(
153 FindMany::new(VERIFICATION_MODEL)
154 .where_clause(identifier_where(identifier))
155 .sort_by(Sort::new("created_at", SortDirection::Desc))
156 .limit(1)
157 .select(VERIFICATION_FIELDS),
158 )
159 .await?
160 .into_iter()
161 .next()
162 .map(verification_from_record)
163 .transpose()
164 }
165
166 pub async fn update_verification(
167 &self,
168 identifier: &str,
169 input: UpdateVerificationInput,
170 ) -> Result<Option<Verification>, OpenAuthError> {
171 let mut query = Update::new(VERIFICATION_MODEL).where_clause(identifier_where(identifier));
172
173 if let Some(value) = input.value {
174 query = query.data("value", DbValue::String(value));
175 }
176 if let Some(expires_at) = input.expires_at {
177 query = query.data("expires_at", DbValue::Timestamp(expires_at));
178 }
179 query = query.data("updated_at", DbValue::Timestamp(OffsetDateTime::now_utc()));
180
181 self.adapter
182 .update(query)
183 .await?
184 .map(verification_from_record)
185 .transpose()
186 }
187
188 pub async fn delete_verification(&self, identifier: &str) -> Result<(), OpenAuthError> {
189 self.adapter
190 .delete(Delete::new(VERIFICATION_MODEL).where_clause(identifier_where(identifier)))
191 .await
192 }
193
194 pub async fn delete_expired_verifications(&self) -> Result<u64, OpenAuthError> {
195 self.adapter
196 .delete_many(
197 DeleteMany::new(VERIFICATION_MODEL).where_clause(
198 Where::new("expires_at", DbValue::Timestamp(OffsetDateTime::now_utc()))
199 .operator(WhereOperator::Lt),
200 ),
201 )
202 .await
203 }
204}
205
206#[derive(Clone)]
208pub struct VerificationStore<'a> {
209 database: DbVerificationStore<'a>,
210 secondary_storage: Option<Arc<dyn SecondaryStorage>>,
211}
212
213impl<'a> VerificationStore<'a> {
214 pub fn new(adapter: &'a dyn DbAdapter, context: &AuthContext) -> Self {
215 Self {
216 database: DbVerificationStore::new(adapter),
217 secondary_storage: context.secondary_storage(),
218 }
219 }
220
221 pub async fn create_verification(
222 &self,
223 input: CreateVerificationInput,
224 ) -> Result<Verification, OpenAuthError> {
225 let Some(storage) = &self.secondary_storage else {
226 return self.database.create_verification(input).await;
227 };
228 let now = OffsetDateTime::now_utc();
229 let verification = Verification {
230 id: input
231 .id
232 .unwrap_or_else(|| generate_random_string(DEFAULT_ID_LENGTH)),
233 identifier: input.identifier,
234 value: input.value,
235 expires_at: input.expires_at,
236 created_at: now,
237 updated_at: now,
238 };
239 storage
240 .set(
241 &verification_key(&verification.identifier),
242 serialize_verification(&verification)?,
243 ttl_seconds(verification.expires_at),
244 )
245 .await?;
246 Ok(verification)
247 }
248
249 pub async fn find_verification(
250 &self,
251 identifier: &str,
252 ) -> Result<Option<Verification>, OpenAuthError> {
253 let Some(storage) = &self.secondary_storage else {
254 return self.database.find_verification(identifier).await;
255 };
256 let Some(verification) = self
257 .find_secondary_verification(storage.as_ref(), identifier)
258 .await?
259 else {
260 return Ok(None);
261 };
262 if verification.expires_at <= OffsetDateTime::now_utc() {
263 storage.delete(&verification_key(identifier)).await?;
264 return Ok(None);
265 }
266 Ok(Some(verification))
267 }
268
269 pub async fn find_verification_including_expired(
270 &self,
271 identifier: &str,
272 ) -> Result<Option<Verification>, OpenAuthError> {
273 let Some(storage) = &self.secondary_storage else {
274 return self
275 .database
276 .find_verification_including_expired(identifier)
277 .await;
278 };
279 self.find_secondary_verification(storage.as_ref(), identifier)
280 .await
281 }
282
283 pub async fn update_verification(
284 &self,
285 identifier: &str,
286 input: UpdateVerificationInput,
287 ) -> Result<Option<Verification>, OpenAuthError> {
288 let Some(storage) = &self.secondary_storage else {
289 return self.database.update_verification(identifier, input).await;
290 };
291 let Some(mut verification) = self
292 .find_secondary_verification(storage.as_ref(), identifier)
293 .await?
294 else {
295 return Ok(None);
296 };
297 if let Some(value) = input.value {
298 verification.value = value;
299 }
300 if let Some(expires_at) = input.expires_at {
301 verification.expires_at = expires_at;
302 }
303 verification.updated_at = OffsetDateTime::now_utc();
304 storage
305 .set(
306 &verification_key(identifier),
307 serialize_verification(&verification)?,
308 ttl_seconds(verification.expires_at),
309 )
310 .await?;
311 Ok(Some(verification))
312 }
313
314 pub async fn delete_verification(&self, identifier: &str) -> Result<(), OpenAuthError> {
315 let Some(storage) = &self.secondary_storage else {
316 return self.database.delete_verification(identifier).await;
317 };
318 storage.delete(&verification_key(identifier)).await
319 }
320
321 pub async fn delete_expired_verifications(&self) -> Result<u64, OpenAuthError> {
322 let Some(_storage) = &self.secondary_storage else {
323 return self.database.delete_expired_verifications().await;
324 };
325 Ok(0)
326 }
327
328 async fn find_secondary_verification(
329 &self,
330 storage: &dyn SecondaryStorage,
331 identifier: &str,
332 ) -> Result<Option<Verification>, OpenAuthError> {
333 storage
334 .get(&verification_key(identifier))
335 .await?
336 .map(|value| deserialize_verification(&value))
337 .transpose()
338 }
339}
340
341fn identifier_where(identifier: &str) -> Where {
342 Where::new("identifier", DbValue::String(identifier.to_owned()))
343}
344
345fn verification_from_record(record: DbRecord) -> Result<Verification, OpenAuthError> {
346 Ok(Verification {
347 id: required_string(&record, "id")?.to_owned(),
348 identifier: required_string(&record, "identifier")?.to_owned(),
349 value: required_string(&record, "value")?.to_owned(),
350 expires_at: required_timestamp(&record, "expires_at")?,
351 created_at: required_timestamp(&record, "created_at")?,
352 updated_at: required_timestamp(&record, "updated_at")?,
353 })
354}
355
356fn verification_key(identifier: &str) -> String {
357 format!("verification:{identifier}")
358}
359
360fn serialize_verification(verification: &Verification) -> Result<String, OpenAuthError> {
361 serde_json::to_string(verification).map_err(|error| OpenAuthError::Serialization {
362 context: "serializing verification record",
363 message: error.to_string(),
364 })
365}
366
367fn deserialize_verification(value: &str) -> Result<Verification, OpenAuthError> {
368 serde_json::from_str(value).map_err(|error| OpenAuthError::Serialization {
369 context: "deserializing verification record",
370 message: error.to_string(),
371 })
372}
373
374fn ttl_seconds(expires_at: OffsetDateTime) -> Option<u64> {
375 let seconds = (expires_at - OffsetDateTime::now_utc()).whole_seconds();
376 Some(u64::try_from(seconds.max(0)).unwrap_or(0))
377}
378
379fn required_string<'a>(record: &'a DbRecord, field: &str) -> Result<&'a str, OpenAuthError> {
380 match record.get(field) {
381 Some(DbValue::String(value)) => Ok(value),
382 Some(_) => Err(invalid_field(field, "string")),
383 None => Err(missing_field(field)),
384 }
385}
386
387fn required_timestamp(record: &DbRecord, field: &str) -> Result<OffsetDateTime, OpenAuthError> {
388 match record.get(field) {
389 Some(DbValue::Timestamp(value)) => Ok(*value),
390 Some(_) => Err(invalid_field(field, "timestamp")),
391 None => Err(missing_field(field)),
392 }
393}
394
395fn missing_field(field: &str) -> OpenAuthError {
396 OpenAuthError::MissingRecordField {
397 record: "verification",
398 field: field.to_owned(),
399 }
400}
401
402fn invalid_field(field: &str, expected: &'static str) -> OpenAuthError {
403 OpenAuthError::InvalidRecordField {
404 record: "verification",
405 field: field.to_owned(),
406 expected,
407 }
408}