1use std::any::Any;
5use std::borrow::Cow;
6use std::marker::PhantomData;
7
8use http::StatusCode;
9use time::{Duration, OffsetDateTime};
10
11use crate::adapter::{Adapter, DbError, Queries, Transaction, Update};
12use crate::crypto::{Hash, random_bytes, random_token};
13use crate::endpoint::{Ctx, Gate, SignInAttempt};
14use crate::error::{AuthError, codes};
15use crate::events::{
16 AccountLinked, EmailVerified, SessionCreated, SessionRevoked, UserClaimed, UserCreated,
17};
18use crate::mail::{AuthEmail, VerifyEmail};
19use crate::model::{Col, Model, OnTable};
20use crate::models::{Account, Session, User, Verification};
21use crate::query::Db;
22use crate::schema::Schema;
23use crate::session::{
24 DONT_REMEMBER_LIFETIME, SESSION_DATA, SessionView, UserView, clear_session_cookies,
25 set_session_cookies,
26};
27use crate::value::{ColumnValue, Id, Value};
28
29#[derive(Clone, Debug, Default)]
31pub struct NewUser {
32 pub email: String,
33 pub name: String,
34 pub image: Option<String>,
35 pub email_verified: bool,
36 pub extra: Vec<(&'static str, Value)>,
38}
39
40#[derive(Clone, Debug, Default)]
42pub struct NewAccount {
43 pub provider_id: String,
44 pub account_id: Option<String>,
46 pub password_hash: Option<String>,
47 pub access_token: Option<String>,
49 pub refresh_token: Option<String>,
51 pub id_token: Option<String>,
52 pub access_token_expires_at: Option<OffsetDateTime>,
53 pub refresh_token_expires_at: Option<OffsetDateTime>,
54 pub scope: Option<String>,
55}
56
57#[derive(Clone, Debug, Default)]
60pub struct NewSession {
61 expires_at: Option<OffsetDateTime>,
62 values: Vec<(&'static str, Value)>,
63}
64
65impl NewSession {
66 pub fn new() -> Self {
67 Self::default()
68 }
69
70 pub fn expires_at(mut self, expires_at: OffsetDateTime) -> Self {
72 self.expires_at = Some(expires_at);
73 self
74 }
75
76 pub fn set<O: OnTable<Table = Session>, T: ColumnValue>(
78 mut self,
79 column: Col<O, T>,
80 value: impl Into<T>,
81 ) -> Self {
82 self.values.push((column.name(), value.into().into_value()));
83 self
84 }
85}
86
87impl NewAccount {
88 pub fn credential(password_hash: String) -> Self {
89 Self {
90 provider_id: Account::CREDENTIAL.into(),
91 password_hash: Some(password_hash),
92 ..Self::default()
93 }
94 }
95
96 pub fn oauth(provider_id: impl Into<String>, account_id: impl Into<String>) -> Self {
97 Self {
98 provider_id: provider_id.into(),
99 account_id: Some(account_id.into()),
100 ..Self::default()
101 }
102 }
103}
104
105#[derive(Clone, Copy, Debug, PartialEq, Eq)]
107pub enum UserInput {
108 SignUp,
110 Create,
112 Update,
114}
115
116#[derive(Clone, Debug)]
117pub enum SignInResult {
118 SignedIn(Box<SessionView>),
119 Challenge(serde_json::Value),
121}
122
123fn user_exists(err: DbError) -> AuthError {
124 match err {
125 DbError::UniqueViolation { ref table, .. } if table == User::TABLE => AuthError::new(
126 StatusCode::UNPROCESSABLE_ENTITY,
127 codes::USER_ALREADY_EXISTS_USE_ANOTHER_EMAIL,
128 "user already exists, use another email",
129 ),
130 other => other.into(),
131 }
132}
133
134fn account_linked(err: DbError) -> AuthError {
135 match err {
136 DbError::UniqueViolation {
137 ref table,
138 column: None,
139 } if table == Account::TABLE => AuthError::new(
140 StatusCode::CONFLICT,
141 codes::SOCIAL_ACCOUNT_ALREADY_LINKED,
142 "social account already linked",
143 ),
144 other => other.into(),
145 }
146}
147
148const PENDING_VERIFICATION: &str = "pending_verification";
150
151fn new_security_stamp() -> i64 {
153 i64::from_le_bytes(random_bytes::<8>())
154}
155
156pub(crate) fn url_encode(value: &str) -> String {
157 url::form_urlencoded::byte_serialize(value.as_bytes()).collect()
158}
159
160fn claimed_meanwhile() -> AuthError {
163 AuthError::new(
164 StatusCode::UNAUTHORIZED,
165 codes::UNAUTHORIZED,
166 "the account changed meanwhile; sign in again",
167 )
168}
169
170pub struct Claim<'a, D> {
175 user_id: &'a Id,
176 tx: &'a (dyn Any + Send + Sync),
177 schema: &'a Schema,
178 _adapter: PhantomData<fn() -> D>,
179}
180
181impl<'a, D: Adapter> Claim<'a, D> {
182 pub fn user_id(&self) -> &'a Id {
184 self.user_id
185 }
186
187 pub fn db(&self) -> Db<'a, D::Tx> {
189 let tx = self
190 .tx
191 .downcast_ref::<D::Tx>()
192 .expect("a claim runs in its adapter's transaction");
193 Db::new(tx, self.schema)
194 }
195}
196
197impl<D> std::fmt::Debug for Claim<'_, D> {
198 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
199 f.debug_struct("Claim")
200 .field("user_id", self.user_id)
201 .finish_non_exhaustive()
202 }
203}
204
205fn user_verification_identifiers(user_id: &Id) -> [String; 2] {
207 [
208 format!("email-verification:{user_id}"),
209 format!("reset-password:{user_id}"),
210 ]
211}
212
213fn user_binding(user: &UserView) -> String {
216 format!("{}:{}", user.security_stamp(), user.email)
217}
218
219pub struct Internal<'a, D, A> {
220 ctx: &'a Ctx<D, A>,
221}
222
223impl<'a, D: Adapter, A> Internal<'a, D, A> {
224 pub(crate) fn new(ctx: &'a Ctx<D, A>) -> Self {
225 Self { ctx }
226 }
227
228 pub async fn find_user_by_email(&self, email: &str) -> Result<Option<UserView>, AuthError> {
229 let row = self
230 .ctx
231 .db()
232 .find::<User>(User::EMAIL.eq(email.trim().to_lowercase()))
233 .one_row()
234 .await?;
235 row.map(UserView::from_row)
236 .transpose()
237 .map_err(AuthError::internal)
238 }
239
240 pub async fn find_user_by_id(&self, id: &Id) -> Result<Option<UserView>, AuthError> {
241 let row = self
242 .ctx
243 .db()
244 .find::<User>(User::ID.eq(id))
245 .one_row()
246 .await?;
247 row.map(UserView::from_row)
248 .transpose()
249 .map_err(AuthError::internal)
250 }
251
252 fn account_values(
253 &self,
254 user_id: &Id,
255 account: NewAccount,
256 ) -> Result<Vec<(&'static str, Value)>, AuthError> {
257 let keys = self.ctx.keys();
258 let seal = |t: Option<String>| t.map(|t| keys.encrypt(t.as_bytes()));
259 Ok(vec![
260 ("id", self.ctx.new_id()?.into_value()),
261 ("user_id", user_id.clone().into_value()),
262 ("provider_id", account.provider_id.into_value()),
263 (
264 "account_id",
265 account
266 .account_id
267 .unwrap_or_else(|| user_id.to_string())
268 .into_value(),
269 ),
270 ("password_hash", account.password_hash.into_value()),
271 ("access_token", seal(account.access_token).into_value()),
272 ("refresh_token", seal(account.refresh_token).into_value()),
273 ("id_token", account.id_token.into_value()),
274 (
275 "access_token_expires_at",
276 account.access_token_expires_at.into_value(),
277 ),
278 (
279 "refresh_token_expires_at",
280 account.refresh_token_expires_at.into_value(),
281 ),
282 ("scope", account.scope.into_value()),
283 ])
284 }
285
286 pub async fn create_user(
289 &self,
290 user: NewUser,
291 account: Option<NewAccount>,
292 ) -> Result<UserView, AuthError> {
293 let id = self.ctx.new_id()?;
294 let mut values = vec![
295 ("id", id.clone().into_value()),
296 ("email", user.email.trim().to_lowercase().into_value()),
297 ("email_verified", user.email_verified.into_value()),
298 ("name", user.name.into_value()),
299 ("image", user.image.into_value()),
300 ];
301 values.extend(user.extra);
302 let account = account
303 .map(|account| self.account_values(&id, account))
304 .transpose()?;
305 let tx = self.ctx.adapter().begin().await?;
306 let db = self.ctx.db_on(&tx);
307 let row = db.insert_row::<User>(values).await.map_err(user_exists)?;
308 if let Some(account) = account {
309 db.insert_row::<Account>(account)
310 .await
311 .map_err(account_linked)?;
312 }
313 tx.commit().await?;
314 let view = UserView::from_row(row).map_err(AuthError::internal)?;
315 self.ctx.emit(UserCreated {
316 user_id: view.id.clone(),
317 email: view.email.clone(),
318 });
319 Ok(view)
320 }
321
322 pub async fn link_account(
323 &self,
324 user_id: &Id,
325 account: NewAccount,
326 ) -> Result<Account, AuthError> {
327 let provider_id = account.provider_id.clone();
328 let row = self
329 .ctx
330 .db()
331 .insert_row::<Account>(self.account_values(user_id, account)?)
332 .await
333 .map_err(account_linked)?;
334 self.ctx.emit(AccountLinked {
335 user_id: user_id.clone(),
336 provider_id,
337 });
338 Account::decode(&row).map_err(AuthError::internal)
339 }
340
341 pub async fn link_account_unless_claimed(
347 &self,
348 user: &UserView,
349 account: NewAccount,
350 ) -> Result<Account, AuthError> {
351 let provider_id = account.provider_id.clone();
352 let values = self.account_values(&user.id, account)?;
353 let tx = self.lock_user_unless_claimed(user).await?;
354 let row = self
355 .ctx
356 .db_on(&tx)
357 .insert_row::<Account>(values)
358 .await
359 .map_err(account_linked)?;
360 tx.commit().await?;
361 self.ctx.emit(AccountLinked {
362 user_id: user.id.clone(),
363 provider_id,
364 });
365 Account::decode(&row).map_err(AuthError::internal)
366 }
367
368 pub async fn lock_user_unless_claimed(&self, user: &UserView) -> Result<D::Tx, AuthError> {
380 let tx = self.ctx.adapter().begin().await?;
381 match self
382 .stamp_holds_on(&tx, &user.id, user.security_stamp())
383 .await
384 {
385 Ok(true) => Ok(tx),
386 Ok(false) => {
387 tx.rollback().await?;
388 Err(claimed_meanwhile())
389 }
390 Err(err) => {
391 let _ = tx.rollback().await;
392 Err(err)
393 }
394 }
395 }
396
397 async fn stamp_holds(&self, user_id: &Id, stamp: i64) -> Result<bool, AuthError> {
401 self.stamp_holds_on(self.ctx.adapter(), user_id, stamp)
402 .await
403 }
404
405 async fn stamp_holds_on<Q: Queries>(
408 &self,
409 db: &Q,
410 user_id: &Id,
411 stamp: i64,
412 ) -> Result<bool, AuthError> {
413 let table = self.ctx.schema().expect(User::TABLE);
414 let filter = User::ID
415 .eq(user_id)
416 .and(User::SECURITY_STAMP.eq(stamp))
417 .resolve(table)?;
418 let column = table
419 .position(User::SECURITY_STAMP.name())
420 .ok_or_else(|| AuthError::internal("user.security_stamp missing"))?;
421 let matched = db
422 .update(Update {
423 table,
424 filter,
425 set: vec![(column, Value::Int(stamp))],
426 })
427 .await?;
428 Ok(matched == 1)
429 }
430
431 pub async fn find_account(
432 &self,
433 provider_id: &str,
434 account_id: &str,
435 ) -> Result<Option<Account>, AuthError> {
436 let filter = Account::PROVIDER_ID
437 .eq(provider_id)
438 .and(Account::ACCOUNT_ID.eq(account_id));
439 Ok(self.ctx.db().find::<Account>(filter).one().await?)
440 }
441
442 pub async fn credential_account(&self, user_id: &Id) -> Result<Option<Account>, AuthError> {
443 let filter = Account::USER_ID
444 .eq(user_id)
445 .and(Account::PROVIDER_ID.eq(Account::CREDENTIAL));
446 Ok(self.ctx.db().find::<Account>(filter).one().await?)
447 }
448
449 pub async fn user_fields(
454 &self,
455 extra: &serde_json::Map<String, serde_json::Value>,
456 input: UserInput,
457 ) -> Result<Vec<(&'static str, Value)>, AuthError> {
458 let mut extra = extra.clone();
459 for hook in &self.ctx.shared.user_input_hooks {
460 extra = hook(self.ctx.retype(), extra, input).await?;
461 }
462 crate::routes::user_input_fields(self.ctx, &extra, input != UserInput::Update)
463 }
464
465 pub fn validate_new_password(&self, password: &str) -> Result<(), AuthError> {
467 let Some(config) = &self.ctx.config().email_password else {
468 return Ok(());
469 };
470 let length = password.chars().count();
471 if length < config.min_password_length {
472 return Err(AuthError::bad_request(
473 codes::PASSWORD_TOO_SHORT,
474 "password is too short",
475 ));
476 }
477 if length > config.max_password_length {
478 return Err(AuthError::bad_request(
479 codes::PASSWORD_TOO_LONG,
480 "password is too long",
481 ));
482 }
483 if config
484 .password_policy
485 .as_ref()
486 .is_some_and(|policy| !policy(password))
487 {
488 return Err(AuthError::bad_request(
489 codes::PASSWORD_TOO_WEAK,
490 "password is too weak",
491 ));
492 }
493 Ok(())
494 }
495
496 pub async fn set_password(&self, user: &UserView, password: &str) -> Result<(), AuthError> {
502 self.validate_new_password(password)?;
503 let hash = self
504 .ctx
505 .passwords()
506 .hash(password)
507 .await
508 .map_err(AuthError::internal)?;
509 let credential = || {
510 Account::USER_ID
511 .eq(&user.id)
512 .and(Account::PROVIDER_ID.eq(Account::CREDENTIAL))
513 };
514 let tx = self.lock_user_unless_claimed(user).await?;
515 let db = self.ctx.db_on(&tx);
516 if db.find::<Account>(credential()).one().await?.is_some() {
517 db.update::<Account>(credential())
518 .set(Account::PASSWORD_HASH, Some(hash))
519 .exec()
520 .await?;
521 tx.commit().await?;
522 return Ok(());
523 }
524 db.insert_row::<Account>(self.account_values(&user.id, NewAccount::credential(hash))?)
525 .await
526 .map_err(account_linked)?;
527 tx.commit().await?;
528 self.ctx.emit(AccountLinked {
529 user_id: user.id.clone(),
530 provider_id: Account::CREDENTIAL.into(),
531 });
532 Ok(())
533 }
534
535 pub async fn create_session(
544 &self,
545 user_id: &Id,
546 remember_me: bool,
547 ) -> Result<SessionView, AuthError> {
548 self.create_session_with(user_id, remember_me, NewSession::default())
549 .await
550 }
551
552 pub async fn create_session_unless_claimed(
557 &self,
558 user: &UserView,
559 remember_me: bool,
560 ) -> Result<SessionView, AuthError> {
561 self.insert_session(
562 &user.id,
563 Some(user.security_stamp()),
564 remember_me,
565 NewSession::default(),
566 )
567 .await
568 }
569
570 pub async fn create_session_with(
573 &self,
574 user_id: &Id,
575 remember_me: bool,
576 options: NewSession,
577 ) -> Result<SessionView, AuthError> {
578 self.insert_session(user_id, None, remember_me, options)
579 .await
580 }
581
582 async fn insert_session(
586 &self,
587 user_id: &Id,
588 stamp: Option<i64>,
589 remember_me: bool,
590 options: NewSession,
591 ) -> Result<SessionView, AuthError> {
592 let now = self.ctx.now();
593 let token = random_token();
594 let lifetime = match remember_me {
595 true => self.ctx.config().session.expires_in,
596 false => self
597 .ctx
598 .config()
599 .session
600 .expires_in
601 .min(DONT_REMEMBER_LIFETIME),
602 };
603 let session = Session {
604 id: self.ctx.new_id()?,
605 token_hash: Hash::sha256(&token),
606 user_id: user_id.clone(),
607 expires_at: options.expires_at.unwrap_or(now + lifetime),
608 ip_address: self.ctx.ip().map(str::to_owned),
609 user_agent: self
610 .ctx
611 .user_agent()
612 .map(|ua| ua.chars().take(512).collect()),
613 created_at: now,
614 updated_at: now,
615 };
616 let mut values = session.encode();
617 values.extend(options.values);
618 let row = self.ctx.db().insert_row::<Session>(values).await?;
619 let session = Session::decode(&row).map_err(AuthError::internal)?;
620 if let Some(stamp) = stamp
621 && !self.stamp_holds(user_id, stamp).await?
622 {
623 self.ctx
624 .db()
625 .delete::<Session>(Session::ID.eq(&session.id))
626 .await?;
627 return Err(claimed_meanwhile());
628 }
629 let user = self
630 .find_user_by_id(user_id)
631 .await?
632 .ok_or_else(|| AuthError::internal("session for a missing user"))?;
633 let view = SessionView {
634 session,
635 row,
636 user,
637 token: Some(token.clone()),
638 ephemeral: false,
639 from_cache: false,
640 };
641 let config = self.ctx.config();
642 let before = self.ctx.effects.lock().unwrap().cookies.clone();
643 set_session_cookies(
644 config,
645 self.ctx.keys(),
646 &self.ctx.effects,
647 &token,
648 remember_me,
649 );
650 for hook in &self.ctx.shared.session_hooks {
651 if let Err(err) = hook(self.ctx.retype(), view.clone()).await {
652 self.ctx.effects.lock().unwrap().cookies = before;
653 self.ctx
654 .db()
655 .delete::<Session>(Session::ID.eq(&view.session.id))
656 .await?;
657 return Err(err);
658 }
659 }
660 self.ctx.set_cookie(crate::cookies::SetCookie::delete(
661 config.cookie_name(SESSION_DATA),
662 ));
663 self.ctx.emit(SessionCreated {
664 session_id: view.session.id.clone(),
665 user_id: user_id.clone(),
666 });
667 Ok(view)
668 }
669
670 pub async fn find_session_by_token(
673 &self,
674 token: &str,
675 ) -> Result<Option<SessionView>, AuthError> {
676 crate::session::by_token(&self.ctx.shared, self.ctx.adapter(), token).await
677 }
678
679 pub async fn ephemeral_session(&self, user_id: &Id) -> Result<Option<SessionView>, AuthError> {
684 crate::session::for_user(
685 &self.ctx.shared,
686 self.ctx.within.as_ref(),
687 &self.ctx.request,
688 &self.ctx.effects,
689 user_id,
690 )
691 .await
692 }
693
694 pub fn set_session_cookies(&self, token: &str, remember_me: bool) {
698 let config = self.ctx.config();
699 set_session_cookies(
700 config,
701 self.ctx.keys(),
702 &self.ctx.effects,
703 token,
704 remember_me,
705 );
706 self.ctx.set_cookie(crate::cookies::SetCookie::delete(
707 config.cookie_name(SESSION_DATA),
708 ));
709 }
710
711 pub async fn sign_in(
719 &self,
720 user: UserView,
721 method: impl Into<Cow<'static, str>>,
722 remember_me: bool,
723 ) -> Result<SignInResult, AuthError> {
724 self.run_gates(user, method.into(), remember_me, None).await
725 }
726
727 pub async fn complete_sign_in(
742 &self,
743 challenger: &str,
744 user: UserView,
745 method: impl Into<Cow<'static, str>>,
746 remember_me: bool,
747 ) -> Result<SignInResult, AuthError> {
748 if !self
749 .ctx
750 .shared
751 .gates
752 .iter()
753 .any(|gate| gate.owner == challenger)
754 {
755 return Err(AuthError::internal(format!(
756 "complete_sign_in: no sign-in gate belongs to `{challenger}`"
757 )));
758 }
759 self.run_gates(user, method.into(), remember_me, Some(challenger))
760 .await
761 }
762
763 async fn run_gates(
764 &self,
765 user: UserView,
766 method: Cow<'static, str>,
767 remember_me: bool,
768 skip: Option<&str>,
769 ) -> Result<SignInResult, AuthError> {
770 let attempt = SignInAttempt {
771 user: user.clone(),
772 method,
773 remember_me,
774 };
775 for owned in &self.ctx.shared.gates {
776 if skip == Some(owned.owner) {
777 continue;
778 }
779 match (owned.gate)(self.ctx.retype(), attempt.clone()).await? {
780 Gate::Allow => {}
781 Gate::Deny(err) => return Err(err),
782 Gate::Challenge(body) => return Ok(SignInResult::Challenge(body)),
783 }
784 }
785 Ok(SignInResult::SignedIn(Box::new(
786 self.insert_session(
787 &user.id,
788 Some(user.security_stamp()),
789 remember_me,
790 NewSession::default(),
791 )
792 .await?,
793 )))
794 }
795
796 pub async fn claim_user(
814 &self,
815 user: UserView,
816 link: Option<NewAccount>,
817 ) -> Result<UserView, AuthError> {
818 let linked_provider = link.as_ref().map(|account| account.provider_id.clone());
819 let link = link
820 .map(|account| self.account_values(&user.id, account))
821 .transpose()?;
822 if !user.email_verified {
823 let tx = self.ctx.adapter().begin().await?;
824 match self.claim_in(&tx, &user.id, link.clone()).await {
825 Ok(Some(revoked)) => {
826 tx.commit().await?;
827 if revoked > 0 {
828 self.ctx.emit(SessionRevoked {
829 user_id: user.id.clone(),
830 session_id: None,
831 });
832 }
833 self.ctx.emit(EmailVerified {
834 user_id: user.id.clone(),
835 });
836 self.ctx.emit(UserClaimed {
837 user_id: user.id.clone(),
838 });
839 if let Some(provider_id) = linked_provider {
840 self.ctx.emit(AccountLinked {
841 user_id: user.id.clone(),
842 provider_id,
843 });
844 }
845 return self
846 .find_user_by_id(&user.id)
847 .await?
848 .ok_or_else(|| AuthError::internal("user deleted while claiming it"));
849 }
850 Ok(None) => tx.rollback().await?,
852 Err(err) => {
853 let _ = tx.rollback().await;
854 return Err(err);
855 }
856 }
857 }
858 if let Some(values) = link {
859 self.ctx
860 .db()
861 .insert_row::<Account>(values)
862 .await
863 .map_err(account_linked)?;
864 if let Some(provider_id) = linked_provider {
865 self.ctx.emit(AccountLinked {
866 user_id: user.id.clone(),
867 provider_id,
868 });
869 }
870 }
871 self.find_user_by_id(&user.id)
872 .await?
873 .ok_or_else(|| AuthError::internal("user deleted while claiming it"))
874 }
875
876 #[deprecated(since = "0.6.0", note = "use `claim_user(user, None)`")]
878 pub async fn claim_unverified_user(&self, user: UserView) -> Result<UserView, AuthError> {
879 self.claim_user(user, None).await
880 }
881
882 async fn claim_in(
886 &self,
887 tx: &D::Tx,
888 user_id: &Id,
889 link: Option<Vec<(&'static str, Value)>>,
890 ) -> Result<Option<u64>, AuthError> {
891 let db = self.ctx.db_on(tx);
892 let claimed = db
893 .update::<User>(User::ID.eq(user_id).and(User::EMAIL_VERIFIED.eq(false)))
894 .set(User::SECURITY_STAMP, new_security_stamp())
895 .set(User::EMAIL_VERIFIED, true)
896 .exec()
897 .await?;
898 if claimed == 0 {
899 return Ok(None);
900 }
901 db.delete::<Account>(Account::USER_ID.eq(user_id)).await?;
902 let revoked = db.delete::<Session>(Session::USER_ID.eq(user_id)).await?;
903 db.delete::<Verification>(
904 Verification::IDENTIFIER.in_(user_verification_identifiers(user_id)),
905 )
906 .await?;
907 for cleanup in &self.ctx.shared.claim_hooks {
908 cleanup(Claim {
909 user_id,
910 tx,
911 schema: self.ctx.schema(),
912 _adapter: PhantomData,
913 })
914 .await?;
915 }
916 if let Some(values) = link {
917 db.insert_row::<Account>(values)
918 .await
919 .map_err(account_linked)?;
920 }
921 Ok(Some(revoked))
922 }
923
924 pub async fn prove_email(&self, user: UserView) -> Result<UserView, AuthError> {
932 if user.email_verified {
933 return Ok(user);
934 }
935 if !self.holds_credentials_of(&user).await? {
936 return self.claim_user(user, None).await;
937 }
938 self.ctx
939 .db()
940 .update::<User>(User::ID.eq(&user.id))
941 .set(User::EMAIL_VERIFIED, true)
942 .exec()
943 .await?;
944 self.ctx.emit(EmailVerified {
945 user_id: user.id.clone(),
946 });
947 self.find_user_by_id(&user.id)
948 .await?
949 .ok_or_else(|| AuthError::internal("user deleted while verifying it"))
950 }
951
952 async fn holds_credentials_of(&self, user: &UserView) -> Result<bool, AuthError> {
961 let binding = self.ctx.signed_token_cookie(PENDING_VERIFICATION);
962 if binding.is_some() {
963 self.ctx.delete_cookie(PENDING_VERIFICATION);
964 }
965 if binding.as_deref() == Some(user_binding(user).as_str()) {
966 return Ok(true);
967 }
968 let Some(token) = self.ctx.signed_token_cookie(crate::session::SESSION_TOKEN) else {
969 return Ok(false);
970 };
971 Ok(self
972 .find_session_by_token(&token)
973 .await?
974 .is_some_and(|session| !session.ephemeral && session.user.id == user.id))
975 }
976
977 pub fn remember_password_holder(&self, user: &UserView) {
981 self.ctx.set_signed_cookie(
982 PENDING_VERIFICATION,
983 &user_binding(user),
984 Some(self.ctx.config().email_verification.ttl),
985 );
986 }
987
988 pub async fn create_user_verification(
993 &self,
994 purpose: &str,
995 user: &UserView,
996 ttl: Duration,
997 ) -> Result<String, AuthError> {
998 self.create_verification(
999 &format!("{purpose}:{}", user.id),
1000 ttl,
1001 Some(user_binding(user)),
1002 )
1003 .await
1004 }
1005
1006 pub async fn consume_user_verification(
1010 &self,
1011 purpose: &str,
1012 token: &str,
1013 ) -> Result<Option<UserView>, AuthError> {
1014 let Some(verification) = self.consume_verification(token).await? else {
1015 return Ok(None);
1016 };
1017 let Some(user_id) = verification
1018 .identifier
1019 .strip_prefix(purpose)
1020 .and_then(|rest| rest.strip_prefix(':'))
1021 else {
1022 return Ok(None);
1023 };
1024 let Some(user) = self.find_user_by_id(&Id::from(user_id)).await? else {
1025 return Ok(None);
1026 };
1027 let bound = verification.data.as_deref() == Some(user_binding(&user).as_str());
1028 Ok(bound.then_some(user))
1029 }
1030
1031 pub async fn revoke_session(&self, user_id: &Id, session_id: &Id) -> Result<bool, AuthError> {
1032 let deleted = self
1033 .ctx
1034 .db()
1035 .delete::<Session>(Session::ID.eq(session_id).and(Session::USER_ID.eq(user_id)))
1036 .await?;
1037 if deleted > 0 {
1038 self.ctx.emit(SessionRevoked {
1039 user_id: user_id.clone(),
1040 session_id: Some(session_id.clone()),
1041 });
1042 }
1043 Ok(deleted > 0)
1044 }
1045
1046 pub async fn revoke_user_sessions(
1048 &self,
1049 user_id: &Id,
1050 keep: Option<&Id>,
1051 ) -> Result<u64, AuthError> {
1052 let mut filter = Session::USER_ID.eq(user_id);
1053 if let Some(keep) = keep {
1054 filter = filter.and(Session::ID.ne(keep));
1055 }
1056 let deleted = self.ctx.db().delete::<Session>(filter).await?;
1057 if deleted > 0 {
1058 self.ctx.emit(SessionRevoked {
1059 user_id: user_id.clone(),
1060 session_id: None,
1061 });
1062 }
1063 Ok(deleted)
1064 }
1065
1066 pub fn clear_session_cookies(&self) {
1067 clear_session_cookies(self.ctx.config(), &self.ctx.effects);
1068 }
1069
1070 async fn purge_expired_verifications(&self) -> Result<(), AuthError> {
1074 self.ctx
1075 .db()
1076 .delete::<Verification>(Verification::EXPIRES_AT.lt(self.ctx.now()))
1077 .await?;
1078 Ok(())
1079 }
1080
1081 pub async fn create_verification(
1083 &self,
1084 identifier: &str,
1085 ttl: Duration,
1086 data: Option<String>,
1087 ) -> Result<String, AuthError> {
1088 self.purge_expired_verifications().await?;
1089 let token = random_token();
1090 let now = self.ctx.now();
1091 let verification = Verification {
1092 id: self.ctx.new_id()?,
1093 identifier: identifier.to_owned(),
1094 value_hash: Hash::sha256(&token),
1095 data,
1096 expires_at: now + ttl,
1097 created_at: now,
1098 updated_at: now,
1099 };
1100 self.ctx.db().insert(&verification).await?;
1101 Ok(token)
1102 }
1103
1104 pub async fn store_verification_value(
1106 &self,
1107 identifier: &str,
1108 value: &str,
1109 ttl: Duration,
1110 data: Option<String>,
1111 ) -> Result<(), AuthError> {
1112 self.purge_expired_verifications().await?;
1113 self.ctx
1114 .db()
1115 .delete::<Verification>(Verification::IDENTIFIER.eq(identifier))
1116 .await?;
1117 let now = self.ctx.now();
1118 let verification = Verification {
1119 id: self.ctx.new_id()?,
1120 identifier: identifier.to_owned(),
1121 value_hash: Hash::sha256(format!("{identifier}:{value}")),
1122 data,
1123 expires_at: now + ttl,
1124 created_at: now,
1125 updated_at: now,
1126 };
1127 self.ctx.db().insert(&verification).await?;
1128 Ok(())
1129 }
1130
1131 pub async fn consume_verification_value(
1133 &self,
1134 identifier: &str,
1135 value: &str,
1136 ) -> Result<Option<Verification>, AuthError> {
1137 self.consume_hash(Hash::sha256(format!("{identifier}:{value}")))
1138 .await
1139 }
1140
1141 pub async fn find_verification(&self, token: &str) -> Result<Option<Verification>, AuthError> {
1143 let found = self
1144 .ctx
1145 .db()
1146 .find::<Verification>(Verification::VALUE_HASH.eq(Hash::sha256(token)))
1147 .one()
1148 .await?;
1149 Ok(found.filter(|v| v.expires_at > self.ctx.now()))
1150 }
1151
1152 pub async fn consume_verification(
1154 &self,
1155 token: &str,
1156 ) -> Result<Option<Verification>, AuthError> {
1157 self.consume_hash(Hash::sha256(token)).await
1158 }
1159
1160 async fn consume_hash(&self, hash: Hash) -> Result<Option<Verification>, AuthError> {
1161 let Some(found) = self
1162 .ctx
1163 .db()
1164 .find::<Verification>(Verification::VALUE_HASH.eq(hash))
1165 .one()
1166 .await?
1167 else {
1168 return Ok(None);
1169 };
1170 let deleted = self
1171 .ctx
1172 .db()
1173 .delete::<Verification>(Verification::ID.eq(&found.id))
1174 .await?;
1175 Ok((deleted == 1 && found.expires_at > self.ctx.now()).then_some(found))
1176 }
1177
1178 pub fn can_send_email(&self) -> bool {
1180 self.ctx.mailer().is_some()
1181 }
1182
1183 pub async fn send_email(&self, email: AuthEmail) -> Result<(), AuthError> {
1184 let Some(mailer) = self.ctx.mailer() else {
1185 return Err(AuthError::internal(
1186 "an email needs sending but no mailer is configured",
1187 ));
1188 };
1189 mailer.send(email).await.map_err(AuthError::internal)
1190 }
1191
1192 pub async fn send_email_in_background(&self, email: AuthEmail) -> Result<(), AuthError> {
1196 let Some(mailer) = self.ctx.mailer() else {
1197 return Err(AuthError::internal(
1198 "an email needs sending but no mailer is configured",
1199 ));
1200 };
1201 crate::mail::send_in_background(mailer.clone(), email).await;
1202 Ok(())
1203 }
1204
1205 pub async fn simulate_verification(&self) -> Result<(), AuthError> {
1208 let token = random_token();
1209 self.find_verification(&token).await?;
1210 Ok(())
1211 }
1212
1213 pub async fn send_verification_email(
1216 &self,
1217 user: &UserView,
1218 callback_url: Option<&str>,
1219 ) -> Result<(), AuthError> {
1220 let ttl = self.ctx.config().email_verification.ttl;
1221 let token = self
1222 .create_user_verification("email-verification", user, ttl)
1223 .await?;
1224 let mut url = format!(
1225 "{}/verify-email?token={token}",
1226 self.ctx.config().auth_url()
1227 );
1228 if let Some(callback) = callback_url {
1229 url.push_str(&format!("&callbackURL={}", url_encode(callback)));
1230 }
1231 self.send_email_in_background(AuthEmail::VerifyEmail(VerifyEmail {
1232 to: user.email.clone(),
1233 name: user.name.clone(),
1234 url,
1235 token,
1236 }))
1237 .await
1238 }
1239}