Skip to main content

rustango_cms/admin/
members.rs

1//! Public **members area** authentication (#members).
2//!
3//! A member is an end-user of the public site — a `rustango_users` row
4//! distinguished from an admin only by the cookie that authenticates it
5//! (`rustango_member_session` vs the admin `rustango_tenant_session`).
6//! Members sign in through **any** method — email/password (this
7//! module), or SSO / social (the framework's [`member_sso_router`],
8//! mounted by the host at `/members/auth`). Every method mints the same
9//! member session via [`member_auth::mint_cookie`], so the page-gating
10//! guard ([`crate::view_restriction_guard`]) treats them uniformly.
11//!
12//! These routes live in [`super::public_router`] (unauthenticated, but
13//! merged into the host `api` router so their POSTs are CSRF-protected
14//! like every other admin form) and render through the shared admin
15//! Tera with [`super::handlers::render_with_csrf`].
16//!
17//! [`member_sso_router`]: rustango::tenancy::member_auth::member_sso_router
18//! [`member_auth::mint_cookie`]: rustango::tenancy::member_auth::mint_cookie
19
20use std::collections::HashMap;
21use std::sync::Arc;
22
23use axum::extract::{Form, Query, State};
24use axum::http::{header, HeaderMap, HeaderValue};
25use axum::response::{IntoResponse, Redirect, Response};
26use axum::Extension;
27use tera::Context;
28
29use rustango::extractors::{Tenant, TenantContext, TenantRejection};
30use rustango::login_throttle::{self, LoginRefused, LoginScope};
31use rustango::tenancy::auth::User;
32use rustango::tenancy::member_auth::{self, CurrentMember};
33
34use super::handlers::{add_auth_chrome, render_with_csrf};
35use crate::security_log::{self, LoginRequest};
36use super::{AdminError, AdminState};
37
38/// Member session lifetime — 7 days, matching the framework's
39/// [`rustango::tenancy::member_auth::MemberAuthConfig`] default.
40pub(crate) const MEMBER_SESSION_TTL: i64 = 7 * 24 * 60 * 60;
41
42/// SSO buttons on the member login list the tenant's enabled providers
43/// pointing at the member callback base (where the host mounts
44/// [`member_sso_router`](rustango::tenancy::member_auth::member_sso_router)).
45const MEMBER_SSO_BASE: &str = "/members/auth";
46
47// ===================================================================
48// Login (email/username + password)
49// ===================================================================
50
51#[derive(serde::Deserialize)]
52pub(crate) struct MemberLoginForm {
53    #[serde(default)]
54    pub identifier: String,
55    #[serde(default)]
56    pub password: String,
57    #[serde(default)]
58    pub next: String,
59}
60
61/// GET `/members/login` — render the member sign-in page (password form
62/// + one button per enabled SSO/social provider). An already-signed-in
63/// member is bounced straight to the landing / `?next` destination.
64pub(crate) async fn member_login_form(
65    State(state): State<AdminState>,
66    headers: HeaderMap,
67    member: CurrentMember,
68    tenant: Tenant,
69    Query(q): Query<HashMap<String, String>>,
70) -> Result<Response, AdminError> {
71    let next = sanitize_next(q.get("next").map(String::as_str).unwrap_or("/"));
72    if member.0.is_some() {
73        return Ok(Redirect::to(&next).into_response());
74    }
75    let mut ctx = Context::new();
76    ctx.insert("action", "/members/login");
77    ctx.insert("signup_url", "/members/signup");
78    ctx.insert("next", &next);
79    if let Some(err) = q.get("error") {
80        ctx.insert("error", err);
81    }
82    if let Some(err) = q.get("sso_error") {
83        ctx.insert("sso_error", err);
84    }
85    let sso_providers =
86        rustango::admin::sso_provider::list_enabled(tenant.pool(), MEMBER_SSO_BASE).await;
87    ctx.insert("sso_enabled", &!sso_providers.is_empty());
88    ctx.insert("sso_providers", &sso_providers);
89    add_auth_chrome(&mut ctx, &tenant).await;
90    render_with_csrf(&state, &headers, "rcms_admin/member_login.html", &mut ctx)
91}
92
93/// POST `/members/login` — verify credentials against `rustango_users`
94/// (by username OR email) and mint the member session cookie. Failures
95/// bounce back to the form with a generic error (never leaking whether
96/// the account exists).
97pub(crate) async fn member_login_submit(
98    Extension(ctx): Extension<Arc<TenantContext>>,
99    tenant: Tenant,
100    request: LoginRequest,
101    Form(form): Form<MemberLoginForm>,
102) -> Response {
103    let next = sanitize_next(&form.next);
104    // The throttle and the lock-out are bound to the site by org id too, so
105    // a later site reusing the slug inherits neither.
106    let Some(site) = rustango::tenancy::TenantSlug::of(&tenant.org) else {
107        return (axum::http::StatusCode::NOT_FOUND, "unknown site").into_response();
108    };
109    let outcome = authenticate_member(
110        tenant.pool(),
111        &site,
112        &request,
113        "member",
114        &form.identifier,
115        &form.password,
116    )
117    .await;
118    match outcome {
119        Ok(user) => signed_in_redirect(&ctx, &user, &tenant.org, &next),
120        Err(e) => {
121            let reason = match e {
122                MemberLoginError::Invalid => "invalid_credentials",
123                MemberLoginError::Refused(_) => "throttled",
124            };
125            Redirect::to(&format!(
126                "/members/login?error={reason}&next={}",
127                crate::view_restriction_guard::url_encode_path(&next)
128            ))
129            .into_response()
130        }
131    }
132}
133
134// ===================================================================
135// Signup (self-service email/password registration)
136// ===================================================================
137
138#[derive(serde::Deserialize)]
139pub(crate) struct MemberSignupForm {
140    #[serde(default)]
141    pub email: String,
142    #[serde(default)]
143    pub password: String,
144    #[serde(default)]
145    pub password_confirm: String,
146    #[serde(default)]
147    pub display_name: String,
148    #[serde(default)]
149    pub next: String,
150}
151
152/// GET `/members/signup` — render the self-service registration form.
153pub(crate) async fn member_signup_form(
154    State(state): State<AdminState>,
155    headers: HeaderMap,
156    member: CurrentMember,
157    tenant: Tenant,
158    Query(q): Query<HashMap<String, String>>,
159) -> Result<Response, AdminError> {
160    let next = sanitize_next(q.get("next").map(String::as_str).unwrap_or("/"));
161    if member.0.is_some() {
162        return Ok(Redirect::to(&next).into_response());
163    }
164    let mut ctx = Context::new();
165    ctx.insert("action", "/members/signup");
166    ctx.insert("login_url", "/members/login");
167    ctx.insert("next", &next);
168    if let Some(err) = q.get("error") {
169        ctx.insert("error", err);
170    }
171    add_auth_chrome(&mut ctx, &tenant).await;
172    render_with_csrf(&state, &headers, "rcms_admin/member_signup.html", &mut ctx)
173}
174
175/// POST `/members/signup` — validate, create a new member
176/// (`is_superuser = false`, no tier — an admin assigns roles later),
177/// and sign them straight in with a member cookie.
178pub(crate) async fn member_signup_submit(
179    Extension(ctx): Extension<Arc<TenantContext>>,
180    tenant: Tenant,
181    Form(form): Form<MemberSignupForm>,
182) -> Response {
183    let next = sanitize_next(&form.next);
184    let email = form.email.trim().to_ascii_lowercase();
185
186    let bounce = |reason: &str| {
187        Redirect::to(&format!(
188            "/members/signup?error={reason}&next={}",
189            crate::view_restriction_guard::url_encode_path(&next)
190        ))
191        .into_response()
192    };
193
194    if email.is_empty() || !email.contains('@') {
195        return bounce("invalid_email");
196    }
197    if form.password.len() < 8 {
198        return bounce("weak_password");
199    }
200    if form.password != form.password_confirm {
201        return bounce("password_mismatch");
202    }
203    match email_taken(tenant.pool(), &email).await {
204        Ok(true) => return bounce("email_taken"),
205        Ok(false) => {}
206        Err(_) => return bounce("server_error"),
207    }
208
209    let display_name = if form.display_name.trim().is_empty() {
210        email.split('@').next().unwrap_or(&email).to_owned()
211    } else {
212        form.display_name.trim().to_owned()
213    };
214
215    match create_member(tenant.pool(), &email, &form.password, &display_name).await {
216        Ok(user) => signed_in_redirect(&ctx, &user, &tenant.org, &next),
217        Err(e) => {
218            tracing::error!(target: "rustango_cms::members", error = %e, "member signup failed");
219            bounce("server_error")
220        }
221    }
222}
223
224/// POST `/members/logout` — expire the member session and return to
225/// the site root.
226pub(crate) async fn member_logout(
227    member: CurrentMember,
228    tenant: Result<Tenant, TenantRejection>,
229    request: LoginRequest,
230) -> Response {
231    if let (Some(user), Ok(tenant)) = (member.0, tenant) {
232        let entry = security_log::Entry::new(security_log::EVENT_LOGOUT, "member", &request.meta)
233            .user(user.id.get().copied(), &user.username);
234        security_log::record(tenant.pool(), &tenant.org.slug, entry).await;
235    }
236    redirect_with_cookie("/", &member_auth::clear_cookie())
237}
238
239// ===================================================================
240// Helpers
241// ===================================================================
242
243/// Why a member sign-in was refused.
244#[derive(Debug)]
245pub enum MemberLoginError {
246    /// Too many attempts at this account or from this address, or the
247    /// password-hashing queue is full. The password was not checked.
248    Refused(LoginRefused),
249    /// Unknown name, wrong password, or a disabled account — one answer
250    /// for all three, so the response tells nothing about the account.
251    Invalid,
252}
253
254/// Sign a member in by username OR (lowercased) email + password, in
255/// `tenant_slug` (the tenant `pool` belongs to).
256///
257/// The attempt goes through the framework's login gate in the tenant
258/// scope, so the account shares one lock with the admin `/login`, and is
259/// written to the [`security_log`] as `source`. Runs a dummy verify on
260/// the unknown-account branch so response timing doesn't reveal whether
261/// the identifier exists.
262///
263/// # Errors
264/// [`MemberLoginError`].
265pub async fn authenticate_member(
266    pool: &rustango::sql::Pool,
267    site: &rustango::tenancy::TenantSlug,
268    request: &LoginRequest,
269    source: &'static str,
270    identifier: &str,
271    password: &str,
272) -> Result<User, MemberLoginError> {
273    let ident = identifier.trim();
274    if ident.is_empty() || password.is_empty() {
275        return Err(MemberLoginError::Invalid);
276    }
277    let scope = LoginScope::Tenant(site.clone());
278    let mut attempt = login_throttle::shared()
279        .begin(&scope, &request.ip, ident)
280        .await
281        .map_err(MemberLoginError::Refused)?;
282    let found = find_member(pool, ident).await;
283    if let Some(user) = &found {
284        attempt.resolve(&user.username).await.map_err(MemberLoginError::Refused)?;
285    }
286    // Verify before checking `active` (#770): returning at once for a
287    // disabled account made its response measurably faster than an active
288    // one's or an unknown one's (which pays `verify_dummy`), so timing told
289    // an attacker the account exists but is disabled.
290    let password_ok = match &found {
291        Some(user) => {
292            matches!(crate::passwords::verify(password, &user.password_hash).await, Ok(true))
293        }
294        None => {
295            crate::passwords::verify_dummy(password).await;
296            false
297        }
298    };
299    let active = found.as_ref().is_some_and(|u| u.active);
300    let user_id = found.as_ref().and_then(|u| u.id.get().copied());
301    let username = found.as_ref().map_or(ident, |u| u.username.as_str());
302    if password_ok && active {
303        attempt.succeeded().await;
304        let entry = security_log::Entry::new(security_log::EVENT_LOGIN, source, &request.meta)
305            .user(user_id, username);
306        security_log::record(pool, &site.slug, entry).await;
307        return found.ok_or(MemberLoginError::Invalid);
308    }
309    attempt.failed().await;
310    let reason = if password_ok { "inactive" } else { "invalid_credentials" };
311    let entry = security_log::Entry::new(security_log::EVENT_LOGIN_FAILED, source, &request.meta)
312        .user(user_id, username)
313        .reason(reason);
314    security_log::record(pool, &site.slug, entry).await;
315    // The gate refuses a locked account before it gets here, so a lock
316    // seen now is the one this failure set.
317    if security_log::is_locked(site, &[ident, username]).await {
318        let entry = security_log::Entry::new(security_log::EVENT_LOCKOUT, source, &request.meta)
319            .user(user_id, username);
320        security_log::record(pool, &site.slug, entry).await;
321    }
322    Err(MemberLoginError::Invalid)
323}
324
325/// The `rustango_users` row named `ident` (username first, then the
326/// lowercased email).
327async fn find_member(pool: &rustango::sql::Pool, ident: &str) -> Option<User> {
328    use rustango::core::Column as _;
329    use rustango::sql::FetcherPool as _;
330    let by_name: Vec<User> = User::objects()
331        .where_(User::username.eq(ident.to_owned()))
332        .limit(1)
333        .fetch(pool)
334        .await
335        .unwrap_or_default();
336    if let Some(user) = by_name.into_iter().next() {
337        return Some(user);
338    }
339    User::objects()
340        .filter("email", ident.to_ascii_lowercase())
341        .limit(1)
342        .fetch(pool)
343        .await
344        .unwrap_or_default()
345        .into_iter()
346        .next()
347}
348
349/// True when a `rustango_users` row already carries this (lowercased)
350/// email.
351async fn email_taken(pool: &rustango::sql::Pool, email: &str) -> Result<bool, AdminError> {
352    use rustango::sql::FetcherPool as _;
353    let rows: Vec<User> = User::objects()
354        .filter("email", email.to_owned())
355        .limit(1)
356        .fetch(pool)
357        .await?;
358    Ok(!rows.is_empty())
359}
360
361/// Insert a new member row (username = email; unusable-until-set tiers
362/// are granted later by an admin). Returns the new user id.
363async fn create_member(
364    pool: &rustango::sql::Pool,
365    email: &str,
366    password: &str,
367    display_name: &str,
368) -> Result<User, AdminError> {
369    use rustango::sql::Auto;
370    let mut user = User {
371        id: Auto::Unset,
372        username: email.to_owned(),
373        password_hash: crate::passwords::hash(password).await
374            .map_err(|e| AdminError::Validation(format!("password hashing failed: {e}")))?,
375        email: Some(email.to_owned()),
376        is_superuser: false,
377        active: true,
378        created_at: chrono::Utc::now(),
379        data: serde_json::json!({ "display_name": display_name }),
380        password_changed_at: None,
381        sessions_revoked_at: None,
382    };
383    user.insert(pool).await?;
384    if user.id.get().is_none() {
385        return Err(AdminError::Validation("member insert returned no id".to_owned()));
386    }
387    Ok(user)
388}
389
390/// Reject open-redirect-shaped `next` values: only a single-slash,
391/// same-origin path is honored, everything else falls back to `/`.
392fn sanitize_next(next: &str) -> String {
393    rustango::auth_decorators::safe_next(next).unwrap_or_else(|| "/".to_owned())
394}
395
396/// Redirect to `next` with a fresh member cookie bound to `org`; a 500 for
397/// an org with no id, which cannot be bound.
398fn signed_in_redirect(
399    ctx: &TenantContext,
400    user: &User,
401    org: &rustango::tenancy::Org,
402    next: &str,
403) -> Response {
404    let Some(tenant) = rustango::tenancy::TenantSlug::of(org) else {
405        return axum::http::StatusCode::INTERNAL_SERVER_ERROR.into_response();
406    };
407    let cookie = member_auth::mint_cookie(&ctx.session_secret, user, &tenant, MEMBER_SESSION_TTL);
408    redirect_with_cookie(next, &cookie)
409}
410
411/// A 303 redirect that also stamps a `Set-Cookie` header.
412fn redirect_with_cookie(location: &str, set_cookie: &str) -> Response {
413    let mut resp = Redirect::to(location).into_response();
414    if let Ok(v) = HeaderValue::from_str(set_cookie) {
415        resp.headers_mut().append(header::SET_COOKIE, v);
416    }
417    resp
418}
419
420#[cfg(test)]
421mod tests {
422    use super::sanitize_next;
423
424    #[test]
425    fn next_stays_on_site() {
426        assert_eq!(sanitize_next("/members/area?x=1"), "/members/area?x=1");
427        for hostile in ["https://evil.test", "//evil.test", "/\\evil.test", "/%5Cevil.test", "/%2F/evil.test", "/\t/evil.test"] {
428            assert_eq!(sanitize_next(hostile), "/", "{hostile:?}");
429        }
430    }
431
432    #[test]
433    fn the_sign_in_page_renders_with_and_without_an_error() {
434        let mut tera = tera::Tera::default();
435        crate::admin::register_templates(&mut tera).expect("admin templates");
436        for error in [None, Some("throttled"), Some("invalid")] {
437            let mut ctx = tera::Context::new();
438            ctx.insert("LANG", "en");
439            ctx.insert("csrf_token", "t");
440            ctx.insert("action", "/members/login");
441            ctx.insert("signup_url", "/members/signup");
442            ctx.insert("next", "/");
443            ctx.insert("sso_enabled", &false);
444            ctx.insert("sso_providers", &Vec::<serde_json::Value>::new());
445            ctx.insert("site_name", "Acme");
446            if let Some(e) = error {
447                ctx.insert("error", e);
448            }
449            let html = tera
450                .render("rcms_admin/member_login.html", &ctx)
451                .unwrap_or_else(|e| panic!("{error:?}: {e:?}"));
452            assert_eq!(html.contains("rcms-error"), error.is_some(), "{error:?}");
453        }
454    }
455
456}