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