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_branding_urls, 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_branding_urls(&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    let outcome = authenticate_member(
105        tenant.pool(),
106        &tenant.org.slug,
107        &request,
108        "member",
109        &form.identifier,
110        &form.password,
111    )
112    .await;
113    match outcome {
114        Ok(user) => {
115            let cookie = member_auth::mint_cookie(
116                &ctx.session_secret,
117                &user,
118                &tenant.org.slug,
119                MEMBER_SESSION_TTL,
120            );
121            redirect_with_cookie(&next, &cookie)
122        }
123        Err(e) => {
124            let reason = match e {
125                MemberLoginError::Invalid => "invalid_credentials",
126                MemberLoginError::Refused(_) => "throttled",
127            };
128            Redirect::to(&format!(
129                "/members/login?error={reason}&next={}",
130                crate::view_restriction_guard::url_encode_path(&next)
131            ))
132            .into_response()
133        }
134    }
135}
136
137// ===================================================================
138// Signup (self-service email/password registration)
139// ===================================================================
140
141#[derive(serde::Deserialize)]
142pub(crate) struct MemberSignupForm {
143    #[serde(default)]
144    pub email: String,
145    #[serde(default)]
146    pub password: String,
147    #[serde(default)]
148    pub password_confirm: String,
149    #[serde(default)]
150    pub display_name: String,
151    #[serde(default)]
152    pub next: String,
153}
154
155/// GET `/members/signup` — render the self-service registration form.
156pub(crate) async fn member_signup_form(
157    State(state): State<AdminState>,
158    headers: HeaderMap,
159    member: CurrentMember,
160    tenant: Tenant,
161    Query(q): Query<HashMap<String, String>>,
162) -> Result<Response, AdminError> {
163    let next = sanitize_next(q.get("next").map(String::as_str).unwrap_or("/"));
164    if member.0.is_some() {
165        return Ok(Redirect::to(&next).into_response());
166    }
167    let mut ctx = Context::new();
168    ctx.insert("action", "/members/signup");
169    ctx.insert("login_url", "/members/login");
170    ctx.insert("next", &next);
171    if let Some(err) = q.get("error") {
172        ctx.insert("error", err);
173    }
174    add_branding_urls(&mut ctx, &tenant).await;
175    render_with_csrf(&state, &headers, "rcms_admin/member_signup.html", &mut ctx)
176}
177
178/// POST `/members/signup` — validate, create a new member
179/// (`is_superuser = false`, no tier — an admin assigns roles later),
180/// and sign them straight in with a member cookie.
181pub(crate) async fn member_signup_submit(
182    Extension(ctx): Extension<Arc<TenantContext>>,
183    tenant: Tenant,
184    Form(form): Form<MemberSignupForm>,
185) -> Response {
186    let next = sanitize_next(&form.next);
187    let email = form.email.trim().to_ascii_lowercase();
188
189    let bounce = |reason: &str| {
190        Redirect::to(&format!(
191            "/members/signup?error={reason}&next={}",
192            crate::view_restriction_guard::url_encode_path(&next)
193        ))
194        .into_response()
195    };
196
197    if email.is_empty() || !email.contains('@') {
198        return bounce("invalid_email");
199    }
200    if form.password.len() < 8 {
201        return bounce("weak_password");
202    }
203    if form.password != form.password_confirm {
204        return bounce("password_mismatch");
205    }
206    match email_taken(tenant.pool(), &email).await {
207        Ok(true) => return bounce("email_taken"),
208        Ok(false) => {}
209        Err(_) => return bounce("server_error"),
210    }
211
212    let display_name = if form.display_name.trim().is_empty() {
213        email.split('@').next().unwrap_or(&email).to_owned()
214    } else {
215        form.display_name.trim().to_owned()
216    };
217
218    match create_member(tenant.pool(), &email, &form.password, &display_name).await {
219        Ok(user) => {
220            let cookie = member_auth::mint_cookie(
221                &ctx.session_secret,
222                &user,
223                &tenant.org.slug,
224                MEMBER_SESSION_TTL,
225            );
226            redirect_with_cookie(&next, &cookie)
227        }
228        Err(e) => {
229            tracing::error!(target: "rustango_cms::members", error = %e, "member signup failed");
230            bounce("server_error")
231        }
232    }
233}
234
235/// POST `/members/logout` — expire the member session and return to
236/// the site root.
237pub(crate) async fn member_logout(
238    member: CurrentMember,
239    tenant: Result<Tenant, TenantRejection>,
240    request: LoginRequest,
241) -> Response {
242    if let (Some(user), Ok(tenant)) = (member.0, tenant) {
243        let entry = security_log::Entry::new(security_log::EVENT_LOGOUT, "member", &request.meta)
244            .user(user.id.get().copied(), &user.username);
245        security_log::record(tenant.pool(), &tenant.org.slug, entry).await;
246    }
247    redirect_with_cookie("/", &member_auth::clear_cookie())
248}
249
250// ===================================================================
251// Helpers
252// ===================================================================
253
254/// Why a member sign-in was refused.
255#[derive(Debug)]
256pub enum MemberLoginError {
257    /// Too many attempts at this account or from this address, or the
258    /// password-hashing queue is full. The password was not checked.
259    Refused(LoginRefused),
260    /// Unknown name, wrong password, or a disabled account — one answer
261    /// for all three, so the response tells nothing about the account.
262    Invalid,
263}
264
265/// Sign a member in by username OR (lowercased) email + password, in
266/// `tenant_slug` (the tenant `pool` belongs to).
267///
268/// The attempt goes through the framework's login gate in the tenant
269/// scope, so the account shares one lock with the admin `/login`, and is
270/// written to the [`security_log`] as `source`. Runs a dummy verify on
271/// the unknown-account branch so response timing doesn't reveal whether
272/// the identifier exists.
273///
274/// # Errors
275/// [`MemberLoginError`].
276pub async fn authenticate_member(
277    pool: &rustango::sql::Pool,
278    tenant_slug: &str,
279    request: &LoginRequest,
280    source: &'static str,
281    identifier: &str,
282    password: &str,
283) -> Result<User, MemberLoginError> {
284    let ident = identifier.trim();
285    if ident.is_empty() || password.is_empty() {
286        return Err(MemberLoginError::Invalid);
287    }
288    let scope = LoginScope::Tenant(tenant_slug.to_owned());
289    let mut attempt = login_throttle::shared()
290        .begin(&scope, &request.ip, ident)
291        .await
292        .map_err(MemberLoginError::Refused)?;
293    let found = find_member(pool, ident).await;
294    if let Some(user) = &found {
295        attempt.resolve(&user.username).await.map_err(MemberLoginError::Refused)?;
296    }
297    // Verify before checking `active` (#770): returning at once for a
298    // disabled account made its response measurably faster than an active
299    // one's or an unknown one's (which pays `verify_dummy`), so timing told
300    // an attacker the account exists but is disabled.
301    let password_ok = match &found {
302        Some(user) => {
303            matches!(crate::passwords::verify(password, &user.password_hash).await, Ok(true))
304        }
305        None => {
306            crate::passwords::verify_dummy(password).await;
307            false
308        }
309    };
310    let active = found.as_ref().is_some_and(|u| u.active);
311    let user_id = found.as_ref().and_then(|u| u.id.get().copied());
312    let username = found.as_ref().map_or(ident, |u| u.username.as_str());
313    if password_ok && active {
314        attempt.succeeded().await;
315        let entry = security_log::Entry::new(security_log::EVENT_LOGIN, source, &request.meta)
316            .user(user_id, username);
317        security_log::record(pool, tenant_slug, entry).await;
318        return found.ok_or(MemberLoginError::Invalid);
319    }
320    attempt.failed().await;
321    let reason = if password_ok { "inactive" } else { "invalid_credentials" };
322    let entry = security_log::Entry::new(security_log::EVENT_LOGIN_FAILED, source, &request.meta)
323        .user(user_id, username)
324        .reason(reason);
325    security_log::record(pool, tenant_slug, entry).await;
326    // The gate refuses a locked account before it gets here, so a lock
327    // seen now is the one this failure set.
328    if security_log::is_locked(tenant_slug, &[ident, username]).await {
329        let entry = security_log::Entry::new(security_log::EVENT_LOCKOUT, source, &request.meta)
330            .user(user_id, username);
331        security_log::record(pool, tenant_slug, entry).await;
332    }
333    Err(MemberLoginError::Invalid)
334}
335
336/// The `rustango_users` row named `ident` (username first, then the
337/// lowercased email).
338async fn find_member(pool: &rustango::sql::Pool, ident: &str) -> Option<User> {
339    use rustango::core::Column as _;
340    use rustango::sql::FetcherPool as _;
341    let by_name: Vec<User> = User::objects()
342        .where_(User::username.eq(ident.to_owned()))
343        .limit(1)
344        .fetch(pool)
345        .await
346        .unwrap_or_default();
347    if let Some(user) = by_name.into_iter().next() {
348        return Some(user);
349    }
350    User::objects()
351        .filter("email", ident.to_ascii_lowercase())
352        .limit(1)
353        .fetch(pool)
354        .await
355        .unwrap_or_default()
356        .into_iter()
357        .next()
358}
359
360/// True when a `rustango_users` row already carries this (lowercased)
361/// email.
362async fn email_taken(pool: &rustango::sql::Pool, email: &str) -> Result<bool, AdminError> {
363    use rustango::sql::FetcherPool as _;
364    let rows: Vec<User> = User::objects()
365        .filter("email", email.to_owned())
366        .limit(1)
367        .fetch(pool)
368        .await?;
369    Ok(!rows.is_empty())
370}
371
372/// Insert a new member row (username = email; unusable-until-set tiers
373/// are granted later by an admin). Returns the new user id.
374async fn create_member(
375    pool: &rustango::sql::Pool,
376    email: &str,
377    password: &str,
378    display_name: &str,
379) -> Result<User, AdminError> {
380    use rustango::sql::Auto;
381    let mut user = User {
382        id: Auto::Unset,
383        username: email.to_owned(),
384        password_hash: crate::passwords::hash(password).await
385            .map_err(|e| AdminError::Validation(format!("password hashing failed: {e}")))?,
386        email: Some(email.to_owned()),
387        is_superuser: false,
388        active: true,
389        created_at: chrono::Utc::now(),
390        data: serde_json::json!({ "display_name": display_name }),
391        password_changed_at: None,
392        sessions_revoked_at: None,
393    };
394    user.insert_pool(pool).await?;
395    if user.id.get().is_none() {
396        return Err(AdminError::Validation("member insert returned no id".to_owned()));
397    }
398    Ok(user)
399}
400
401/// Reject open-redirect-shaped `next` values: only a single-slash,
402/// same-origin path is honored, everything else falls back to `/`.
403fn sanitize_next(next: &str) -> String {
404    rustango::auth_decorators::safe_next(next).unwrap_or_else(|| "/".to_owned())
405}
406
407/// A 303 redirect that also stamps a `Set-Cookie` header.
408fn redirect_with_cookie(location: &str, set_cookie: &str) -> Response {
409    let mut resp = Redirect::to(location).into_response();
410    if let Ok(v) = HeaderValue::from_str(set_cookie) {
411        resp.headers_mut().append(header::SET_COOKIE, v);
412    }
413    resp
414}
415
416#[cfg(test)]
417mod tests {
418    use super::sanitize_next;
419
420    #[test]
421    fn next_stays_on_site() {
422        assert_eq!(sanitize_next("/members/area?x=1"), "/members/area?x=1");
423        for hostile in ["https://evil.test", "//evil.test", "/\\evil.test", "/%5Cevil.test", "/%2F/evil.test", "/\t/evil.test"] {
424            assert_eq!(sanitize_next(hostile), "/", "{hostile:?}");
425        }
426    }
427}