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 Ok(SessionView {
334 session,
335 row,
336 user,
337 token: Some(token),
338 ephemeral: false,
339 })
340 }
341
342 pub async fn sign_in(
345 &self,
346 user: UserView,
347 method: impl Into<Cow<'static, str>>,
348 remember_me: bool,
349 ) -> Result<SignInResult, AuthError> {
350 self.run_gates(user, method.into(), remember_me, None).await
351 }
352
353 pub async fn complete_sign_in(
368 &self,
369 challenger: &str,
370 user: UserView,
371 method: impl Into<Cow<'static, str>>,
372 remember_me: bool,
373 ) -> Result<SignInResult, AuthError> {
374 if !self
375 .ctx
376 .shared
377 .gates
378 .iter()
379 .any(|gate| gate.owner == challenger)
380 {
381 return Err(AuthError::internal(format!(
382 "complete_sign_in: no sign-in gate belongs to `{challenger}`"
383 )));
384 }
385 self.run_gates(user, method.into(), remember_me, Some(challenger))
386 .await
387 }
388
389 async fn run_gates(
390 &self,
391 user: UserView,
392 method: Cow<'static, str>,
393 remember_me: bool,
394 skip: Option<&str>,
395 ) -> Result<SignInResult, AuthError> {
396 let attempt = SignInAttempt {
397 user: user.clone(),
398 method,
399 remember_me,
400 };
401 for owned in &self.ctx.shared.gates {
402 if skip == Some(owned.owner) {
403 continue;
404 }
405 match (owned.gate)(self.ctx.retype(), attempt.clone()).await? {
406 Gate::Allow => {}
407 Gate::Deny(err) => return Err(err),
408 Gate::Challenge(body) => return Ok(SignInResult::Challenge(body)),
409 }
410 }
411 Ok(SignInResult::SignedIn(Box::new(
412 self.create_session(&user.id, remember_me).await?,
413 )))
414 }
415
416 pub async fn claim_unverified_user(&self, user: UserView) -> Result<UserView, AuthError> {
422 if user.email_verified {
423 return Ok(user);
424 }
425 self.ctx
426 .db()
427 .delete::<Account>(Account::USER_ID.eq(&user.id))
428 .await?;
429 self.revoke_user_sessions(&user.id, None).await?;
430 self.ctx
431 .db()
432 .update::<User>(User::ID.eq(&user.id))
433 .set(User::EMAIL_VERIFIED, true)
434 .exec()
435 .await?;
436 self.ctx.emit(EmailVerified {
437 user_id: user.id.clone(),
438 });
439 self.find_user_by_id(&user.id)
440 .await?
441 .ok_or_else(|| AuthError::internal("user deleted while claiming it"))
442 }
443
444 pub async fn revoke_session(&self, user_id: &Id, session_id: &Id) -> Result<bool, AuthError> {
445 let deleted = self
446 .ctx
447 .db()
448 .delete::<Session>(Session::ID.eq(session_id).and(Session::USER_ID.eq(user_id)))
449 .await?;
450 if deleted > 0 {
451 self.ctx.emit(SessionRevoked {
452 user_id: user_id.clone(),
453 session_id: Some(session_id.clone()),
454 });
455 }
456 Ok(deleted > 0)
457 }
458
459 pub async fn revoke_user_sessions(
461 &self,
462 user_id: &Id,
463 keep: Option<&Id>,
464 ) -> Result<u64, AuthError> {
465 let mut filter = Session::USER_ID.eq(user_id);
466 if let Some(keep) = keep {
467 filter = filter.and(Session::ID.ne(keep));
468 }
469 let deleted = self.ctx.db().delete::<Session>(filter).await?;
470 if deleted > 0 {
471 self.ctx.emit(SessionRevoked {
472 user_id: user_id.clone(),
473 session_id: None,
474 });
475 }
476 Ok(deleted)
477 }
478
479 pub fn clear_session_cookies(&self) {
480 clear_session_cookies(self.ctx.config(), &self.ctx.effects);
481 }
482
483 pub async fn create_verification(
485 &self,
486 identifier: &str,
487 ttl: Duration,
488 data: Option<String>,
489 ) -> Result<String, AuthError> {
490 let token = random_token();
491 let now = self.ctx.now();
492 let verification = Verification {
493 id: self.ctx.new_id()?,
494 identifier: identifier.to_owned(),
495 value_hash: Hash::sha256(&token),
496 data,
497 expires_at: now + ttl,
498 created_at: now,
499 updated_at: now,
500 };
501 self.ctx.db().insert(&verification).await?;
502 Ok(token)
503 }
504
505 pub async fn store_verification_value(
507 &self,
508 identifier: &str,
509 value: &str,
510 ttl: Duration,
511 data: Option<String>,
512 ) -> Result<(), AuthError> {
513 self.ctx
514 .db()
515 .delete::<Verification>(Verification::IDENTIFIER.eq(identifier))
516 .await?;
517 let now = self.ctx.now();
518 let verification = Verification {
519 id: self.ctx.new_id()?,
520 identifier: identifier.to_owned(),
521 value_hash: Hash::sha256(format!("{identifier}:{value}")),
522 data,
523 expires_at: now + ttl,
524 created_at: now,
525 updated_at: now,
526 };
527 self.ctx.db().insert(&verification).await?;
528 Ok(())
529 }
530
531 pub async fn consume_verification_value(
533 &self,
534 identifier: &str,
535 value: &str,
536 ) -> Result<Option<Verification>, AuthError> {
537 self.consume_hash(Hash::sha256(format!("{identifier}:{value}")))
538 .await
539 }
540
541 pub async fn find_verification(&self, token: &str) -> Result<Option<Verification>, AuthError> {
543 let found = self
544 .ctx
545 .db()
546 .find::<Verification>(Verification::VALUE_HASH.eq(Hash::sha256(token)))
547 .one()
548 .await?;
549 Ok(found.filter(|v| v.expires_at > self.ctx.now()))
550 }
551
552 pub async fn consume_verification(
554 &self,
555 token: &str,
556 ) -> Result<Option<Verification>, AuthError> {
557 self.consume_hash(Hash::sha256(token)).await
558 }
559
560 async fn consume_hash(&self, hash: Hash) -> Result<Option<Verification>, AuthError> {
561 let Some(found) = self
562 .ctx
563 .db()
564 .find::<Verification>(Verification::VALUE_HASH.eq(hash))
565 .one()
566 .await?
567 else {
568 return Ok(None);
569 };
570 let deleted = self
571 .ctx
572 .db()
573 .delete::<Verification>(Verification::ID.eq(&found.id))
574 .await?;
575 Ok((deleted == 1 && found.expires_at > self.ctx.now()).then_some(found))
576 }
577
578 pub fn can_send_email(&self) -> bool {
580 self.ctx.mailer().is_some()
581 }
582
583 pub async fn send_email(&self, email: AuthEmail) -> Result<(), AuthError> {
584 let Some(mailer) = self.ctx.mailer() else {
585 return Err(AuthError::internal(
586 "an email needs sending but no mailer is configured",
587 ));
588 };
589 mailer.send(email).await.map_err(AuthError::internal)
590 }
591
592 pub async fn send_verification_email(
593 &self,
594 user: &UserView,
595 callback_url: Option<&str>,
596 ) -> Result<(), AuthError> {
597 let ttl = self.ctx.config().email_verification.ttl;
598 let token = self
599 .create_verification(&format!("email-verification:{}", user.id), ttl, None)
600 .await?;
601 let mut url = format!(
602 "{}/verify-email?token={token}",
603 self.ctx.config().auth_url()
604 );
605 if let Some(callback) = callback_url {
606 url.push_str(&format!("&callbackURL={}", url_encode(callback)));
607 }
608 self.send_email(AuthEmail::VerifyEmail(VerifyEmail {
609 to: user.email.clone(),
610 name: user.name.clone(),
611 url,
612 token,
613 }))
614 .await
615 }
616}