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, 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 revoke_session(&self, user_id: &Id, session_id: &Id) -> Result<bool, AuthError> {
417 let deleted = self
418 .ctx
419 .db()
420 .delete::<Session>(Session::ID.eq(session_id).and(Session::USER_ID.eq(user_id)))
421 .await?;
422 if deleted > 0 {
423 self.ctx.emit(SessionRevoked {
424 user_id: user_id.clone(),
425 session_id: Some(session_id.clone()),
426 });
427 }
428 Ok(deleted > 0)
429 }
430
431 pub async fn revoke_user_sessions(
433 &self,
434 user_id: &Id,
435 keep: Option<&Id>,
436 ) -> Result<u64, AuthError> {
437 let mut filter = Session::USER_ID.eq(user_id);
438 if let Some(keep) = keep {
439 filter = filter.and(Session::ID.ne(keep));
440 }
441 let deleted = self.ctx.db().delete::<Session>(filter).await?;
442 if deleted > 0 {
443 self.ctx.emit(SessionRevoked {
444 user_id: user_id.clone(),
445 session_id: None,
446 });
447 }
448 Ok(deleted)
449 }
450
451 pub fn clear_session_cookies(&self) {
452 clear_session_cookies(self.ctx.config(), &self.ctx.effects);
453 }
454
455 pub async fn create_verification(
457 &self,
458 identifier: &str,
459 ttl: Duration,
460 data: Option<String>,
461 ) -> Result<String, AuthError> {
462 let token = random_token();
463 let now = self.ctx.now();
464 let verification = Verification {
465 id: self.ctx.new_id()?,
466 identifier: identifier.to_owned(),
467 value_hash: Hash::sha256(&token),
468 data,
469 expires_at: now + ttl,
470 created_at: now,
471 updated_at: now,
472 };
473 self.ctx.db().insert(&verification).await?;
474 Ok(token)
475 }
476
477 pub async fn store_verification_value(
479 &self,
480 identifier: &str,
481 value: &str,
482 ttl: Duration,
483 data: Option<String>,
484 ) -> Result<(), AuthError> {
485 self.ctx
486 .db()
487 .delete::<Verification>(Verification::IDENTIFIER.eq(identifier))
488 .await?;
489 let now = self.ctx.now();
490 let verification = Verification {
491 id: self.ctx.new_id()?,
492 identifier: identifier.to_owned(),
493 value_hash: Hash::sha256(format!("{identifier}:{value}")),
494 data,
495 expires_at: now + ttl,
496 created_at: now,
497 updated_at: now,
498 };
499 self.ctx.db().insert(&verification).await?;
500 Ok(())
501 }
502
503 pub async fn consume_verification_value(
505 &self,
506 identifier: &str,
507 value: &str,
508 ) -> Result<Option<Verification>, AuthError> {
509 self.consume_hash(Hash::sha256(format!("{identifier}:{value}")))
510 .await
511 }
512
513 pub async fn find_verification(&self, token: &str) -> Result<Option<Verification>, AuthError> {
515 let found = self
516 .ctx
517 .db()
518 .find::<Verification>(Verification::VALUE_HASH.eq(Hash::sha256(token)))
519 .one()
520 .await?;
521 Ok(found.filter(|v| v.expires_at > self.ctx.now()))
522 }
523
524 pub async fn consume_verification(
526 &self,
527 token: &str,
528 ) -> Result<Option<Verification>, AuthError> {
529 self.consume_hash(Hash::sha256(token)).await
530 }
531
532 async fn consume_hash(&self, hash: Hash) -> Result<Option<Verification>, AuthError> {
533 let Some(found) = self
534 .ctx
535 .db()
536 .find::<Verification>(Verification::VALUE_HASH.eq(hash))
537 .one()
538 .await?
539 else {
540 return Ok(None);
541 };
542 let deleted = self
543 .ctx
544 .db()
545 .delete::<Verification>(Verification::ID.eq(&found.id))
546 .await?;
547 Ok((deleted == 1 && found.expires_at > self.ctx.now()).then_some(found))
548 }
549
550 pub fn can_send_email(&self) -> bool {
552 self.ctx.mailer().is_some()
553 }
554
555 pub async fn send_email(&self, email: AuthEmail) -> Result<(), AuthError> {
556 let Some(mailer) = self.ctx.mailer() else {
557 return Err(AuthError::internal(
558 "an email needs sending but no mailer is configured",
559 ));
560 };
561 mailer.send(email).await.map_err(AuthError::internal)
562 }
563
564 pub async fn send_verification_email(
565 &self,
566 user: &UserView,
567 callback_url: Option<&str>,
568 ) -> Result<(), AuthError> {
569 let ttl = self.ctx.config().email_verification.ttl;
570 let token = self
571 .create_verification(&format!("email-verification:{}", user.id), ttl, None)
572 .await?;
573 let mut url = format!(
574 "{}/verify-email?token={token}",
575 self.ctx.config().auth_url()
576 );
577 if let Some(callback) = callback_url {
578 url.push_str(&format!("&callbackURL={}", url_encode(callback)));
579 }
580 self.send_email(AuthEmail::VerifyEmail(VerifyEmail {
581 to: user.email.clone(),
582 name: user.name.clone(),
583 url,
584 token,
585 }))
586 .await
587 }
588}