1use std::borrow::Cow;
5
6use http::StatusCode;
7use time::{Duration, OffsetDateTime};
8
9use crate::adapter::{Adapter, DbError, Transaction};
10use crate::crypto::{Hash, random_token};
11use crate::endpoint::{Ctx, Gate, SignInAttempt};
12use crate::error::{AuthError, codes};
13use crate::events::{
14 AccountLinked, EmailVerified, SessionCreated, SessionRevoked, UserClaimed, UserCreated,
15};
16use crate::mail::{AuthEmail, VerifyEmail};
17use crate::model::Model;
18use crate::models::{Account, Session, User, Verification};
19use crate::session::{
20 SESSION_DATA, SessionView, UserView, clear_session_cookies, set_session_cookies,
21};
22use crate::value::{ColumnValue, Id, Value};
23
24#[derive(Clone, Debug, Default)]
26pub struct NewUser {
27 pub email: String,
28 pub name: String,
29 pub image: Option<String>,
30 pub email_verified: bool,
31 pub extra: Vec<(&'static str, Value)>,
33}
34
35#[derive(Clone, Debug, Default)]
37pub struct NewAccount {
38 pub provider_id: String,
39 pub account_id: Option<String>,
41 pub password_hash: Option<String>,
42 pub access_token: Option<String>,
44 pub refresh_token: Option<String>,
46 pub id_token: Option<String>,
47 pub access_token_expires_at: Option<OffsetDateTime>,
48 pub refresh_token_expires_at: Option<OffsetDateTime>,
49 pub scope: Option<String>,
50}
51
52impl NewAccount {
53 pub fn credential(password_hash: String) -> Self {
54 Self {
55 provider_id: Account::CREDENTIAL.into(),
56 password_hash: Some(password_hash),
57 ..Self::default()
58 }
59 }
60
61 pub fn oauth(provider_id: impl Into<String>, account_id: impl Into<String>) -> Self {
62 Self {
63 provider_id: provider_id.into(),
64 account_id: Some(account_id.into()),
65 ..Self::default()
66 }
67 }
68}
69
70#[derive(Clone, Debug)]
71pub enum SignInResult {
72 SignedIn(Box<SessionView>),
73 Challenge(serde_json::Value),
75}
76
77fn user_exists(err: DbError) -> AuthError {
78 match err {
79 DbError::UniqueViolation { ref table, .. } if table == User::TABLE => AuthError::new(
80 StatusCode::UNPROCESSABLE_ENTITY,
81 codes::USER_ALREADY_EXISTS_USE_ANOTHER_EMAIL,
82 "user already exists, use another email",
83 ),
84 other => other.into(),
85 }
86}
87
88pub(crate) fn url_encode(value: &str) -> String {
89 url::form_urlencoded::byte_serialize(value.as_bytes()).collect()
90}
91
92pub struct Internal<'a, D, A> {
93 ctx: &'a Ctx<D, A>,
94}
95
96impl<'a, D: Adapter, A> Internal<'a, D, A> {
97 pub(crate) fn new(ctx: &'a Ctx<D, A>) -> Self {
98 Self { ctx }
99 }
100
101 pub async fn find_user_by_email(&self, email: &str) -> Result<Option<UserView>, AuthError> {
102 let row = self
103 .ctx
104 .db()
105 .find::<User>(User::EMAIL.eq(email.trim().to_lowercase()))
106 .one_row()
107 .await?;
108 row.map(UserView::from_row)
109 .transpose()
110 .map_err(AuthError::internal)
111 }
112
113 pub async fn find_user_by_id(&self, id: &Id) -> Result<Option<UserView>, AuthError> {
114 let row = self
115 .ctx
116 .db()
117 .find::<User>(User::ID.eq(id))
118 .one_row()
119 .await?;
120 row.map(UserView::from_row)
121 .transpose()
122 .map_err(AuthError::internal)
123 }
124
125 fn account_values(
126 &self,
127 user_id: &Id,
128 account: NewAccount,
129 ) -> Result<Vec<(&'static str, Value)>, AuthError> {
130 let keys = self.ctx.keys();
131 let seal = |t: Option<String>| t.map(|t| keys.encrypt(t.as_bytes()));
132 Ok(vec![
133 ("id", self.ctx.new_id()?.into_value()),
134 ("user_id", user_id.clone().into_value()),
135 ("provider_id", account.provider_id.into_value()),
136 (
137 "account_id",
138 account
139 .account_id
140 .unwrap_or_else(|| user_id.to_string())
141 .into_value(),
142 ),
143 ("password_hash", account.password_hash.into_value()),
144 ("access_token", seal(account.access_token).into_value()),
145 ("refresh_token", seal(account.refresh_token).into_value()),
146 ("id_token", account.id_token.into_value()),
147 (
148 "access_token_expires_at",
149 account.access_token_expires_at.into_value(),
150 ),
151 (
152 "refresh_token_expires_at",
153 account.refresh_token_expires_at.into_value(),
154 ),
155 ("scope", account.scope.into_value()),
156 ])
157 }
158
159 pub async fn create_user(
162 &self,
163 user: NewUser,
164 account: Option<NewAccount>,
165 ) -> Result<UserView, AuthError> {
166 let id = self.ctx.new_id()?;
167 let mut values = vec![
168 ("id", id.clone().into_value()),
169 ("email", user.email.trim().to_lowercase().into_value()),
170 ("email_verified", user.email_verified.into_value()),
171 ("name", user.name.into_value()),
172 ("image", user.image.into_value()),
173 ];
174 values.extend(user.extra);
175 let account = account
176 .map(|account| self.account_values(&id, account))
177 .transpose()?;
178 let tx = self.ctx.adapter().begin().await?;
179 let db = self.ctx.db_on(&tx);
180 let row = db.insert_row::<User>(values).await.map_err(user_exists)?;
181 if let Some(account) = account {
182 db.insert_row::<Account>(account).await?;
183 }
184 tx.commit().await?;
185 let view = UserView::from_row(row).map_err(AuthError::internal)?;
186 self.ctx.emit(UserCreated {
187 user_id: view.id.clone(),
188 email: view.email.clone(),
189 });
190 Ok(view)
191 }
192
193 pub async fn link_account(
194 &self,
195 user_id: &Id,
196 account: NewAccount,
197 ) -> Result<Account, AuthError> {
198 let provider_id = account.provider_id.clone();
199 let row = self
200 .ctx
201 .db()
202 .insert_row::<Account>(self.account_values(user_id, account)?)
203 .await?;
204 self.ctx.emit(AccountLinked {
205 user_id: user_id.clone(),
206 provider_id,
207 });
208 Account::decode(&row).map_err(AuthError::internal)
209 }
210
211 pub async fn find_account(
212 &self,
213 provider_id: &str,
214 account_id: &str,
215 ) -> Result<Option<Account>, AuthError> {
216 let filter = Account::PROVIDER_ID
217 .eq(provider_id)
218 .and(Account::ACCOUNT_ID.eq(account_id));
219 Ok(self.ctx.db().find::<Account>(filter).one().await?)
220 }
221
222 pub async fn credential_account(&self, user_id: &Id) -> Result<Option<Account>, AuthError> {
223 let filter = Account::USER_ID
224 .eq(user_id)
225 .and(Account::PROVIDER_ID.eq(Account::CREDENTIAL));
226 Ok(self.ctx.db().find::<Account>(filter).one().await?)
227 }
228
229 pub fn validate_new_password(&self, password: &str) -> Result<(), AuthError> {
231 let Some(config) = &self.ctx.config().email_password else {
232 return Ok(());
233 };
234 let length = password.chars().count();
235 if length < config.min_password_length {
236 return Err(AuthError::bad_request(
237 codes::PASSWORD_TOO_SHORT,
238 "password is too short",
239 ));
240 }
241 if length > config.max_password_length {
242 return Err(AuthError::bad_request(
243 codes::PASSWORD_TOO_LONG,
244 "password is too long",
245 ));
246 }
247 if config
248 .password_policy
249 .as_ref()
250 .is_some_and(|policy| !policy(password))
251 {
252 return Err(AuthError::bad_request(
253 codes::PASSWORD_TOO_WEAK,
254 "password is too weak",
255 ));
256 }
257 Ok(())
258 }
259
260 pub async fn set_password(&self, user_id: &Id, password: &str) -> Result<(), AuthError> {
262 self.validate_new_password(password)?;
263 let hash = self
264 .ctx
265 .passwords()
266 .hash(password)
267 .await
268 .map_err(AuthError::internal)?;
269 let updated = self
270 .ctx
271 .db()
272 .update::<Account>(
273 Account::USER_ID
274 .eq(user_id)
275 .and(Account::PROVIDER_ID.eq(Account::CREDENTIAL)),
276 )
277 .set(Account::PASSWORD_HASH, Some(hash.clone()))
278 .exec()
279 .await?;
280 if updated == 0 {
281 self.link_account(user_id, NewAccount::credential(hash))
282 .await?;
283 }
284 Ok(())
285 }
286
287 pub async fn create_session(
292 &self,
293 user_id: &Id,
294 remember_me: bool,
295 ) -> Result<SessionView, AuthError> {
296 let now = self.ctx.now();
297 let token = random_token();
298 let session = Session {
299 id: self.ctx.new_id()?,
300 token_hash: Hash::sha256(&token),
301 user_id: user_id.clone(),
302 expires_at: now + self.ctx.config().session.expires_in,
303 ip_address: self.ctx.ip().map(str::to_owned),
304 user_agent: self
305 .ctx
306 .user_agent()
307 .map(|ua| ua.chars().take(512).collect()),
308 created_at: now,
309 updated_at: now,
310 };
311 let row = self
312 .ctx
313 .db()
314 .insert_row::<Session>(session.encode())
315 .await?;
316 let user = self
317 .find_user_by_id(user_id)
318 .await?
319 .ok_or_else(|| AuthError::internal("session for a missing user"))?;
320 let config = self.ctx.config();
321 set_session_cookies(
322 config,
323 self.ctx.keys(),
324 &self.ctx.effects,
325 &token,
326 remember_me,
327 );
328 self.ctx.set_cookie(crate::cookies::SetCookie::delete(
329 config.cookie_name(SESSION_DATA),
330 ));
331 self.ctx.emit(SessionCreated {
332 session_id: session.id.clone(),
333 user_id: user_id.clone(),
334 });
335 let view = SessionView {
336 session,
337 row,
338 user,
339 token: Some(token),
340 ephemeral: false,
341 };
342 for hook in &self.ctx.shared.session_hooks {
343 hook(self.ctx.retype(), view.clone()).await?;
344 }
345 Ok(view)
346 }
347
348 pub async fn find_session_by_token(
351 &self,
352 token: &str,
353 ) -> Result<Option<SessionView>, AuthError> {
354 crate::session::by_token(&self.ctx.shared, self.ctx.adapter(), token).await
355 }
356
357 pub async fn ephemeral_session(&self, user_id: &Id) -> Result<Option<SessionView>, AuthError> {
362 crate::session::for_user(
363 &self.ctx.shared,
364 self.ctx.within.as_ref(),
365 &self.ctx.request,
366 &self.ctx.effects,
367 user_id,
368 )
369 .await
370 }
371
372 pub fn set_session_cookies(&self, token: &str, remember_me: bool) {
376 let config = self.ctx.config();
377 set_session_cookies(
378 config,
379 self.ctx.keys(),
380 &self.ctx.effects,
381 token,
382 remember_me,
383 );
384 self.ctx.set_cookie(crate::cookies::SetCookie::delete(
385 config.cookie_name(SESSION_DATA),
386 ));
387 }
388
389 pub async fn sign_in(
392 &self,
393 user: UserView,
394 method: impl Into<Cow<'static, str>>,
395 remember_me: bool,
396 ) -> Result<SignInResult, AuthError> {
397 self.run_gates(user, method.into(), remember_me, None).await
398 }
399
400 pub async fn complete_sign_in(
415 &self,
416 challenger: &str,
417 user: UserView,
418 method: impl Into<Cow<'static, str>>,
419 remember_me: bool,
420 ) -> Result<SignInResult, AuthError> {
421 if !self
422 .ctx
423 .shared
424 .gates
425 .iter()
426 .any(|gate| gate.owner == challenger)
427 {
428 return Err(AuthError::internal(format!(
429 "complete_sign_in: no sign-in gate belongs to `{challenger}`"
430 )));
431 }
432 self.run_gates(user, method.into(), remember_me, Some(challenger))
433 .await
434 }
435
436 async fn run_gates(
437 &self,
438 user: UserView,
439 method: Cow<'static, str>,
440 remember_me: bool,
441 skip: Option<&str>,
442 ) -> Result<SignInResult, AuthError> {
443 let attempt = SignInAttempt {
444 user: user.clone(),
445 method,
446 remember_me,
447 };
448 for owned in &self.ctx.shared.gates {
449 if skip == Some(owned.owner) {
450 continue;
451 }
452 match (owned.gate)(self.ctx.retype(), attempt.clone()).await? {
453 Gate::Allow => {}
454 Gate::Deny(err) => return Err(err),
455 Gate::Challenge(body) => return Ok(SignInResult::Challenge(body)),
456 }
457 }
458 Ok(SignInResult::SignedIn(Box::new(
459 self.create_session(&user.id, remember_me).await?,
460 )))
461 }
462
463 pub async fn claim_unverified_user(&self, user: UserView) -> Result<UserView, AuthError> {
470 if user.email_verified {
471 return Ok(user);
472 }
473 self.ctx
474 .db()
475 .delete::<Account>(Account::USER_ID.eq(&user.id))
476 .await?;
477 self.revoke_user_sessions(&user.id, None).await?;
478 self.ctx
479 .db()
480 .update::<User>(User::ID.eq(&user.id))
481 .set(User::EMAIL_VERIFIED, true)
482 .exec()
483 .await?;
484 self.ctx.emit(EmailVerified {
485 user_id: user.id.clone(),
486 });
487 self.ctx.emit(UserClaimed {
488 user_id: user.id.clone(),
489 });
490 self.find_user_by_id(&user.id)
491 .await?
492 .ok_or_else(|| AuthError::internal("user deleted while claiming it"))
493 }
494
495 pub async fn revoke_session(&self, user_id: &Id, session_id: &Id) -> Result<bool, AuthError> {
496 let deleted = self
497 .ctx
498 .db()
499 .delete::<Session>(Session::ID.eq(session_id).and(Session::USER_ID.eq(user_id)))
500 .await?;
501 if deleted > 0 {
502 self.ctx.emit(SessionRevoked {
503 user_id: user_id.clone(),
504 session_id: Some(session_id.clone()),
505 });
506 }
507 Ok(deleted > 0)
508 }
509
510 pub async fn revoke_user_sessions(
512 &self,
513 user_id: &Id,
514 keep: Option<&Id>,
515 ) -> Result<u64, AuthError> {
516 let mut filter = Session::USER_ID.eq(user_id);
517 if let Some(keep) = keep {
518 filter = filter.and(Session::ID.ne(keep));
519 }
520 let deleted = self.ctx.db().delete::<Session>(filter).await?;
521 if deleted > 0 {
522 self.ctx.emit(SessionRevoked {
523 user_id: user_id.clone(),
524 session_id: None,
525 });
526 }
527 Ok(deleted)
528 }
529
530 pub fn clear_session_cookies(&self) {
531 clear_session_cookies(self.ctx.config(), &self.ctx.effects);
532 }
533
534 pub async fn create_verification(
536 &self,
537 identifier: &str,
538 ttl: Duration,
539 data: Option<String>,
540 ) -> Result<String, AuthError> {
541 let token = random_token();
542 let now = self.ctx.now();
543 let verification = Verification {
544 id: self.ctx.new_id()?,
545 identifier: identifier.to_owned(),
546 value_hash: Hash::sha256(&token),
547 data,
548 expires_at: now + ttl,
549 created_at: now,
550 updated_at: now,
551 };
552 self.ctx.db().insert(&verification).await?;
553 Ok(token)
554 }
555
556 pub async fn store_verification_value(
558 &self,
559 identifier: &str,
560 value: &str,
561 ttl: Duration,
562 data: Option<String>,
563 ) -> Result<(), AuthError> {
564 self.ctx
565 .db()
566 .delete::<Verification>(Verification::IDENTIFIER.eq(identifier))
567 .await?;
568 let now = self.ctx.now();
569 let verification = Verification {
570 id: self.ctx.new_id()?,
571 identifier: identifier.to_owned(),
572 value_hash: Hash::sha256(format!("{identifier}:{value}")),
573 data,
574 expires_at: now + ttl,
575 created_at: now,
576 updated_at: now,
577 };
578 self.ctx.db().insert(&verification).await?;
579 Ok(())
580 }
581
582 pub async fn consume_verification_value(
584 &self,
585 identifier: &str,
586 value: &str,
587 ) -> Result<Option<Verification>, AuthError> {
588 self.consume_hash(Hash::sha256(format!("{identifier}:{value}")))
589 .await
590 }
591
592 pub async fn find_verification(&self, token: &str) -> Result<Option<Verification>, AuthError> {
594 let found = self
595 .ctx
596 .db()
597 .find::<Verification>(Verification::VALUE_HASH.eq(Hash::sha256(token)))
598 .one()
599 .await?;
600 Ok(found.filter(|v| v.expires_at > self.ctx.now()))
601 }
602
603 pub async fn consume_verification(
605 &self,
606 token: &str,
607 ) -> Result<Option<Verification>, AuthError> {
608 self.consume_hash(Hash::sha256(token)).await
609 }
610
611 async fn consume_hash(&self, hash: Hash) -> Result<Option<Verification>, AuthError> {
612 let Some(found) = self
613 .ctx
614 .db()
615 .find::<Verification>(Verification::VALUE_HASH.eq(hash))
616 .one()
617 .await?
618 else {
619 return Ok(None);
620 };
621 let deleted = self
622 .ctx
623 .db()
624 .delete::<Verification>(Verification::ID.eq(&found.id))
625 .await?;
626 Ok((deleted == 1 && found.expires_at > self.ctx.now()).then_some(found))
627 }
628
629 pub fn can_send_email(&self) -> bool {
631 self.ctx.mailer().is_some()
632 }
633
634 pub async fn send_email(&self, email: AuthEmail) -> Result<(), AuthError> {
635 let Some(mailer) = self.ctx.mailer() else {
636 return Err(AuthError::internal(
637 "an email needs sending but no mailer is configured",
638 ));
639 };
640 mailer.send(email).await.map_err(AuthError::internal)
641 }
642
643 pub async fn send_email_in_background(&self, email: AuthEmail) -> Result<(), AuthError> {
647 let Some(mailer) = self.ctx.mailer() else {
648 return Err(AuthError::internal(
649 "an email needs sending but no mailer is configured",
650 ));
651 };
652 crate::mail::send_in_background(mailer.clone(), email).await;
653 Ok(())
654 }
655
656 pub async fn simulate_verification(&self) -> Result<(), AuthError> {
659 let token = random_token();
660 self.find_verification(&token).await?;
661 Ok(())
662 }
663
664 pub async fn send_verification_email(
667 &self,
668 user: &UserView,
669 callback_url: Option<&str>,
670 ) -> Result<(), AuthError> {
671 let ttl = self.ctx.config().email_verification.ttl;
672 let token = self
673 .create_verification(&format!("email-verification:{}", user.id), ttl, None)
674 .await?;
675 let mut url = format!(
676 "{}/verify-email?token={token}",
677 self.ctx.config().auth_url()
678 );
679 if let Some(callback) = callback_url {
680 url.push_str(&format!("&callbackURL={}", url_encode(callback)));
681 }
682 self.send_email_in_background(AuthEmail::VerifyEmail(VerifyEmail {
683 to: user.email.clone(),
684 name: user.name.clone(),
685 url,
686 token,
687 }))
688 .await
689 }
690}