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::config::SessionTokens;
13use crate::crypto::{Hash, random_bytes, random_token};
14use crate::endpoint::{Ctx, Gate, SignInAttempt};
15use crate::error::{AuthError, codes};
16use crate::events::{
17 AccountLinked, EmailVerified, SessionCreated, SessionRevoked, UserClaimed, UserCreated,
18};
19use crate::mail::{AuthEmail, VerifyEmail};
20use crate::model::{Col, Model, OnTable};
21use crate::models::{Account, Session, User, Verification};
22use crate::query::{Db, Where};
23use crate::schema::Schema;
24use crate::session::{
25 DONT_REMEMBER_LIFETIME, SESSION_DATA, SessionView, UserView, clear_session_cookies,
26 set_session_cookies,
27};
28use crate::value::{ColumnValue, Id, Value};
29
30#[derive(Clone, Debug, Default)]
32pub struct NewUser {
33 pub email: String,
34 pub name: String,
35 pub image: Option<String>,
36 pub email_verified: bool,
37 pub extra: Vec<(&'static str, Value)>,
39}
40
41#[derive(Clone, Debug, Default)]
43pub struct NewAccount {
44 pub provider_id: String,
45 pub account_id: Option<String>,
47 pub password_hash: Option<String>,
48 pub access_token: Option<String>,
51 pub refresh_token: Option<String>,
53 pub id_token: Option<String>,
54 pub access_token_expires_at: Option<OffsetDateTime>,
55 pub refresh_token_expires_at: Option<OffsetDateTime>,
56 pub scope: Option<String>,
57}
58
59#[derive(Clone, Debug, Default)]
62pub struct NewSession {
63 expires_at: Option<OffsetDateTime>,
64 values: Vec<(&'static str, Value)>,
65}
66
67impl NewSession {
68 pub fn new() -> Self {
69 Self::default()
70 }
71
72 pub fn expires_at(mut self, expires_at: OffsetDateTime) -> Self {
74 self.expires_at = Some(expires_at);
75 self
76 }
77
78 pub fn set<O: OnTable<Table = Session>, T: ColumnValue>(
80 mut self,
81 column: Col<O, T>,
82 value: impl Into<T>,
83 ) -> Self {
84 self.values.push((column.name(), value.into().into_value()));
85 self
86 }
87}
88
89impl NewAccount {
90 pub fn credential(password_hash: String) -> Self {
91 Self {
92 provider_id: Account::CREDENTIAL.into(),
93 password_hash: Some(password_hash),
94 ..Self::default()
95 }
96 }
97
98 pub fn oauth(provider_id: impl Into<String>, account_id: impl Into<String>) -> Self {
99 Self {
100 provider_id: provider_id.into(),
101 account_id: Some(account_id.into()),
102 ..Self::default()
103 }
104 }
105}
106
107#[derive(Clone, Copy, Debug, PartialEq, Eq)]
109pub enum UserInput {
110 SignUp,
112 Create,
114 Update,
116}
117
118#[derive(Clone, Debug)]
119pub enum SignInResult {
120 SignedIn(Box<SessionView>),
121 Challenge(serde_json::Value),
123}
124
125fn user_exists(err: DbError) -> AuthError {
126 match err {
127 DbError::UniqueViolation { ref table, .. } if table == User::TABLE => AuthError::new(
128 StatusCode::UNPROCESSABLE_ENTITY,
129 codes::USER_ALREADY_EXISTS_USE_ANOTHER_EMAIL,
130 "user already exists, use another email",
131 ),
132 other => other.into(),
133 }
134}
135
136fn account_linked(err: DbError) -> AuthError {
137 match err {
138 DbError::UniqueViolation {
139 ref table,
140 column: None,
141 } if table == Account::TABLE => AuthError::new(
142 StatusCode::CONFLICT,
143 codes::SOCIAL_ACCOUNT_ALREADY_LINKED,
144 "social account already linked",
145 ),
146 other => other.into(),
147 }
148}
149
150const PENDING_VERIFICATION: &str = "pending_verification";
152
153fn new_security_stamp() -> i64 {
155 i64::from_le_bytes(random_bytes::<8>())
156}
157
158pub(crate) fn url_encode(value: &str) -> String {
159 url::form_urlencoded::byte_serialize(value.as_bytes()).collect()
160}
161
162fn claimed_meanwhile() -> AuthError {
165 AuthError::new(
166 StatusCode::UNAUTHORIZED,
167 codes::UNAUTHORIZED,
168 "the account changed meanwhile; sign in again",
169 )
170}
171
172pub struct Claim<'a, D> {
177 user_id: &'a Id,
178 tx: &'a (dyn Any + Send + Sync),
179 schema: &'a Schema,
180 _adapter: PhantomData<fn() -> D>,
181}
182
183impl<'a, D: Adapter> Claim<'a, D> {
184 pub fn user_id(&self) -> &'a Id {
186 self.user_id
187 }
188
189 pub fn db(&self) -> Db<'a, D::Tx> {
191 let tx = self
192 .tx
193 .downcast_ref::<D::Tx>()
194 .expect("a claim runs in its adapter's transaction");
195 Db::new(tx, self.schema)
196 }
197}
198
199impl<D> std::fmt::Debug for Claim<'_, D> {
200 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
201 f.debug_struct("Claim")
202 .field("user_id", self.user_id)
203 .finish_non_exhaustive()
204 }
205}
206
207fn user_verification_identifiers(user_id: &Id) -> [String; 2] {
209 [
210 format!("email-verification:{user_id}"),
211 format!("reset-password:{user_id}"),
212 ]
213}
214
215fn user_binding(user: &UserView) -> String {
218 format!("{}:{}", user.security_stamp(), user.email)
219}
220
221pub struct Internal<'a, D, A> {
222 ctx: &'a Ctx<D, A>,
223}
224
225impl<'a, D: Adapter, A> Internal<'a, D, A> {
226 pub(crate) fn new(ctx: &'a Ctx<D, A>) -> Self {
227 Self { ctx }
228 }
229
230 pub async fn find_user_by_email(&self, email: &str) -> Result<Option<UserView>, AuthError> {
231 let row = self
232 .ctx
233 .db()
234 .find::<User>(User::EMAIL.eq(email.trim().to_lowercase()))
235 .one_row()
236 .await?;
237 row.map(UserView::from_row)
238 .transpose()
239 .map_err(AuthError::internal)
240 }
241
242 pub async fn find_user_by_id(&self, id: &Id) -> Result<Option<UserView>, AuthError> {
243 let row = self
244 .ctx
245 .db()
246 .find::<User>(User::ID.eq(id))
247 .one_row()
248 .await?;
249 row.map(UserView::from_row)
250 .transpose()
251 .map_err(AuthError::internal)
252 }
253
254 fn account_values(
255 &self,
256 user_id: &Id,
257 account: NewAccount,
258 ) -> Result<Vec<(&'static str, Value)>, AuthError> {
259 let seal = |t: Option<String>| t.map(|t| self.ctx.oauth_token_bytes(&t));
260 Ok(vec![
261 ("id", self.ctx.new_id()?.into_value()),
262 ("user_id", user_id.clone().into_value()),
263 ("provider_id", account.provider_id.into_value()),
264 (
265 "account_id",
266 account
267 .account_id
268 .unwrap_or_else(|| user_id.to_string())
269 .into_value(),
270 ),
271 ("password_hash", account.password_hash.into_value()),
272 ("access_token", seal(account.access_token).into_value()),
273 ("refresh_token", seal(account.refresh_token).into_value()),
274 ("id_token", account.id_token.into_value()),
275 (
276 "access_token_expires_at",
277 account.access_token_expires_at.into_value(),
278 ),
279 (
280 "refresh_token_expires_at",
281 account.refresh_token_expires_at.into_value(),
282 ),
283 ("scope", account.scope.into_value()),
284 ])
285 }
286
287 pub async fn create_user(
290 &self,
291 user: NewUser,
292 account: Option<NewAccount>,
293 ) -> Result<UserView, AuthError> {
294 let id = self.ctx.new_id()?;
295 let mut values = vec![
296 ("id", id.clone().into_value()),
297 ("email", user.email.trim().to_lowercase().into_value()),
298 ("email_verified", user.email_verified.into_value()),
299 ("name", user.name.into_value()),
300 ("image", user.image.into_value()),
301 ];
302 values.extend(user.extra);
303 let account = account
304 .map(|account| self.account_values(&id, account))
305 .transpose()?;
306 let tx = self.ctx.adapter().begin().await?;
307 let db = self.ctx.db_on(&tx);
308 let row = db.insert_row::<User>(values).await.map_err(user_exists)?;
309 if let Some(account) = account {
310 db.insert_row::<Account>(account)
311 .await
312 .map_err(account_linked)?;
313 }
314 tx.commit().await?;
315 let view = UserView::from_row(row).map_err(AuthError::internal)?;
316 self.ctx.emit(UserCreated {
317 user_id: view.id.clone(),
318 email: view.email.clone(),
319 });
320 Ok(view)
321 }
322
323 pub async fn link_account(
324 &self,
325 user_id: &Id,
326 account: NewAccount,
327 ) -> Result<Account, AuthError> {
328 let provider_id = account.provider_id.clone();
329 let row = self
330 .ctx
331 .db()
332 .insert_row::<Account>(self.account_values(user_id, account)?)
333 .await
334 .map_err(account_linked)?;
335 self.ctx.emit(AccountLinked {
336 user_id: user_id.clone(),
337 provider_id,
338 });
339 Account::decode(&row).map_err(AuthError::internal)
340 }
341
342 pub async fn link_account_unless_claimed(
348 &self,
349 user: &UserView,
350 account: NewAccount,
351 ) -> Result<Account, AuthError> {
352 let provider_id = account.provider_id.clone();
353 let values = self.account_values(&user.id, account)?;
354 let tx = self.lock_user_unless_claimed(user).await?;
355 let row = self
356 .ctx
357 .db_on(&tx)
358 .insert_row::<Account>(values)
359 .await
360 .map_err(account_linked)?;
361 tx.commit().await?;
362 self.ctx.emit(AccountLinked {
363 user_id: user.id.clone(),
364 provider_id,
365 });
366 Account::decode(&row).map_err(AuthError::internal)
367 }
368
369 pub async fn lock_user_unless_claimed(&self, user: &UserView) -> Result<D::Tx, AuthError> {
381 let tx = self.ctx.adapter().begin().await?;
382 match self
383 .stamp_holds_on(&tx, &user.id, user.security_stamp())
384 .await
385 {
386 Ok(true) => Ok(tx),
387 Ok(false) => {
388 tx.rollback().await?;
389 Err(claimed_meanwhile())
390 }
391 Err(err) => {
392 let _ = tx.rollback().await;
393 Err(err)
394 }
395 }
396 }
397
398 async fn stamp_holds(&self, user_id: &Id, stamp: i64) -> Result<bool, AuthError> {
402 self.stamp_holds_on(self.ctx.adapter(), user_id, stamp)
403 .await
404 }
405
406 async fn stamp_holds_on<Q: Queries>(
409 &self,
410 db: &Q,
411 user_id: &Id,
412 stamp: i64,
413 ) -> Result<bool, AuthError> {
414 let table = self.ctx.schema().expect(User::TABLE);
415 let filter = User::ID
416 .eq(user_id)
417 .and(User::SECURITY_STAMP.eq(stamp))
418 .resolve(table)?;
419 let column = table
420 .position(User::SECURITY_STAMP.name())
421 .ok_or_else(|| AuthError::internal("user.security_stamp missing"))?;
422 let matched = db
423 .update(Update {
424 table,
425 filter,
426 set: vec![(column, Value::Int(stamp))],
427 })
428 .await?;
429 Ok(matched == 1)
430 }
431
432 pub fn accounts_of(&self, user_id: &Id) -> Where<Account> {
437 let filter = Account::USER_ID.eq(user_id);
438 match self.ctx.config().owned_account_providers() {
439 Some(owned) => filter.and(Account::PROVIDER_ID.in_(owned.iter().cloned())),
440 None => filter,
441 }
442 }
443
444 pub async fn refuse_foreign_accounts(&self, user_id: &Id) -> Result<(), AuthError> {
449 if self.ctx.config().owned_account_providers().is_none() {
450 return Ok(());
451 }
452 let db = self.ctx.db();
453 let all = db.count::<Account>(Account::USER_ID.eq(user_id)).await?;
454 let owned = db.count::<Account>(self.accounts_of(user_id)).await?;
455 if all > owned {
456 return Err(AuthError::new(
457 StatusCode::CONFLICT,
458 codes::USER_HAS_FOREIGN_ACCOUNTS,
459 "the user has accounts another app manages; remove them there first",
460 ));
461 }
462 Ok(())
463 }
464
465 pub async fn find_account(
466 &self,
467 provider_id: &str,
468 account_id: &str,
469 ) -> Result<Option<Account>, AuthError> {
470 if !self.ctx.config().owns_account_provider(provider_id) {
471 return Ok(None);
472 }
473 let filter = Account::PROVIDER_ID
474 .eq(provider_id)
475 .and(Account::ACCOUNT_ID.eq(account_id));
476 Ok(self.ctx.db().find::<Account>(filter).one().await?)
477 }
478
479 pub async fn credential_account(&self, user_id: &Id) -> Result<Option<Account>, AuthError> {
480 let filter = Account::USER_ID
481 .eq(user_id)
482 .and(Account::PROVIDER_ID.eq(Account::CREDENTIAL));
483 Ok(self.ctx.db().find::<Account>(filter).one().await?)
484 }
485
486 pub async fn user_fields(
491 &self,
492 extra: &serde_json::Map<String, serde_json::Value>,
493 input: UserInput,
494 ) -> Result<Vec<(&'static str, Value)>, AuthError> {
495 let mut extra = extra.clone();
496 for hook in &self.ctx.shared.user_input_hooks {
497 extra = hook(self.ctx.retype(), extra, input).await?;
498 }
499 crate::routes::user_input_fields(self.ctx, &extra, input != UserInput::Update)
500 }
501
502 pub fn validate_new_password(&self, password: &str) -> Result<(), AuthError> {
504 let Some(config) = &self.ctx.config().email_password else {
505 return Ok(());
506 };
507 let length = password.chars().count();
508 if length < config.min_password_length {
509 return Err(AuthError::bad_request(
510 codes::PASSWORD_TOO_SHORT,
511 "password is too short",
512 ));
513 }
514 if length > config.max_password_length {
515 return Err(AuthError::bad_request(
516 codes::PASSWORD_TOO_LONG,
517 "password is too long",
518 ));
519 }
520 if config
521 .password_policy
522 .as_ref()
523 .is_some_and(|policy| !policy(password))
524 {
525 return Err(AuthError::bad_request(
526 codes::PASSWORD_TOO_WEAK,
527 "password is too weak",
528 ));
529 }
530 Ok(())
531 }
532
533 pub async fn set_password(&self, user: &UserView, password: &str) -> Result<(), AuthError> {
539 self.validate_new_password(password)?;
540 let hash = self
541 .ctx
542 .passwords()
543 .hash(password)
544 .await
545 .map_err(AuthError::internal)?;
546 let credential = || {
547 Account::USER_ID
548 .eq(&user.id)
549 .and(Account::PROVIDER_ID.eq(Account::CREDENTIAL))
550 };
551 let tx = self.lock_user_unless_claimed(user).await?;
552 let db = self.ctx.db_on(&tx);
553 if db.find::<Account>(credential()).one().await?.is_some() {
554 db.update::<Account>(credential())
555 .set(Account::PASSWORD_HASH, Some(hash))
556 .exec()
557 .await?;
558 tx.commit().await?;
559 return Ok(());
560 }
561 db.insert_row::<Account>(self.account_values(&user.id, NewAccount::credential(hash))?)
562 .await
563 .map_err(account_linked)?;
564 tx.commit().await?;
565 self.ctx.emit(AccountLinked {
566 user_id: user.id.clone(),
567 provider_id: Account::CREDENTIAL.into(),
568 });
569 Ok(())
570 }
571
572 pub async fn create_session(
581 &self,
582 user_id: &Id,
583 remember_me: bool,
584 ) -> Result<SessionView, AuthError> {
585 self.create_session_with(user_id, remember_me, NewSession::default())
586 .await
587 }
588
589 pub async fn create_session_unless_claimed(
594 &self,
595 user: &UserView,
596 remember_me: bool,
597 ) -> Result<SessionView, AuthError> {
598 self.insert_session(
599 &user.id,
600 Some(user.security_stamp()),
601 remember_me,
602 NewSession::default(),
603 )
604 .await
605 }
606
607 pub async fn create_session_with(
610 &self,
611 user_id: &Id,
612 remember_me: bool,
613 options: NewSession,
614 ) -> Result<SessionView, AuthError> {
615 self.insert_session(user_id, None, remember_me, options)
616 .await
617 }
618
619 async fn insert_session(
623 &self,
624 user_id: &Id,
625 stamp: Option<i64>,
626 remember_me: bool,
627 options: NewSession,
628 ) -> Result<SessionView, AuthError> {
629 let now = self.ctx.now();
630 let token = random_token();
631 let lifetime = match remember_me {
632 true => self.ctx.config().session.expires_in,
633 false => self
634 .ctx
635 .config()
636 .session
637 .expires_in
638 .min(DONT_REMEMBER_LIFETIME),
639 };
640 let session = Session {
641 id: self.ctx.new_id()?,
642 token_hash: Hash::sha256(&token),
643 user_id: user_id.clone(),
644 expires_at: options.expires_at.unwrap_or(now + lifetime),
645 ip_address: self.ctx.ip().map(str::to_owned),
646 user_agent: self
647 .ctx
648 .user_agent()
649 .map(|ua| ua.chars().take(512).collect()),
650 created_at: now,
651 updated_at: now,
652 };
653 let mut values = session.encode();
654 if self.ctx.config().session_tokens() == SessionTokens::Raw {
655 values.retain(|(column, _)| *column != Session::TOKEN_HASH.name());
656 values.push(Session::TOKEN.value(token.clone()));
657 }
658 values.extend(options.values);
659 let row = self.ctx.db().insert_row::<Session>(values).await?;
660 let session = Session::decode(&row).map_err(AuthError::internal)?;
661 if let Some(stamp) = stamp
662 && !self.stamp_holds(user_id, stamp).await?
663 {
664 self.ctx
665 .db()
666 .delete::<Session>(Session::ID.eq(&session.id))
667 .await?;
668 return Err(claimed_meanwhile());
669 }
670 let user = self
671 .find_user_by_id(user_id)
672 .await?
673 .ok_or_else(|| AuthError::internal("session for a missing user"))?;
674 let view = SessionView {
675 session,
676 row,
677 user,
678 token: Some(token.clone()),
679 ephemeral: false,
680 from_cache: false,
681 };
682 let config = self.ctx.config();
683 let before = self.ctx.effects.lock().unwrap().cookies.clone();
684 set_session_cookies(
685 config,
686 self.ctx.keys(),
687 &self.ctx.effects,
688 &token,
689 remember_me,
690 );
691 for hook in &self.ctx.shared.session_hooks {
692 if let Err(err) = hook(self.ctx.retype(), view.clone()).await {
693 self.ctx.effects.lock().unwrap().cookies = before;
694 self.ctx
695 .db()
696 .delete::<Session>(Session::ID.eq(&view.session.id))
697 .await?;
698 return Err(err);
699 }
700 }
701 self.ctx.set_cookie(crate::cookies::SetCookie::delete(
702 config.cookie_name(SESSION_DATA),
703 ));
704 self.ctx.emit(SessionCreated {
705 session_id: view.session.id.clone(),
706 user_id: user_id.clone(),
707 });
708 Ok(view)
709 }
710
711 pub async fn find_session_by_token(
714 &self,
715 token: &str,
716 ) -> Result<Option<SessionView>, AuthError> {
717 crate::session::by_token(&self.ctx.shared, self.ctx.adapter(), token).await
718 }
719
720 pub async fn ephemeral_session(&self, user_id: &Id) -> Result<Option<SessionView>, AuthError> {
725 crate::session::for_user(
726 &self.ctx.shared,
727 self.ctx.within.as_ref(),
728 &self.ctx.request,
729 &self.ctx.effects,
730 user_id,
731 )
732 .await
733 }
734
735 pub fn set_session_cookies(&self, token: &str, remember_me: bool) {
739 let config = self.ctx.config();
740 set_session_cookies(
741 config,
742 self.ctx.keys(),
743 &self.ctx.effects,
744 token,
745 remember_me,
746 );
747 self.ctx.set_cookie(crate::cookies::SetCookie::delete(
748 config.cookie_name(SESSION_DATA),
749 ));
750 }
751
752 pub async fn sign_in(
760 &self,
761 user: UserView,
762 method: impl Into<Cow<'static, str>>,
763 remember_me: bool,
764 ) -> Result<SignInResult, AuthError> {
765 self.run_gates(user, method.into(), remember_me, None).await
766 }
767
768 pub async fn complete_sign_in(
783 &self,
784 challenger: &str,
785 user: UserView,
786 method: impl Into<Cow<'static, str>>,
787 remember_me: bool,
788 ) -> Result<SignInResult, AuthError> {
789 if !self
790 .ctx
791 .shared
792 .gates
793 .iter()
794 .any(|gate| gate.owner == challenger)
795 {
796 return Err(AuthError::internal(format!(
797 "complete_sign_in: no sign-in gate belongs to `{challenger}`"
798 )));
799 }
800 self.run_gates(user, method.into(), remember_me, Some(challenger))
801 .await
802 }
803
804 async fn run_gates(
805 &self,
806 user: UserView,
807 method: Cow<'static, str>,
808 remember_me: bool,
809 skip: Option<&str>,
810 ) -> Result<SignInResult, AuthError> {
811 let attempt = SignInAttempt {
812 user: user.clone(),
813 method,
814 remember_me,
815 };
816 for owned in &self.ctx.shared.gates {
817 if skip == Some(owned.owner) {
818 continue;
819 }
820 match (owned.gate)(self.ctx.retype(), attempt.clone()).await? {
821 Gate::Allow => {}
822 Gate::Deny(err) => return Err(err),
823 Gate::Challenge(body) => return Ok(SignInResult::Challenge(body)),
824 }
825 }
826 Ok(SignInResult::SignedIn(Box::new(
827 self.insert_session(
828 &user.id,
829 Some(user.security_stamp()),
830 remember_me,
831 NewSession::default(),
832 )
833 .await?,
834 )))
835 }
836
837 pub async fn claim_user(
855 &self,
856 user: UserView,
857 link: Option<NewAccount>,
858 ) -> Result<UserView, AuthError> {
859 let linked_provider = link.as_ref().map(|account| account.provider_id.clone());
860 let link = link
861 .map(|account| self.account_values(&user.id, account))
862 .transpose()?;
863 if !user.email_verified {
864 let tx = self.ctx.adapter().begin().await?;
865 match self.claim_in(&tx, &user.id, link.clone()).await {
866 Ok(Some(revoked)) => {
867 tx.commit().await?;
868 if revoked > 0 {
869 self.ctx.emit(SessionRevoked {
870 user_id: user.id.clone(),
871 session_id: None,
872 });
873 }
874 self.ctx.emit(EmailVerified {
875 user_id: user.id.clone(),
876 });
877 self.ctx.emit(UserClaimed {
878 user_id: user.id.clone(),
879 });
880 if let Some(provider_id) = linked_provider {
881 self.ctx.emit(AccountLinked {
882 user_id: user.id.clone(),
883 provider_id,
884 });
885 }
886 return self
887 .find_user_by_id(&user.id)
888 .await?
889 .ok_or_else(|| AuthError::internal("user deleted while claiming it"));
890 }
891 Ok(None) => tx.rollback().await?,
893 Err(err) => {
894 let _ = tx.rollback().await;
895 return Err(err);
896 }
897 }
898 }
899 if let Some(values) = link {
900 self.ctx
901 .db()
902 .insert_row::<Account>(values)
903 .await
904 .map_err(account_linked)?;
905 if let Some(provider_id) = linked_provider {
906 self.ctx.emit(AccountLinked {
907 user_id: user.id.clone(),
908 provider_id,
909 });
910 }
911 }
912 self.find_user_by_id(&user.id)
913 .await?
914 .ok_or_else(|| AuthError::internal("user deleted while claiming it"))
915 }
916
917 #[deprecated(since = "0.6.0", note = "use `claim_user(user, None)`")]
919 pub async fn claim_unverified_user(&self, user: UserView) -> Result<UserView, AuthError> {
920 self.claim_user(user, None).await
921 }
922
923 async fn claim_in(
927 &self,
928 tx: &D::Tx,
929 user_id: &Id,
930 link: Option<Vec<(&'static str, Value)>>,
931 ) -> Result<Option<u64>, AuthError> {
932 let db = self.ctx.db_on(tx);
933 let claimed = db
934 .update::<User>(User::ID.eq(user_id).and(User::EMAIL_VERIFIED.eq(false)))
935 .set(User::SECURITY_STAMP, new_security_stamp())
936 .set(User::EMAIL_VERIFIED, true)
937 .exec()
938 .await?;
939 if claimed == 0 {
940 return Ok(None);
941 }
942 db.delete::<Account>(self.accounts_of(user_id)).await?;
943 let revoked = db.delete::<Session>(Session::USER_ID.eq(user_id)).await?;
944 db.delete::<Verification>(
945 Verification::IDENTIFIER.in_(user_verification_identifiers(user_id)),
946 )
947 .await?;
948 for cleanup in &self.ctx.shared.claim_hooks {
949 cleanup(Claim {
950 user_id,
951 tx,
952 schema: self.ctx.schema(),
953 _adapter: PhantomData,
954 })
955 .await?;
956 }
957 if let Some(values) = link {
958 db.insert_row::<Account>(values)
959 .await
960 .map_err(account_linked)?;
961 }
962 Ok(Some(revoked))
963 }
964
965 pub async fn prove_email(&self, user: UserView) -> Result<UserView, AuthError> {
973 if user.email_verified {
974 return Ok(user);
975 }
976 if !self.holds_credentials_of(&user).await? {
977 return self.claim_user(user, None).await;
978 }
979 self.ctx
980 .db()
981 .update::<User>(User::ID.eq(&user.id))
982 .set(User::EMAIL_VERIFIED, true)
983 .exec()
984 .await?;
985 self.ctx.emit(EmailVerified {
986 user_id: user.id.clone(),
987 });
988 self.find_user_by_id(&user.id)
989 .await?
990 .ok_or_else(|| AuthError::internal("user deleted while verifying it"))
991 }
992
993 async fn holds_credentials_of(&self, user: &UserView) -> Result<bool, AuthError> {
1002 let binding = self.ctx.signed_token_cookie(PENDING_VERIFICATION);
1003 if binding.is_some() {
1004 self.ctx.delete_cookie(PENDING_VERIFICATION);
1005 }
1006 if binding.as_deref() == Some(user_binding(user).as_str()) {
1007 return Ok(true);
1008 }
1009 let Some(token) = self.ctx.signed_token_cookie(crate::session::SESSION_TOKEN) else {
1010 return Ok(false);
1011 };
1012 Ok(self
1013 .find_session_by_token(&token)
1014 .await?
1015 .is_some_and(|session| !session.ephemeral && session.user.id == user.id))
1016 }
1017
1018 pub fn remember_password_holder(&self, user: &UserView) {
1022 self.ctx.set_signed_cookie(
1023 PENDING_VERIFICATION,
1024 &user_binding(user),
1025 Some(self.ctx.config().email_verification.ttl),
1026 );
1027 }
1028
1029 pub async fn create_user_verification(
1034 &self,
1035 purpose: &str,
1036 user: &UserView,
1037 ttl: Duration,
1038 ) -> Result<String, AuthError> {
1039 self.create_verification(
1040 &format!("{purpose}:{}", user.id),
1041 ttl,
1042 Some(user_binding(user)),
1043 )
1044 .await
1045 }
1046
1047 pub async fn consume_user_verification(
1051 &self,
1052 purpose: &str,
1053 token: &str,
1054 ) -> Result<Option<UserView>, AuthError> {
1055 let Some(verification) = self.consume_verification(token).await? else {
1056 return Ok(None);
1057 };
1058 let Some(user_id) = verification
1059 .identifier
1060 .strip_prefix(purpose)
1061 .and_then(|rest| rest.strip_prefix(':'))
1062 else {
1063 return Ok(None);
1064 };
1065 let Some(user) = self.find_user_by_id(&Id::from(user_id)).await? else {
1066 return Ok(None);
1067 };
1068 let bound = verification.data.as_deref() == Some(user_binding(&user).as_str());
1069 Ok(bound.then_some(user))
1070 }
1071
1072 pub async fn revoke_session(&self, user_id: &Id, session_id: &Id) -> Result<bool, AuthError> {
1073 let deleted = self
1074 .ctx
1075 .db()
1076 .delete::<Session>(Session::ID.eq(session_id).and(Session::USER_ID.eq(user_id)))
1077 .await?;
1078 if deleted > 0 {
1079 self.ctx.emit(SessionRevoked {
1080 user_id: user_id.clone(),
1081 session_id: Some(session_id.clone()),
1082 });
1083 }
1084 Ok(deleted > 0)
1085 }
1086
1087 pub async fn revoke_user_sessions(
1089 &self,
1090 user_id: &Id,
1091 keep: Option<&Id>,
1092 ) -> Result<u64, AuthError> {
1093 let mut filter = Session::USER_ID.eq(user_id);
1094 if let Some(keep) = keep {
1095 filter = filter.and(Session::ID.ne(keep));
1096 }
1097 let deleted = self.ctx.db().delete::<Session>(filter).await?;
1098 if deleted > 0 {
1099 self.ctx.emit(SessionRevoked {
1100 user_id: user_id.clone(),
1101 session_id: None,
1102 });
1103 }
1104 Ok(deleted)
1105 }
1106
1107 pub fn clear_session_cookies(&self) {
1108 clear_session_cookies(self.ctx.config(), &self.ctx.effects);
1109 }
1110
1111 async fn purge_expired_verifications(&self) -> Result<(), AuthError> {
1115 self.ctx
1116 .db()
1117 .delete::<Verification>(Verification::EXPIRES_AT.lt(self.ctx.now()))
1118 .await?;
1119 Ok(())
1120 }
1121
1122 pub async fn create_verification(
1124 &self,
1125 identifier: &str,
1126 ttl: Duration,
1127 data: Option<String>,
1128 ) -> Result<String, AuthError> {
1129 self.purge_expired_verifications().await?;
1130 let token = random_token();
1131 let now = self.ctx.now();
1132 let verification = Verification {
1133 id: self.ctx.new_id()?,
1134 identifier: identifier.to_owned(),
1135 value_hash: Hash::sha256(&token),
1136 data,
1137 expires_at: now + ttl,
1138 created_at: now,
1139 updated_at: now,
1140 };
1141 self.ctx.db().insert(&verification).await?;
1142 Ok(token)
1143 }
1144
1145 pub async fn store_verification_value(
1147 &self,
1148 identifier: &str,
1149 value: &str,
1150 ttl: Duration,
1151 data: Option<String>,
1152 ) -> Result<(), AuthError> {
1153 self.purge_expired_verifications().await?;
1154 self.ctx
1155 .db()
1156 .delete::<Verification>(Verification::IDENTIFIER.eq(identifier))
1157 .await?;
1158 let now = self.ctx.now();
1159 let verification = Verification {
1160 id: self.ctx.new_id()?,
1161 identifier: identifier.to_owned(),
1162 value_hash: Hash::sha256(format!("{identifier}:{value}")),
1163 data,
1164 expires_at: now + ttl,
1165 created_at: now,
1166 updated_at: now,
1167 };
1168 self.ctx.db().insert(&verification).await?;
1169 Ok(())
1170 }
1171
1172 pub async fn consume_verification_value(
1174 &self,
1175 identifier: &str,
1176 value: &str,
1177 ) -> Result<Option<Verification>, AuthError> {
1178 self.consume_hash(Hash::sha256(format!("{identifier}:{value}")))
1179 .await
1180 }
1181
1182 pub async fn find_verification(&self, token: &str) -> Result<Option<Verification>, AuthError> {
1184 let found = self
1185 .ctx
1186 .db()
1187 .find::<Verification>(Verification::VALUE_HASH.eq(Hash::sha256(token)))
1188 .one()
1189 .await?;
1190 Ok(found.filter(|v| v.expires_at > self.ctx.now()))
1191 }
1192
1193 pub async fn consume_verification(
1195 &self,
1196 token: &str,
1197 ) -> Result<Option<Verification>, AuthError> {
1198 self.consume_hash(Hash::sha256(token)).await
1199 }
1200
1201 async fn consume_hash(&self, hash: Hash) -> Result<Option<Verification>, AuthError> {
1202 let Some(found) = self
1203 .ctx
1204 .db()
1205 .find::<Verification>(Verification::VALUE_HASH.eq(hash))
1206 .one()
1207 .await?
1208 else {
1209 return Ok(None);
1210 };
1211 let deleted = self
1212 .ctx
1213 .db()
1214 .delete::<Verification>(Verification::ID.eq(&found.id))
1215 .await?;
1216 Ok((deleted == 1 && found.expires_at > self.ctx.now()).then_some(found))
1217 }
1218
1219 pub fn can_send_email(&self) -> bool {
1221 self.ctx.mailer().is_some()
1222 }
1223
1224 pub async fn send_email(&self, email: AuthEmail) -> Result<(), AuthError> {
1225 let Some(mailer) = self.ctx.mailer() else {
1226 return Err(AuthError::internal(
1227 "an email needs sending but no mailer is configured",
1228 ));
1229 };
1230 mailer.send(email).await.map_err(AuthError::internal)
1231 }
1232
1233 pub async fn send_email_in_background(&self, email: AuthEmail) -> Result<(), AuthError> {
1237 let Some(mailer) = self.ctx.mailer() else {
1238 return Err(AuthError::internal(
1239 "an email needs sending but no mailer is configured",
1240 ));
1241 };
1242 crate::mail::send_in_background(mailer.clone(), email).await;
1243 Ok(())
1244 }
1245
1246 pub async fn simulate_verification(&self) -> Result<(), AuthError> {
1249 let token = random_token();
1250 self.find_verification(&token).await?;
1251 Ok(())
1252 }
1253
1254 pub async fn send_verification_email(
1257 &self,
1258 user: &UserView,
1259 callback_url: Option<&str>,
1260 ) -> Result<(), AuthError> {
1261 let ttl = self.ctx.config().email_verification.ttl;
1262 let token = self
1263 .create_user_verification("email-verification", user, ttl)
1264 .await?;
1265 let mut url = format!(
1266 "{}/verify-email?token={token}",
1267 self.ctx.config().auth_url()
1268 );
1269 if let Some(callback) = callback_url {
1270 url.push_str(&format!("&callbackURL={}", url_encode(callback)));
1271 }
1272 self.send_email_in_background(AuthEmail::VerifyEmail(VerifyEmail {
1273 to: user.email.clone(),
1274 name: user.name.clone(),
1275 url,
1276 token,
1277 }))
1278 .await
1279 }
1280}