1use 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
38pub(crate) const MEMBER_SESSION_TTL: i64 = 7 * 24 * 60 * 60;
41
42const MEMBER_SSO_BASE: &str = "/members/auth";
46
47#[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
61pub(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
93pub(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#[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
155pub(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
178pub(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
235pub(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#[derive(Debug)]
256pub enum MemberLoginError {
257 Refused(LoginRefused),
260 Invalid,
263}
264
265pub 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 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 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
336async 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
360async 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
372async 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
401fn sanitize_next(next: &str) -> String {
404 rustango::auth_decorators::safe_next(next).unwrap_or_else(|| "/".to_owned())
405}
406
407fn 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}