1use http::StatusCode;
5use time::{Duration, OffsetDateTime};
6
7use crate::adapter::{Adapter, DbError, Transaction};
8use crate::crypto::{Hash, random_token};
9use crate::endpoint::{Ctx, Gate, SignInAttempt};
10use crate::error::{AuthError, codes};
11use crate::events::{AccountLinked, SessionCreated, SessionRevoked, UserCreated};
12use crate::mail::{AuthEmail, VerifyEmail};
13use crate::model::Model;
14use crate::models::{Account, Session, User, Verification};
15use crate::session::{
16 SESSION_DATA, SessionView, UserView, clear_session_cookies, set_session_cookies,
17};
18use crate::value::{ColumnValue, Id, Value};
19
20#[derive(Clone, Debug, Default)]
22pub struct NewUser {
23 pub email: String,
24 pub name: String,
25 pub image: Option<String>,
26 pub email_verified: bool,
27 pub extra: Vec<(&'static str, Value)>,
29}
30
31#[derive(Clone, Debug, Default)]
33pub struct NewAccount {
34 pub provider_id: String,
35 pub account_id: Option<String>,
37 pub password_hash: Option<String>,
38 pub access_token: Option<String>,
40 pub refresh_token: Option<String>,
42 pub id_token: Option<String>,
43 pub access_token_expires_at: Option<OffsetDateTime>,
44 pub refresh_token_expires_at: Option<OffsetDateTime>,
45 pub scope: Option<String>,
46}
47
48impl NewAccount {
49 pub fn credential(password_hash: String) -> Self {
50 Self {
51 provider_id: Account::CREDENTIAL.into(),
52 password_hash: Some(password_hash),
53 ..Self::default()
54 }
55 }
56
57 pub fn oauth(provider_id: impl Into<String>, account_id: impl Into<String>) -> Self {
58 Self {
59 provider_id: provider_id.into(),
60 account_id: Some(account_id.into()),
61 ..Self::default()
62 }
63 }
64}
65
66#[derive(Clone, Debug)]
67pub enum SignInResult {
68 SignedIn(Box<SessionView>),
69 Challenge(serde_json::Value),
71}
72
73fn user_exists(err: DbError) -> AuthError {
74 match err {
75 DbError::UniqueViolation { ref table, .. } if table == User::TABLE => AuthError::new(
76 StatusCode::UNPROCESSABLE_ENTITY,
77 codes::USER_ALREADY_EXISTS_USE_ANOTHER_EMAIL,
78 "user already exists, use another email",
79 ),
80 other => other.into(),
81 }
82}
83
84pub(crate) fn url_encode(value: &str) -> String {
85 url::form_urlencoded::byte_serialize(value.as_bytes()).collect()
86}
87
88pub struct Internal<'a, D, A> {
89 ctx: &'a Ctx<D, A>,
90}
91
92impl<'a, D: Adapter, A> Internal<'a, D, A> {
93 pub(crate) fn new(ctx: &'a Ctx<D, A>) -> Self {
94 Self { ctx }
95 }
96
97 pub async fn find_user_by_email(&self, email: &str) -> Result<Option<UserView>, AuthError> {
98 let row = self
99 .ctx
100 .db()
101 .find::<User>(User::EMAIL.eq(email.trim().to_lowercase()))
102 .one_row()
103 .await?;
104 row.map(UserView::from_row)
105 .transpose()
106 .map_err(AuthError::internal)
107 }
108
109 pub async fn find_user_by_id(&self, id: &Id) -> Result<Option<UserView>, AuthError> {
110 let row = self
111 .ctx
112 .db()
113 .find::<User>(User::ID.eq(id))
114 .one_row()
115 .await?;
116 row.map(UserView::from_row)
117 .transpose()
118 .map_err(AuthError::internal)
119 }
120
121 fn account_values(&self, user_id: &Id, account: NewAccount) -> Vec<(&'static str, Value)> {
122 let keys = self.ctx.keys();
123 let seal = |t: Option<String>| t.map(|t| keys.encrypt(t.as_bytes()));
124 vec![
125 ("id", self.ctx.new_id().into_value()),
126 ("user_id", user_id.clone().into_value()),
127 ("provider_id", account.provider_id.into_value()),
128 (
129 "account_id",
130 account
131 .account_id
132 .unwrap_or_else(|| user_id.to_string())
133 .into_value(),
134 ),
135 ("password_hash", account.password_hash.into_value()),
136 ("access_token", seal(account.access_token).into_value()),
137 ("refresh_token", seal(account.refresh_token).into_value()),
138 ("id_token", account.id_token.into_value()),
139 (
140 "access_token_expires_at",
141 account.access_token_expires_at.into_value(),
142 ),
143 (
144 "refresh_token_expires_at",
145 account.refresh_token_expires_at.into_value(),
146 ),
147 ("scope", account.scope.into_value()),
148 ]
149 }
150
151 pub async fn create_user(
154 &self,
155 user: NewUser,
156 account: Option<NewAccount>,
157 ) -> Result<UserView, AuthError> {
158 let id = self.ctx.new_id();
159 let mut values = vec![
160 ("id", id.clone().into_value()),
161 ("email", user.email.trim().to_lowercase().into_value()),
162 ("email_verified", user.email_verified.into_value()),
163 ("name", user.name.into_value()),
164 ("image", user.image.into_value()),
165 ];
166 values.extend(user.extra);
167 let tx = self.ctx.adapter().begin().await?;
168 let db = self.ctx.db_on(&tx);
169 let row = db.insert_row::<User>(values).await.map_err(user_exists)?;
170 if let Some(account) = account {
171 db.insert_row::<Account>(self.account_values(&id, account))
172 .await?;
173 }
174 tx.commit().await?;
175 let view = UserView::from_row(row).map_err(AuthError::internal)?;
176 self.ctx.emit(UserCreated {
177 user_id: view.id.clone(),
178 email: view.email.clone(),
179 });
180 Ok(view)
181 }
182
183 pub async fn link_account(
184 &self,
185 user_id: &Id,
186 account: NewAccount,
187 ) -> Result<Account, AuthError> {
188 let provider_id = account.provider_id.clone();
189 let row = self
190 .ctx
191 .db()
192 .insert_row::<Account>(self.account_values(user_id, account))
193 .await?;
194 self.ctx.emit(AccountLinked {
195 user_id: user_id.clone(),
196 provider_id,
197 });
198 Account::decode(&row).map_err(AuthError::internal)
199 }
200
201 pub async fn find_account(
202 &self,
203 provider_id: &str,
204 account_id: &str,
205 ) -> Result<Option<Account>, AuthError> {
206 let filter = Account::PROVIDER_ID
207 .eq(provider_id)
208 .and(Account::ACCOUNT_ID.eq(account_id));
209 Ok(self.ctx.db().find::<Account>(filter).one().await?)
210 }
211
212 pub async fn credential_account(&self, user_id: &Id) -> Result<Option<Account>, AuthError> {
213 let filter = Account::USER_ID
214 .eq(user_id)
215 .and(Account::PROVIDER_ID.eq(Account::CREDENTIAL));
216 Ok(self.ctx.db().find::<Account>(filter).one().await?)
217 }
218
219 pub fn validate_new_password(&self, password: &str) -> Result<(), AuthError> {
221 let Some(config) = &self.ctx.config().email_password else {
222 return Ok(());
223 };
224 let length = password.chars().count();
225 if length < config.min_password_length {
226 return Err(AuthError::bad_request(
227 codes::PASSWORD_TOO_SHORT,
228 "password is too short",
229 ));
230 }
231 if length > config.max_password_length {
232 return Err(AuthError::bad_request(
233 codes::PASSWORD_TOO_LONG,
234 "password is too long",
235 ));
236 }
237 if config
238 .password_policy
239 .as_ref()
240 .is_some_and(|policy| !policy(password))
241 {
242 return Err(AuthError::bad_request(
243 codes::PASSWORD_TOO_WEAK,
244 "password is too weak",
245 ));
246 }
247 Ok(())
248 }
249
250 pub async fn set_password(&self, user_id: &Id, password: &str) -> Result<(), AuthError> {
252 self.validate_new_password(password)?;
253 let hash = self
254 .ctx
255 .passwords()
256 .hash(password)
257 .await
258 .map_err(AuthError::internal)?;
259 let updated = self
260 .ctx
261 .db()
262 .update::<Account>(
263 Account::USER_ID
264 .eq(user_id)
265 .and(Account::PROVIDER_ID.eq(Account::CREDENTIAL)),
266 )
267 .set(Account::PASSWORD_HASH, Some(hash.clone()))
268 .exec()
269 .await?;
270 if updated == 0 {
271 self.link_account(user_id, NewAccount::credential(hash))
272 .await?;
273 }
274 Ok(())
275 }
276
277 pub async fn create_session(
280 &self,
281 user_id: &Id,
282 remember_me: bool,
283 ) -> Result<SessionView, AuthError> {
284 let now = self.ctx.now();
285 let token = random_token();
286 let session = Session {
287 id: self.ctx.new_id(),
288 token_hash: Hash::sha256(&token),
289 user_id: user_id.clone(),
290 expires_at: now + self.ctx.config().session.expires_in,
291 ip_address: self.ctx.ip().map(str::to_owned),
292 user_agent: self
293 .ctx
294 .user_agent()
295 .map(|ua| ua.chars().take(512).collect()),
296 created_at: now,
297 updated_at: now,
298 };
299 let row = self
300 .ctx
301 .db()
302 .insert_row::<Session>(session.encode())
303 .await?;
304 let user = self
305 .find_user_by_id(user_id)
306 .await?
307 .ok_or_else(|| AuthError::internal("session for a missing user"))?;
308 let config = self.ctx.config();
309 set_session_cookies(
310 config,
311 self.ctx.keys(),
312 &self.ctx.effects,
313 &token,
314 remember_me,
315 );
316 self.ctx.set_cookie(crate::cookies::SetCookie::delete(
317 config.cookie_name(SESSION_DATA),
318 ));
319 self.ctx.emit(SessionCreated {
320 session_id: session.id.clone(),
321 user_id: user_id.clone(),
322 });
323 Ok(SessionView {
324 session,
325 row,
326 user,
327 token: Some(token),
328 ephemeral: false,
329 })
330 }
331
332 pub async fn sign_in(
334 &self,
335 user: UserView,
336 method: &'static str,
337 remember_me: bool,
338 ) -> Result<SignInResult, AuthError> {
339 let attempt = SignInAttempt {
340 user: user.clone(),
341 method,
342 remember_me,
343 };
344 for gate in &self.ctx.shared.gates {
345 match gate(self.ctx.retype(), attempt.clone()).await? {
346 Gate::Allow => {}
347 Gate::Deny(err) => return Err(err),
348 Gate::Challenge(body) => return Ok(SignInResult::Challenge(body)),
349 }
350 }
351 Ok(SignInResult::SignedIn(Box::new(
352 self.create_session(&user.id, remember_me).await?,
353 )))
354 }
355
356 pub async fn revoke_session(&self, user_id: &Id, session_id: &Id) -> Result<bool, AuthError> {
357 let deleted = self
358 .ctx
359 .db()
360 .delete::<Session>(Session::ID.eq(session_id).and(Session::USER_ID.eq(user_id)))
361 .await?;
362 if deleted > 0 {
363 self.ctx.emit(SessionRevoked {
364 user_id: user_id.clone(),
365 session_id: Some(session_id.clone()),
366 });
367 }
368 Ok(deleted > 0)
369 }
370
371 pub async fn revoke_user_sessions(
373 &self,
374 user_id: &Id,
375 keep: Option<&Id>,
376 ) -> Result<u64, AuthError> {
377 let mut filter = Session::USER_ID.eq(user_id);
378 if let Some(keep) = keep {
379 filter = filter.and(Session::ID.ne(keep));
380 }
381 let deleted = self.ctx.db().delete::<Session>(filter).await?;
382 if deleted > 0 {
383 self.ctx.emit(SessionRevoked {
384 user_id: user_id.clone(),
385 session_id: None,
386 });
387 }
388 Ok(deleted)
389 }
390
391 pub fn clear_session_cookies(&self) {
392 clear_session_cookies(self.ctx.config(), &self.ctx.effects);
393 }
394
395 pub async fn create_verification(
397 &self,
398 identifier: &str,
399 ttl: Duration,
400 data: Option<String>,
401 ) -> Result<String, AuthError> {
402 let token = random_token();
403 let now = self.ctx.now();
404 let verification = Verification {
405 id: self.ctx.new_id(),
406 identifier: identifier.to_owned(),
407 value_hash: Hash::sha256(&token),
408 data,
409 expires_at: now + ttl,
410 created_at: now,
411 updated_at: now,
412 };
413 self.ctx.db().insert(&verification).await?;
414 Ok(token)
415 }
416
417 pub async fn store_verification_value(
419 &self,
420 identifier: &str,
421 value: &str,
422 ttl: Duration,
423 data: Option<String>,
424 ) -> Result<(), AuthError> {
425 self.ctx
426 .db()
427 .delete::<Verification>(Verification::IDENTIFIER.eq(identifier))
428 .await?;
429 let now = self.ctx.now();
430 let verification = Verification {
431 id: self.ctx.new_id(),
432 identifier: identifier.to_owned(),
433 value_hash: Hash::sha256(format!("{identifier}:{value}")),
434 data,
435 expires_at: now + ttl,
436 created_at: now,
437 updated_at: now,
438 };
439 self.ctx.db().insert(&verification).await?;
440 Ok(())
441 }
442
443 pub async fn consume_verification_value(
445 &self,
446 identifier: &str,
447 value: &str,
448 ) -> Result<Option<Verification>, AuthError> {
449 self.consume_hash(Hash::sha256(format!("{identifier}:{value}")))
450 .await
451 }
452
453 pub async fn find_verification(&self, token: &str) -> Result<Option<Verification>, AuthError> {
455 let found = self
456 .ctx
457 .db()
458 .find::<Verification>(Verification::VALUE_HASH.eq(Hash::sha256(token)))
459 .one()
460 .await?;
461 Ok(found.filter(|v| v.expires_at > self.ctx.now()))
462 }
463
464 pub async fn consume_verification(
466 &self,
467 token: &str,
468 ) -> Result<Option<Verification>, AuthError> {
469 self.consume_hash(Hash::sha256(token)).await
470 }
471
472 async fn consume_hash(&self, hash: Hash) -> Result<Option<Verification>, AuthError> {
473 let Some(found) = self
474 .ctx
475 .db()
476 .find::<Verification>(Verification::VALUE_HASH.eq(hash))
477 .one()
478 .await?
479 else {
480 return Ok(None);
481 };
482 let deleted = self
483 .ctx
484 .db()
485 .delete::<Verification>(Verification::ID.eq(&found.id))
486 .await?;
487 Ok((deleted == 1 && found.expires_at > self.ctx.now()).then_some(found))
488 }
489
490 pub fn can_send_email(&self) -> bool {
492 self.ctx.mailer().is_some()
493 }
494
495 pub async fn send_email(&self, email: AuthEmail) -> Result<(), AuthError> {
496 let Some(mailer) = self.ctx.mailer() else {
497 return Err(AuthError::internal(
498 "an email needs sending but no mailer is configured",
499 ));
500 };
501 mailer.send(email).await.map_err(AuthError::internal)
502 }
503
504 pub async fn send_verification_email(
505 &self,
506 user: &UserView,
507 callback_url: Option<&str>,
508 ) -> Result<(), AuthError> {
509 let ttl = self.ctx.config().email_verification.ttl;
510 let token = self
511 .create_verification(&format!("email-verification:{}", user.id), ttl, None)
512 .await?;
513 let mut url = format!(
514 "{}/verify-email?token={token}",
515 self.ctx.config().auth_url()
516 );
517 if let Some(callback) = callback_url {
518 url.push_str(&format!("&callbackURL={}", url_encode(callback)));
519 }
520 self.send_email(AuthEmail::VerifyEmail(VerifyEmail {
521 to: user.email.clone(),
522 name: user.name.clone(),
523 url,
524 token,
525 }))
526 .await
527 }
528}