1use std::sync::Arc;
2
3use axum::extract::{Extension, State};
4use axum::response::{IntoResponse, Redirect, Response};
5use serde::{Deserialize, Serialize};
6use serde_json::{Value, json};
7
8use super::events::{LockedOut, LoggedIn, LoggedOut, LoginFailed, Registered, announce};
9use super::user::dummy_hash;
10use super::{User, intended, login, logout, passwords, verification, verify_password};
11use crate::db::Migration;
12use crate::i18n::Lang;
13use crate::validation::{Errors, Valid, Validate, ValidationError, Validator};
14use crate::{
15 AppState, AuthUser, ClientIp, Htmx, HxRedirect, Module, Result, Routes, Session, View, context,
16 view,
17};
18
19const MIGRATIONS: &[Migration] = &[
20 crate::db::framework_migration!("auth", "00010101000000_create_users_table"),
21 crate::db::framework_migration!("auth", "00010101000001_create_password_reset_tokens_table"),
22 crate::db::framework_migration!("auth", "00010101000002_create_personal_access_tokens_table"),
23 crate::db::framework_migration!("auth", "00010101000003_create_notifications_table"),
24 crate::db::framework_migration!("auth", "00010101000004_add_sessions_revoked_at_to_users"),
25 crate::db::framework_migration!(
26 "auth",
27 "00010101000005_add_abilities_to_personal_access_tokens"
28 ),
29 crate::db::framework_migration!("auth", "00010101000006_create_revoked_sessions_table"),
30 crate::db::framework_migration!("auth", "00010101000007_create_device_tokens_table"),
31 crate::db::framework_migration!("auth", "00010101000008_create_one_time_codes_table"),
32];
33
34pub(crate) struct Settings {
35 pub(super) password: crate::validation::Password,
36 pub(super) registration: bool,
37 redirect_to: Option<String>,
38 pub(super) verify_email: bool,
39 rules: Option<RulesFn>,
40 pub(super) on_registered: Option<RegisteredFn>,
41 pub(super) passwordless: super::passwordless::Passwordless,
42}
43
44type RulesFn = Arc<dyn Fn(&Registration, &mut Validator) + Send + Sync>;
45pub(super) type RegisteredFn = Arc<
46 dyn Fn(
47 AppState,
48 User,
49 Registration,
50 ) -> std::pin::Pin<Box<dyn std::future::Future<Output = Result> + Send>>
51 + Send
52 + Sync,
53>;
54
55#[derive(Debug, Clone)]
59#[non_exhaustive]
60pub struct Registration {
61 pub(super) fields: serde_json::Map<String, Value>,
62}
63
64impl Registration {
65 pub fn get(&self, field: &str) -> String {
67 match self.fields.get(field) {
68 Some(Value::String(value)) => value.trim().to_owned(),
69 Some(Value::Array(values)) => values
70 .first()
71 .and_then(Value::as_str)
72 .unwrap_or_default()
73 .trim()
74 .to_owned(),
75 _ => String::new(),
76 }
77 }
78
79 pub fn all(&self, field: &str) -> Vec<String> {
81 match self.fields.get(field) {
82 Some(Value::String(value)) => vec![value.clone()],
83 Some(Value::Array(values)) => values
84 .iter()
85 .filter_map(|v| v.as_str().map(str::to_owned))
86 .collect(),
87 _ => Vec::new(),
88 }
89 }
90}
91
92#[derive(Clone)]
111pub struct Auth {
112 password: crate::validation::Password,
113 account: bool,
114 registration: bool,
115 redirect_to: Option<String>,
116 verify_email: bool,
117 notifications: bool,
118 rules: Option<RulesFn>,
119 on_registered: Option<RegisteredFn>,
120 passwordless: super::passwordless::Passwordless,
121}
122
123impl Auth {
124 pub fn new() -> Self {
126 Self {
127 password: crate::validation::Password::default(),
128 account: false,
129 registration: true,
130 redirect_to: None,
131 verify_email: false,
132 notifications: false,
133 rules: None,
134 on_registered: None,
135 passwordless: super::passwordless::Passwordless {
136 magic_link: None,
137 same_browser: false,
138 codes: None,
139 register_on_first_use: false,
140 sent: Default::default(),
141 },
142 }
143 }
144
145 pub fn magic_link(mut self) -> Self {
161 self.passwordless.magic_link = Some(super::passwordless::MagicLink {
162 ttl: std::time::Duration::from_secs(15 * 60),
163 });
164 self
165 }
166
167 pub fn magic_link_ttl(mut self, ttl: std::time::Duration) -> Self {
170 self.passwordless.magic_link = Some(super::passwordless::MagicLink { ttl });
171 self
172 }
173
174 pub fn same_browser(mut self) -> Self {
179 self.passwordless.same_browser = true;
180 self
181 }
182
183 pub fn login_codes(mut self, mut codes: super::LoginCodes) -> Self {
189 if codes.channels.is_empty() {
190 codes = codes.channel("mail");
191 }
192 self.passwordless.codes = Some(codes);
193 self
194 }
195
196 pub fn register_on_first_use(mut self) -> Self {
203 self.passwordless.register_on_first_use = true;
204 self
205 }
206
207 pub fn notifications(mut self) -> Self {
220 self.notifications = true;
221 self
222 }
223
224 pub fn registration_rules(
243 mut self,
244 rules: impl Fn(&Registration, &mut Validator) + Send + Sync + 'static,
245 ) -> Self {
246 self.rules = Some(Arc::new(rules));
247 self
248 }
249
250 pub fn on_registered<F, Fut>(mut self, hook: F) -> Self
254 where
255 F: Fn(User, Registration, AppState) -> Fut + Send + Sync + 'static,
256 Fut: std::future::Future<Output = Result> + Send + 'static,
257 {
258 self.on_registered = Some(Arc::new(move |state, user, form| {
259 Box::pin(hook(user, form, state))
260 }));
261 self
262 }
263
264 pub fn verify_email(mut self) -> Self {
267 self.verify_email = true;
268 self
269 }
270
271 pub fn password_rules(mut self, policy: crate::validation::Password) -> Self {
282 self.password = policy;
283 self
284 }
285
286 pub fn account(mut self) -> Self {
292 self.account = true;
293 self
294 }
295
296 pub fn without_registration(mut self) -> Self {
298 self.registration = false;
299 self
300 }
301
302 pub fn redirect_to(mut self, path: &str) -> Self {
305 self.redirect_to = Some(path.to_owned());
306 self
307 }
308
309 fn settings(&self) -> Settings {
310 Settings {
311 password: self.password.clone(),
312 registration: self.registration,
313 redirect_to: self.redirect_to.clone(),
314 verify_email: self.verify_email,
315 rules: self.rules.clone(),
316 on_registered: self.on_registered.clone(),
317 passwordless: self.passwordless.clone(),
318 }
319 }
320}
321
322impl Default for Auth {
323 fn default() -> Self {
324 Self::new()
325 }
326}
327
328impl Module for Auth {
329 fn name(&self) -> &'static str {
330 "auth"
331 }
332
333 fn migrations(&self) -> &'static [Migration] {
334 MIGRATIONS
335 }
336
337 fn register(&self, app: &mut crate::Registry) {
338 app.auth = Some(Arc::new(self.settings()));
340 if self.notifications {
341 app.share(
342 "unread_notifications",
343 |ctx: crate::view::ViewContext| async move {
344 match ctx.user {
345 Some(user) => user.unread_notification_count(&ctx.state.db).await,
346 None => Ok(0),
347 }
348 },
349 );
350 }
351 app.command(
353 "tokens:prune",
354 "Delete API tokens that expired more than a day ago",
355 |_args, state| async move {
356 let day = std::time::Duration::from_secs(24 * 60 * 60);
357 let pruned = super::prune_expired_tokens(&state.db, day).await?
358 + super::DeviceToken::prune_expired(&state.db, day).await?
359 + super::prune_expired_codes(&state.db).await?;
360 println!("Deleted {pruned} expired API tokens and login codes.");
361 Ok(())
362 },
363 );
364 app.command(
365 "notifications:prune",
366 "Delete notifications read more than --days ago (default 30)",
367 |args, state| async move {
368 let days: u64 = args
369 .value("--days")
370 .unwrap_or("30")
371 .parse()
372 .map_err(|_| crate::Error::BadRequest("--days must be a number".into()))?;
373 let age = std::time::Duration::from_secs(days * 24 * 60 * 60);
374 let pruned = super::prune_read_notifications(&state.db, age).await?;
375 println!("Deleted {pruned} notifications read more than {days} days ago.");
376 Ok(())
377 },
378 );
379 }
380
381 fn routes(&self) -> Routes {
382 let settings = Arc::new(self.settings());
383
384 let mut guest = Routes::new()
385 .get("/login", show_login)
386 .post("/login", store_login)
387 .name("login");
388 if self.registration {
389 guest = guest
390 .get("/register", show_register)
391 .post("/register", store_register)
392 .name("register");
393 }
394 let guest = guest
395 .get("/forgot-password", passwords::show_forgot)
396 .name("password.request")
397 .post("/forgot-password", passwords::send_link)
398 .name("password.email")
399 .get("/reset-password/{token}", passwords::show_reset)
400 .name("password.reset")
401 .post("/reset-password", passwords::reset)
402 .name("password.update")
403 .guest_only();
404 let verification = Routes::new()
405 .get("/verify-email", verification::notice)
406 .name("verification.notice")
407 .get("/verify-email/{id}/{hash}", verification::verify)
408 .name("verification.verify")
409 .post("/email/verification-notification", verification::resend)
410 .name("verification.send")
411 .require_auth();
412 let confirm = Routes::new()
413 .get("/confirm-password", super::account::show_confirm)
414 .post("/confirm-password", super::account::confirm)
415 .name("password.confirm")
416 .require_auth();
417 let mut routes = guest
418 .merge(verification)
419 .merge(confirm)
420 .merge(Routes::new().post("/logout", destroy).name("logout"));
421 if self.passwordless.magic_link.is_some() || self.passwordless.codes.is_some() {
422 routes = routes.merge(self.passwordless_routes());
423 }
424 if self.account {
425 routes = routes.merge(super::account::routes());
426 }
427 if self.notifications {
428 routes = routes.merge(super::inbox::routes());
429 }
430 routes.route_layer(Extension(settings))
431 }
432}
433
434impl Auth {
435 fn passwordless_routes(&self) -> Routes {
437 use super::passwordless as p;
438 let mut routes = Routes::new();
439 if self.passwordless.magic_link.is_some() {
440 routes = routes
441 .get("/login/link", p::show_link_request)
442 .name("login.link.request")
443 .post("/login/link", p::send_link)
444 .name("login.link.send")
445 .get("/login/link/{token}", p::show_link)
446 .name("login.link.show")
447 .post("/login/link/{token}", p::consume_link)
448 .name("login.link.consume");
449 }
450 if self.passwordless.codes.is_some() {
451 routes = routes
452 .get("/login/code", p::show_code_request)
453 .name("login.code.request")
454 .post("/login/code", p::send_code)
455 .name("login.code.send")
456 .get("/login/code/verify", p::show_code_verify)
457 .post("/login/code/verify", p::check_code)
458 .name("login.code.verify")
459 .post("/login/code/resend", p::resend_code)
460 .name("login.code.resend");
461 }
462 routes.guest_only()
463 }
464}
465
466pub(super) fn texts(lang: &Lang) -> Value {
469 let mut base = text();
470 if let Value::Object(map) = &mut base {
471 for (key, value) in lang.texts().iter() {
472 if let Some(key) = key.strip_prefix("renox.auth.") {
473 map.insert(key.to_owned(), Value::String(value.clone()));
474 }
475 }
476 }
477 base
478}
479
480pub(super) fn message(lang: &Lang, key: &str, params: &[(&str, String)]) -> String {
482 let template = crate::validation::template_for(Some(&lang.texts()), key);
483 crate::i18n::format(&template, params, None)
484}
485
486pub(super) fn after_login(state: &AppState, settings: &Settings, session: &Session) -> String {
487 let fallback = settings
488 .redirect_to
489 .clone()
490 .unwrap_or_else(|| state.url("home", &[]).unwrap_or_else(|_| "/".into()));
491 intended(session, fallback)
492}
493
494pub(super) fn go(htmx: &Htmx, to: String) -> Response {
496 if htmx.request {
497 HxRedirect(to).into_response()
498 } else {
499 Redirect::to(&to).into_response()
500 }
501}
502
503async fn show_login(Extension(settings): Extension<Arc<Settings>>, lang: Lang) -> View {
504 view(
505 "renox/auth/login.html",
506 context! {
507 registration => settings.registration,
508 magic_link => settings.passwordless.magic_link.is_some(),
509 login_codes => settings.passwordless.codes.is_some(),
510 text => texts(&lang),
511 },
512 )
513}
514
515#[derive(Deserialize, Serialize)]
516struct LoginForm {
517 email: String,
518 password: String,
519 remember: Option<String>,
520}
521
522pub(super) fn label(_v: &Validator, field: &'static str) -> &'static str {
524 match field {
525 "current_password" => "current password",
526 _ => field,
527 }
528}
529
530impl Validate for LoginForm {
531 fn rules(&self, v: &mut Validator) {
532 v.field("email", &super::user::normalize_email(&self.email))
533 .required()
534 .email();
535 let password = label(v, "password");
536 v.field("password", &self.password)
537 .fallback_label(password)
538 .required();
539 }
540}
541
542async fn store_login(
543 Extension(settings): Extension<Arc<Settings>>,
544 State(state): State<AppState>,
545 session: Session,
546 htmx: Htmx,
547 ClientIp(ip): ClientIp,
548 lang: Lang,
549 Valid(form): Valid<LoginForm>,
550) -> Result<Response> {
551 let failed = |key: &str, seconds: Option<u64>| {
552 let mut errors = Errors::new();
553 let seconds = seconds.map(|s| s.to_string()).unwrap_or_default();
554 errors.add("email", message(&lang, key, &[("seconds", seconds)]));
555 ValidationError::new(errors)
556 .with_input(&json!({ "email": form.email, "remember": form.remember }))
557 };
558
559 let address = ip.map(|ip| ip.to_string());
560 if let Some(seconds) = state.throttle.blocked_for(&form.email, ip).await {
561 let event = LockedOut {
562 email: form.email.clone(),
563 ip: address,
564 seconds,
565 };
566 announce(&state, event).await;
567 return Err(failed("auth.throttle", Some(seconds)).into());
568 }
569
570 let user = User::find_by_email(&state.db, &form.email).await?;
571 let hash = user
573 .as_ref()
574 .map_or_else(dummy_hash, |u| u.password.clone());
575 let valid = verify_password(&form.password, &hash).await;
576 let Some(mut user) = user.filter(|_| valid) else {
577 state.throttle.fail(&form.email, ip).await;
578 let event = LoginFailed {
579 email: form.email.clone(),
580 ip: address,
581 };
582 announce(&state, event).await;
583 return Err(failed("auth.failed", None).into());
584 };
585 user.rehash_if_needed(&state.db, &form.password).await?;
586
587 if let Some(second) = &state.second_factor
591 && (second.required)(user.clone(), state.clone()).await?
592 {
593 let to = after_login(&state, &settings, &session);
594 super::second_factor::begin(
595 &session,
596 &user,
597 &form.email,
598 form.remember.is_some(),
599 to,
600 "password",
601 )?;
602 let challenge = state.url(&second.challenge, &[])?;
603 return Ok(go(&htmx, challenge));
604 }
605
606 state.throttle.clear(&form.email, ip).await;
607 let remember = form
608 .remember
609 .is_some()
610 .then_some(state.config.remember_lifetime);
611 login(&session, &user, remember)?;
612 super::account::mark_confirmed(&session)?;
613 let event = LoggedIn {
614 user_id: user.id,
615 ip: address,
616 via: "password".into(),
617 };
618 announce(&state, event).await;
619 Ok(go(&htmx, after_login(&state, &settings, &session)))
620}
621
622async fn show_register(lang: Lang) -> View {
623 view(
624 "renox/auth/register.html",
625 context! { text => texts(&lang) },
626 )
627}
628
629#[derive(Deserialize)]
630struct RegisterForm {
631 name: String,
632 email: String,
633 password: String,
634 password_confirmation: Option<String>,
635}
636
637impl Validate for RegisterForm {
638 fn rules(&self, v: &mut Validator) {
639 let (name, password) = (label(v, "name"), label(v, "password"));
640 v.field("name", &self.name)
641 .fallback_label(name)
642 .required()
643 .max(255);
644 v.field("email", &super::user::normalize_email(&self.email))
646 .required()
647 .email()
648 .max(255)
649 .unique("users", "email");
650 let _ = password;
652 }
653}
654
655async fn store_register(
656 Extension(settings): Extension<Arc<Settings>>,
657 State(state): State<AppState>,
658 session: Session,
659 htmx: Htmx,
660 lang: Lang,
661 req: axum::extract::Request,
662) -> Result<Response> {
663 let rules = settings.rules.clone();
664 let policy = settings.password.clone();
665 let validated = crate::validation::extract::validate_request(
666 req,
667 &state,
668 move |form: &RegisterForm, fields, v| {
669 let password = label(v, "password");
670 v.field("password", &form.password)
671 .fallback_label(password)
672 .required()
673 .password(&policy)
674 .confirmed(&form.password_confirmation);
675 if let Some(rules) = &rules {
676 rules(
677 &Registration {
678 fields: fields.clone(),
679 },
680 v,
681 );
682 }
683 },
684 )
685 .await;
686 let (form, fields) = match validated {
687 Ok(validated) => validated,
688 Err(rejection) => return Ok(rejection),
689 };
690 let user = match User::register(&state.db, &form.name, &form.email, &form.password).await {
691 Ok(user) => user,
692 Err(err) if err.is_unique_violation() => {
695 let template = crate::validation::template_for(Some(&lang.texts()), "unique");
696 let mut errors = Errors::new();
697 errors.add("email", crate::validation::render(&template, "email", &[]));
698 return Err(ValidationError::new(errors)
699 .with_input(&json!({ "name": form.name, "email": form.email }))
700 .into());
701 }
702 Err(err) => return Err(err),
703 };
704 let user = match &settings.on_registered {
705 None => user,
706 Some(hook) => {
707 let id = user.id;
708 if let Err(err) = hook(state.clone(), user, Registration { fields }).await {
709 crate::db::sql("DELETE FROM users WHERE id = ?")
711 .bind(id)
712 .execute(&state.db)
713 .await?;
714 return Err(err);
715 }
716 <User as crate::db::Model>::find_or_404(&state.db, id).await?
718 }
719 };
720 if settings.verify_email {
721 verification::send_verification(&state, &user).await?;
722 }
723 let event = Registered {
724 user_id: user.id,
725 email: user.email.clone(),
726 };
727 if let Some(second) = &state.second_factor
730 && (second.required)(user.clone(), state.clone()).await?
731 {
732 let to = after_login(&state, &settings, &session);
733 super::second_factor::begin(&session, &user, &user.email, false, to, "password")?;
734 announce(&state, event).await;
735 let challenge = state.url(&second.challenge, &[])?;
736 return Ok(go(&htmx, challenge));
737 }
738 login(&session, &user, None)?;
739 announce(&state, event).await;
740 Ok(go(&htmx, after_login(&state, &settings, &session)))
741}
742
743async fn destroy(
744 State(state): State<AppState>,
745 session: Session,
746 user: Option<AuthUser>,
747 htmx: Htmx,
748) -> Result<Response> {
749 logout(&state.db, &session).await?;
750 if let Some(user) = user {
751 announce(&state, LoggedOut { user_id: user.id }).await;
752 }
753 Ok(go(
754 &htmx,
755 state.url("home", &[]).unwrap_or_else(|_| "/".into()),
756 ))
757}
758
759pub(super) fn text() -> Value {
762 let mut text = json!({
763 "login_title": "Log in",
764 "register_title": "Create an account",
765 "name": "Name",
766 "email": "Email",
767 "password": "Password",
768 "password_confirmation": "Confirm password",
769 "remember": "Remember me",
770 "login_button": "Log in",
771 "register_button": "Register",
772 "no_account": "No account yet?",
773 "have_account": "Already registered?",
774 "forgot_link": "Forgot your password?",
775 "forgot_title": "Forgot your password?",
776 "forgot_intro": "Enter your email and we'll send you a link to choose a new password.",
777 "send_link": "Email me a reset link",
778 "back_to_login": "Back to log in",
779 "reset_title": "Choose a new password",
780 "reset_button": "Reset password",
781 "reset_link_sent": "If that email has an account, a reset link is on its way.",
782 "reset_invalid": "This password reset link is invalid or has expired.",
783 "password_reset_done": "Your password has been reset. You can log in now.",
784 "verify_title": "Verify your email",
785 "verify_intro": "We've emailed you a link to verify your address. Didn't get it?",
786 "resend_button": "Send another link",
787 "logout": "Log out",
788 "verification_sent": "A new verification link has been sent.",
789 "verified": "Your email address is verified.",
790 "mail_reset_subject": "Reset your password",
791 "mail_reset_intro": "You asked to reset your password. Choose a new one with the button below.",
792 "mail_reset_outro": "The link works for 60 minutes. If you didn't ask for this, ignore this email.",
793 "mail_verify_subject": "Verify your email address",
794 "mail_verify_intro": "Please confirm that this is your email address.",
795 "mail_verify_outro": "The link works for 60 minutes.",
796 "account_title": "Your account",
797 "profile_title": "Profile",
798 "profile_saved": "Your profile is saved.",
799 "email_unverified": "Your new email address isn't verified yet: check your inbox.",
800 "save": "Save",
801 "password_title": "Change password",
802 "set_password_title": "Set a password",
803 "set_password_intro": "You log in with a linked account. Choose a password to log in with it too.",
804 "current_password": "Current password",
805 "new_password": "New password",
806 "password_changed": "Your password is changed. Your other devices are logged out.",
807 "other_devices_title": "Other devices",
808 "other_devices_intro": "Log out everywhere else, e.g. on a phone you lost.",
809 "other_devices_button": "Log out other devices",
810 "other_devices_logged_out": "Your other devices are logged out.",
811 "delete_title": "Delete account",
812 "delete_intro": "Your account and its data are deleted for good.",
813 "delete_button": "Delete my account",
814 "delete_confirm": "Delete your account for good?",
815 "confirm_title": "Confirm your password",
816 "confirm_intro": "This is a secure area. Please confirm your password to continue.",
817 "confirm_button": "Confirm",
818 });
819 if let (Value::Object(base), Value::Object(more)) = (&mut text, passwordless_text()) {
820 base.extend(more);
821 }
822 text
823}
824
825fn passwordless_text() -> Value {
827 json!({
828 "login_via_link": "Email me a login link",
829 "login_via_code": "Log in with a code",
830 "login_link_title": "Log in with a link",
831 "login_link_intro": "Enter your email address and we'll send you a link that logs you in. No password needed.",
832 "login_link_button": "Email me a link",
833 "login_link_sent": "If that address can log in, a link is on its way.",
834 "login_link_invalid": "This login link is invalid or has expired.",
835 "login_link_confirm_title": "Log in",
836 "login_link_confirm_intro": "You are about to log in as",
837 "login_link_confirm_button": "Log in",
838 "mail_link_subject": "Your login link",
839 "mail_link_intro": "Use the button below to log in. No password needed.",
840 "mail_link_outro": "The link works once and expires in :minutes minutes. If you didn't ask for it, ignore this email.",
841 "login_code_title": "Log in with a code",
842 "login_code_identifier": "Email or phone number",
843 "login_code_intro": "Enter how we know you and we'll send you a one-time code.",
844 "login_code_channel": "Send it by",
845 "login_code_button": "Send me a code",
846 "login_code_sent": "If that account can log in, a code is on its way.",
847 "login_code_verify_title": "Enter your code",
848 "login_code_verify_intro": "We sent a code by :channel. It expires in :minutes minutes.",
849 "login_code_input": "Code",
850 "login_code_verify_button": "Log in",
851 "login_code_wrong": "That code is wrong or has expired.",
852 "login_code_burned": "Too many wrong codes. Request a new one.",
853 "login_code_expired": "That code has expired. Request a new one.",
854 "login_code_resend": "Send a new code",
855 "login_code_other_way": "Send it another way:",
856 "login_code_message": "Your :app login code is :code. It expires in :minutes minutes.",
857 "mail_code_subject": "Your login code",
858 "mail_code_intro": "Your login code is:",
859 "mail_code_outro": "It expires in :minutes minutes. If you didn't ask for it, ignore this email.",
860 "channel_mail": "Email",
861 "channel_sms": "SMS",
862 "channel_whatsapp": "WhatsApp",
863 })
864}