1use std::sync::Arc;
5
6use axum::extract::{Extension, State};
7use axum::response::{IntoResponse, Redirect, Response};
8use serde::Deserialize;
9
10use super::events::{
11 AccountDeleted, OtherDevicesLoggedOut, PasswordChanged, ProfileUpdated, announce,
12};
13use super::module::{Settings, go, label, texts};
14use super::{User, change_password, logout_other_devices, verification};
15use crate::db::Model;
16use crate::i18n::Lang;
17use crate::validation::{Errors, Validate, ValidationError, Validator};
18use crate::{AppState, AuthUser, Htmx, Result, Routes, Session, View, context, view};
19
20const CONFIRMED_AT: &str = "_password_confirmed_at";
22pub(crate) const CONFIRM_FOR: u64 = 3 * 60 * 60;
24const CONFIRM_INTENDED: &str = "_password_confirm_intended";
25
26pub(super) fn routes() -> Routes {
27 Routes::new()
28 .get("/account", show)
29 .name("account.show")
30 .put("/account/profile", update_profile)
31 .name("account.profile")
32 .put("/account/password", update_password)
33 .name("account.password")
34 .post("/account/logout-others", logout_others)
35 .name("account.logout_others")
36 .delete("/account", destroy)
37 .name("account.destroy")
38 .require_auth()
39}
40
41fn unix_now() -> u64 {
42 crate::clock::unix_secs().max(0) as u64
43}
44
45pub(crate) fn mark_confirmed(session: &Session) -> Result {
47 session.put(CONFIRMED_AT, unix_now())
48}
49
50pub(crate) fn confirmed_destination(session: &Session) -> String {
52 session
53 .pull::<String>(CONFIRM_INTENDED)
54 .filter(|path| crate::htmx::is_local_path(path))
55 .unwrap_or_else(|| "/".into())
56}
57
58pub(crate) fn recently_confirmed(session: &Session) -> bool {
60 session
61 .get::<u64>(CONFIRMED_AT)
62 .is_some_and(|at| unix_now().saturating_sub(at) < CONFIRM_FOR)
63}
64
65pub(crate) async fn require_password_confirmed(
68 req: axum::extract::Request,
69 next: axum::middleware::Next,
70) -> Response {
71 let Some(session) = req.extensions().get::<Session>().cloned() else {
72 return next.run(req).await;
73 };
74 if recently_confirmed(&session) {
75 return next.run(req).await;
76 }
77 let back = if req.method() == axum::http::Method::GET {
81 req.uri().path_and_query().map(|p| p.as_str().to_owned())
82 } else {
83 crate::htmx::same_site_referer(req.headers())
84 };
85 if let Some(back) = back {
86 let _ = session.put(CONFIRM_INTENDED, back);
87 }
88 let confirm = req
89 .extensions()
90 .get::<AppState>()
91 .and_then(|state| state.url("password.confirm", &[]).ok())
92 .unwrap_or_else(|| "/confirm-password".into());
93 if crate::Htmx::from_headers(req.headers()).request {
94 return crate::HxRedirect(confirm).into_response();
95 }
96 Redirect::to(&confirm).into_response()
97}
98
99pub(super) async fn show_confirm(State(state): State<AppState>, lang: Lang) -> View {
100 view(
101 "renox/auth/confirm-password.html",
102 context! { text => texts(&lang), layout => super::signed_in_layout(&state) },
103 )
104}
105
106#[derive(Deserialize)]
107pub(super) struct ConfirmForm {
108 password: String,
109}
110
111impl Validate for ConfirmForm {
112 fn rules(&self, v: &mut Validator) {
113 let password = label(v, "password");
114 v.field("password", &self.password)
115 .fallback_label(password)
116 .required();
117 }
118}
119
120async fn check_password(
123 user: &User,
124 password: &str,
125 field: &str,
126 lang: &Lang,
127) -> std::result::Result<(), crate::Error> {
128 if user.check_password(password).await {
129 return Ok(());
130 }
131 let template = crate::validation::template_for(Some(&lang.texts()), "current_password");
132 let name = lang
135 .texts()
136 .get(&format!("renox.validation.attributes.{field}"))
137 .cloned()
138 .unwrap_or_else(|| match field {
139 "current_password" => "current password".to_owned(),
140 _ => "password".to_owned(),
141 });
142 let mut errors = Errors::new();
143 errors.add(field, crate::validation::render(&template, &name, &[]));
144 Err(ValidationError::new(errors).into())
145}
146
147pub(super) async fn confirm(
148 user: AuthUser,
149 session: Session,
150 htmx: Htmx,
151 lang: Lang,
152 crate::validation::Valid(form): crate::validation::Valid<ConfirmForm>,
153) -> Result<Response> {
154 check_password(user.user(), &form.password, "password", &lang).await?;
155 mark_confirmed(&session)?;
156 Ok(go(&htmx, confirmed_destination(&session)))
157}
158
159pub(crate) struct AccountSection {
161 template: String,
162 pub(crate) order: i32,
163 data: SectionFn,
164}
165
166type SectionFn = Arc<
167 dyn Fn(
168 User,
169 AppState,
170 )
171 -> std::pin::Pin<Box<dyn std::future::Future<Output = Result<serde_json::Value>> + Send>>
172 + Send
173 + Sync,
174>;
175
176pub(crate) fn section<F, Fut>(template: &str, order: i32, data: F) -> AccountSection
177where
178 F: Fn(User, AppState) -> Fut + Send + Sync + 'static,
179 Fut: std::future::Future<Output = Result<serde_json::Value>> + Send + 'static,
180{
181 AccountSection {
182 template: template.to_owned(),
183 order,
184 data: Arc::new(move |user, state| Box::pin(data(user, state))),
185 }
186}
187
188async fn show(
189 Extension(settings): Extension<Arc<Settings>>,
190 State(state): State<AppState>,
191 user: AuthUser,
192 lang: Lang,
193) -> Result<View> {
194 let registered: Vec<(String, SectionFn)> = state
197 .account_sections
198 .iter()
199 .map(|section| (section.template.clone(), section.data.clone()))
200 .collect();
201 let mut sections = Vec::with_capacity(registered.len());
202 for (template, data) in registered {
203 let data = data(user.user().clone(), state.clone()).await?;
204 sections.push(context! { template, data });
205 }
206 Ok(view(
207 "renox/auth/account.html",
208 context! {
209 text => texts(&lang),
210 user => user.user(),
211 has_password => user.has_password(),
212 verify_email => settings.verify_email,
213 sections,
214 layout => super::signed_in_layout(&state),
215 },
216 ))
217}
218
219#[derive(Deserialize)]
220struct ProfileForm {
221 name: String,
222 email: String,
223}
224
225impl Validate for ProfileForm {
226 fn rules(&self, v: &mut Validator) {
227 let name = label(v, "name");
228 v.field("name", &self.name)
229 .fallback_label(name)
230 .required()
231 .max(255);
232 v.field("email", &super::user::normalize_email(&self.email))
233 .required()
234 .email()
235 .max(255);
236 }
237}
238
239async fn update_profile(
240 Extension(settings): Extension<Arc<Settings>>,
241 State(state): State<AppState>,
242 user: AuthUser,
243 session: Session,
244 htmx: Htmx,
245 lang: Lang,
246 req: axum::extract::Request,
247) -> Result<Response> {
248 let id = user.id;
249 let validated = crate::validation::extract::validate_request(
250 req,
251 &state,
252 move |form: &ProfileForm, _, v| {
253 v.field("email", &super::user::normalize_email(&form.email))
254 .unique("users", "email")
255 .ignore(id);
256 },
257 )
258 .await;
259 let form = match validated {
260 Ok((form, _)) => form,
261 Err(rejection) => return Ok(rejection),
262 };
263 let mut me = user.user().clone();
264 let email = super::user::normalize_email(&form.email);
265 let email_changed = email != me.email;
266 me.name = form.name.trim().to_owned();
267 if email_changed {
268 me.email = email;
269 if settings.verify_email {
270 me.email_verified_at = None;
271 }
272 }
273 me.save(&state.db).await?;
274 if email_changed && settings.verify_email {
275 verification::send_verification(&state, &me).await?;
276 }
277 let event = ProfileUpdated {
278 user_id: me.id,
279 email_changed,
280 };
281 announce(&state, event).await;
282 session.flash("status", &texts(&lang)["profile_saved"])?;
283 Ok(go(&htmx, state.url("account.show", &[])?))
284}
285
286#[derive(Deserialize)]
287struct PasswordForm {
288 #[serde(default)]
290 current_password: String,
291 password: String,
292 password_confirmation: Option<String>,
293}
294
295impl Validate for PasswordForm {
296 fn rules(&self, _v: &mut Validator) {}
297}
298
299#[derive(Deserialize)]
302struct PasswordCheck {
303 #[serde(default)]
304 password: String,
305}
306
307impl Validate for PasswordCheck {
308 fn rules(&self, _v: &mut Validator) {}
309}
310
311fn needs_confirmation(
316 state: &AppState,
317 session: &Session,
318 user: &User,
319 htmx: &Htmx,
320) -> Option<Response> {
321 if user.has_password() || recently_confirmed(session) {
322 return None;
323 }
324 if let Ok(account) = state.url("account.show", &[]) {
325 let _ = session.put(CONFIRM_INTENDED, account);
326 }
327 let confirm = state
328 .url("password.confirm", &[])
329 .unwrap_or_else(|_| "/confirm-password".into());
330 Some(go(htmx, confirm))
331}
332
333async fn check_typed(user: &User, typed: &str, field: &str, lang: &Lang) -> Result {
335 if user.has_password() {
336 check_password(user, typed, field, lang).await?;
337 }
338 Ok(())
339}
340
341async fn password_check(
343 state: &AppState,
344 user: &User,
345 req: axum::extract::Request,
346) -> std::result::Result<PasswordCheck, Box<Response>> {
347 let has_password = user.has_password();
348 crate::validation::extract::validate_request(req, state, move |form: &PasswordCheck, _, v| {
349 if has_password {
350 let password = label(v, "password");
351 v.field("password", &form.password)
352 .fallback_label(password)
353 .required();
354 }
355 })
356 .await
357 .map(|(form, _)| form)
358 .map_err(Box::new)
359}
360
361async fn update_password(
362 Extension(settings): Extension<Arc<Settings>>,
363 State(state): State<AppState>,
364 user: AuthUser,
365 session: Session,
366 htmx: Htmx,
367 lang: Lang,
368 req: axum::extract::Request,
369) -> Result<Response> {
370 if let Some(confirm) = needs_confirmation(&state, &session, user.user(), &htmx) {
371 return Ok(confirm);
372 }
373 let policy = settings.password.clone();
374 let has_password = user.has_password();
375 let validated = crate::validation::extract::validate_request(
376 req,
377 &state,
378 move |form: &PasswordForm, _, v| {
379 if has_password {
380 let current = label(v, "current_password");
381 v.field("current_password", &form.current_password)
382 .fallback_label(current)
383 .required();
384 }
385 let password = label(v, "password");
386 v.field("password", &form.password)
387 .fallback_label(password)
388 .required()
389 .password(&policy)
390 .confirmed(&form.password_confirmation);
391 },
392 )
393 .await;
394 let form = match validated {
395 Ok((form, _)) => form,
396 Err(rejection) => return Ok(rejection),
397 };
398 check_typed(
399 user.user(),
400 &form.current_password,
401 "current_password",
402 &lang,
403 )
404 .await?;
405 let mut me = user.user().clone();
406 change_password(&state.db, &session, &mut me, &form.password).await?;
407 mark_confirmed(&session)?;
408 announce(&state, PasswordChanged { user_id: me.id }).await;
409 session.flash("status", &texts(&lang)["password_changed"])?;
410 Ok(go(&htmx, state.url("account.show", &[])?))
411}
412
413async fn logout_others(
414 State(state): State<AppState>,
415 user: AuthUser,
416 session: Session,
417 htmx: Htmx,
418 lang: Lang,
419 req: axum::extract::Request,
420) -> Result<Response> {
421 if let Some(confirm) = needs_confirmation(&state, &session, user.user(), &htmx) {
422 return Ok(confirm);
423 }
424 let form = match password_check(&state, user.user(), req).await {
425 Ok(form) => form,
426 Err(rejection) => return Ok(*rejection),
427 };
428 check_typed(user.user(), &form.password, "password", &lang).await?;
429 logout_other_devices(&state.db, &session, user.user()).await?;
430 announce(&state, OtherDevicesLoggedOut { user_id: user.id }).await;
431 session.flash("status", &texts(&lang)["other_devices_logged_out"])?;
432 Ok(go(&htmx, state.url("account.show", &[])?))
433}
434
435async fn destroy(
436 State(state): State<AppState>,
437 user: AuthUser,
438 session: Session,
439 htmx: Htmx,
440 lang: Lang,
441 req: axum::extract::Request,
442) -> Result<Response> {
443 if let Some(confirm) = needs_confirmation(&state, &session, user.user(), &htmx) {
444 return Ok(confirm);
445 }
446 let form = match password_check(&state, user.user(), req).await {
447 Ok(form) => form,
448 Err(rejection) => return Ok(*rejection),
449 };
450 check_typed(user.user(), &form.password, "password", &lang).await?;
451 user.delete_account(&state.db).await?;
452 session.flush();
453 let event = AccountDeleted {
454 user_id: user.id,
455 email: user.email.clone(),
456 };
457 announce(&state, event).await;
458 Ok(go(
459 &htmx,
460 state.url("home", &[]).unwrap_or_else(|_| "/".into()),
461 ))
462}
463
464impl User {
465 pub async fn delete_account(&self, db: &crate::db::Db) -> Result {
469 let mut tx = db.begin().await?;
470 crate::db::sql("DELETE FROM grid_preferences WHERE user_id = ?")
473 .bind(self.id)
474 .execute(&mut tx)
475 .await?;
476 crate::db::sql("DELETE FROM users WHERE id = ?")
477 .bind(self.id)
478 .execute(&mut tx)
479 .await?;
480 tx.commit().await?;
481 Ok(())
482 }
483}