use std::collections::HashMap;
use std::sync::Arc;
use axum::extract::{Form, Query, State};
use axum::http::{header, HeaderMap, HeaderValue};
use axum::response::{IntoResponse, Redirect, Response};
use axum::Extension;
use tera::Context;
use rustango::extractors::{Tenant, TenantContext, TenantRejection};
use rustango::login_throttle::{self, LoginRefused, LoginScope};
use rustango::tenancy::auth::User;
use rustango::tenancy::member_auth::{self, CurrentMember};
use super::handlers::{add_branding_urls, render_with_csrf};
use crate::security_log::{self, LoginRequest};
use super::{AdminError, AdminState};
pub(crate) const MEMBER_SESSION_TTL: i64 = 7 * 24 * 60 * 60;
const MEMBER_SSO_BASE: &str = "/members/auth";
#[derive(serde::Deserialize)]
pub(crate) struct MemberLoginForm {
#[serde(default)]
pub identifier: String,
#[serde(default)]
pub password: String,
#[serde(default)]
pub next: String,
}
pub(crate) async fn member_login_form(
State(state): State<AdminState>,
headers: HeaderMap,
member: CurrentMember,
tenant: Tenant,
Query(q): Query<HashMap<String, String>>,
) -> Result<Response, AdminError> {
let next = sanitize_next(q.get("next").map(String::as_str).unwrap_or("/"));
if member.0.is_some() {
return Ok(Redirect::to(&next).into_response());
}
let mut ctx = Context::new();
ctx.insert("action", "/members/login");
ctx.insert("signup_url", "/members/signup");
ctx.insert("next", &next);
if let Some(err) = q.get("error") {
ctx.insert("error", err);
}
if let Some(err) = q.get("sso_error") {
ctx.insert("sso_error", err);
}
let sso_providers =
rustango::admin::sso_provider::list_enabled(tenant.pool(), MEMBER_SSO_BASE).await;
ctx.insert("sso_enabled", &!sso_providers.is_empty());
ctx.insert("sso_providers", &sso_providers);
add_branding_urls(&mut ctx, &tenant).await;
render_with_csrf(&state, &headers, "rcms_admin/member_login.html", &mut ctx)
}
pub(crate) async fn member_login_submit(
Extension(ctx): Extension<Arc<TenantContext>>,
tenant: Tenant,
request: LoginRequest,
Form(form): Form<MemberLoginForm>,
) -> Response {
let next = sanitize_next(&form.next);
let outcome = authenticate_member(
tenant.pool(),
&tenant.org.slug,
&request,
"member",
&form.identifier,
&form.password,
)
.await;
match outcome {
Ok(user) => {
let cookie = member_auth::mint_cookie(
&ctx.session_secret,
&user,
&tenant.org.slug,
MEMBER_SESSION_TTL,
);
redirect_with_cookie(&next, &cookie)
}
Err(e) => {
let reason = match e {
MemberLoginError::Invalid => "invalid_credentials",
MemberLoginError::Refused(_) => "throttled",
};
Redirect::to(&format!(
"/members/login?error={reason}&next={}",
crate::view_restriction_guard::url_encode_path(&next)
))
.into_response()
}
}
}
#[derive(serde::Deserialize)]
pub(crate) struct MemberSignupForm {
#[serde(default)]
pub email: String,
#[serde(default)]
pub password: String,
#[serde(default)]
pub password_confirm: String,
#[serde(default)]
pub display_name: String,
#[serde(default)]
pub next: String,
}
pub(crate) async fn member_signup_form(
State(state): State<AdminState>,
headers: HeaderMap,
member: CurrentMember,
tenant: Tenant,
Query(q): Query<HashMap<String, String>>,
) -> Result<Response, AdminError> {
let next = sanitize_next(q.get("next").map(String::as_str).unwrap_or("/"));
if member.0.is_some() {
return Ok(Redirect::to(&next).into_response());
}
let mut ctx = Context::new();
ctx.insert("action", "/members/signup");
ctx.insert("login_url", "/members/login");
ctx.insert("next", &next);
if let Some(err) = q.get("error") {
ctx.insert("error", err);
}
add_branding_urls(&mut ctx, &tenant).await;
render_with_csrf(&state, &headers, "rcms_admin/member_signup.html", &mut ctx)
}
pub(crate) async fn member_signup_submit(
Extension(ctx): Extension<Arc<TenantContext>>,
tenant: Tenant,
Form(form): Form<MemberSignupForm>,
) -> Response {
let next = sanitize_next(&form.next);
let email = form.email.trim().to_ascii_lowercase();
let bounce = |reason: &str| {
Redirect::to(&format!(
"/members/signup?error={reason}&next={}",
crate::view_restriction_guard::url_encode_path(&next)
))
.into_response()
};
if email.is_empty() || !email.contains('@') {
return bounce("invalid_email");
}
if form.password.len() < 8 {
return bounce("weak_password");
}
if form.password != form.password_confirm {
return bounce("password_mismatch");
}
match email_taken(tenant.pool(), &email).await {
Ok(true) => return bounce("email_taken"),
Ok(false) => {}
Err(_) => return bounce("server_error"),
}
let display_name = if form.display_name.trim().is_empty() {
email.split('@').next().unwrap_or(&email).to_owned()
} else {
form.display_name.trim().to_owned()
};
match create_member(tenant.pool(), &email, &form.password, &display_name).await {
Ok(user) => {
let cookie = member_auth::mint_cookie(
&ctx.session_secret,
&user,
&tenant.org.slug,
MEMBER_SESSION_TTL,
);
redirect_with_cookie(&next, &cookie)
}
Err(e) => {
tracing::error!(target: "rustango_cms::members", error = %e, "member signup failed");
bounce("server_error")
}
}
}
pub(crate) async fn member_logout(
member: CurrentMember,
tenant: Result<Tenant, TenantRejection>,
request: LoginRequest,
) -> Response {
if let (Some(user), Ok(tenant)) = (member.0, tenant) {
let entry = security_log::Entry::new(security_log::EVENT_LOGOUT, "member", &request.meta)
.user(user.id.get().copied(), &user.username);
security_log::record(tenant.pool(), &tenant.org.slug, entry).await;
}
redirect_with_cookie("/", &member_auth::clear_cookie())
}
#[derive(Debug)]
pub enum MemberLoginError {
Refused(LoginRefused),
Invalid,
}
pub async fn authenticate_member(
pool: &rustango::sql::Pool,
tenant_slug: &str,
request: &LoginRequest,
source: &'static str,
identifier: &str,
password: &str,
) -> Result<User, MemberLoginError> {
let ident = identifier.trim();
if ident.is_empty() || password.is_empty() {
return Err(MemberLoginError::Invalid);
}
let scope = LoginScope::Tenant(tenant_slug.to_owned());
let mut attempt = login_throttle::shared()
.begin(&scope, &request.ip, ident)
.await
.map_err(MemberLoginError::Refused)?;
let found = find_member(pool, ident).await;
if let Some(user) = &found {
attempt.resolve(&user.username).await.map_err(MemberLoginError::Refused)?;
}
let password_ok = match &found {
Some(user) => {
matches!(crate::passwords::verify(password, &user.password_hash).await, Ok(true))
}
None => {
crate::passwords::verify_dummy(password).await;
false
}
};
let active = found.as_ref().is_some_and(|u| u.active);
let user_id = found.as_ref().and_then(|u| u.id.get().copied());
let username = found.as_ref().map_or(ident, |u| u.username.as_str());
if password_ok && active {
attempt.succeeded().await;
let entry = security_log::Entry::new(security_log::EVENT_LOGIN, source, &request.meta)
.user(user_id, username);
security_log::record(pool, tenant_slug, entry).await;
return found.ok_or(MemberLoginError::Invalid);
}
attempt.failed().await;
let reason = if password_ok { "inactive" } else { "invalid_credentials" };
let entry = security_log::Entry::new(security_log::EVENT_LOGIN_FAILED, source, &request.meta)
.user(user_id, username)
.reason(reason);
security_log::record(pool, tenant_slug, entry).await;
if security_log::is_locked(tenant_slug, &[ident, username]).await {
let entry = security_log::Entry::new(security_log::EVENT_LOCKOUT, source, &request.meta)
.user(user_id, username);
security_log::record(pool, tenant_slug, entry).await;
}
Err(MemberLoginError::Invalid)
}
async fn find_member(pool: &rustango::sql::Pool, ident: &str) -> Option<User> {
use rustango::core::Column as _;
use rustango::sql::FetcherPool as _;
let by_name: Vec<User> = User::objects()
.where_(User::username.eq(ident.to_owned()))
.limit(1)
.fetch(pool)
.await
.unwrap_or_default();
if let Some(user) = by_name.into_iter().next() {
return Some(user);
}
User::objects()
.filter("email", ident.to_ascii_lowercase())
.limit(1)
.fetch(pool)
.await
.unwrap_or_default()
.into_iter()
.next()
}
async fn email_taken(pool: &rustango::sql::Pool, email: &str) -> Result<bool, AdminError> {
use rustango::sql::FetcherPool as _;
let rows: Vec<User> = User::objects()
.filter("email", email.to_owned())
.limit(1)
.fetch(pool)
.await?;
Ok(!rows.is_empty())
}
async fn create_member(
pool: &rustango::sql::Pool,
email: &str,
password: &str,
display_name: &str,
) -> Result<User, AdminError> {
use rustango::sql::Auto;
let mut user = User {
id: Auto::Unset,
username: email.to_owned(),
password_hash: crate::passwords::hash(password).await
.map_err(|e| AdminError::Validation(format!("password hashing failed: {e}")))?,
email: Some(email.to_owned()),
is_superuser: false,
active: true,
created_at: chrono::Utc::now(),
data: serde_json::json!({ "display_name": display_name }),
password_changed_at: None,
sessions_revoked_at: None,
};
user.insert_pool(pool).await?;
if user.id.get().is_none() {
return Err(AdminError::Validation("member insert returned no id".to_owned()));
}
Ok(user)
}
fn sanitize_next(next: &str) -> String {
rustango::auth_decorators::safe_next(next).unwrap_or_else(|| "/".to_owned())
}
fn redirect_with_cookie(location: &str, set_cookie: &str) -> Response {
let mut resp = Redirect::to(location).into_response();
if let Ok(v) = HeaderValue::from_str(set_cookie) {
resp.headers_mut().append(header::SET_COOKIE, v);
}
resp
}
#[cfg(test)]
mod tests {
use super::sanitize_next;
#[test]
fn next_stays_on_site() {
assert_eq!(sanitize_next("/members/area?x=1"), "/members/area?x=1");
for hostile in ["https://evil.test", "//evil.test", "/\\evil.test", "/%5Cevil.test", "/%2F/evil.test", "/\t/evil.test"] {
assert_eq!(sanitize_next(hostile), "/", "{hostile:?}");
}
}
}