Files
sorsfonalak/services/backend/src/routes/auth.rs
T
fecoandClaude Opus 5.5 450174c273 Free chart summaries; password login off by default
- New analysis kind 'summary' (migration 0005): saving a chart queues a
  free 3-4 sentence summary written by SUMMARY_MODEL (default Sonnet
  5.5, about 1 cent; Haiku was tested too but chose weaker highlights).
  POST /v1/charts/{id}/summary returns it and re-queues a failed one.
- The chart page shows it in a "Röviden" card and polls until ready.
- PASSWORD_LOGIN (default false): register, login and password reset
  answer 403; only Google (later Apple, Facebook) logins remain.
- Prompt v2: Hungarian names for elements and modalities (an English
  "Fire" slipped into a summary); worker compare-models --summary.
- The worker also reads a lower-case openrouter_api_key.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_012vLHzh5qUhFtmJhzkcTbXL
2026-11-16 17:12:17 +00:00

480 lines
18 KiB
Rust

//! Registration and login: e-mail + password, Google; e-mail verification,
//! password reset, logout.
use axum::Json;
use axum::extract::State;
use axum::http::{HeaderMap, StatusCode};
use axum::response::IntoResponse;
use axum_extra::extract::{CookieJar, WithRejection};
use db::{Role, USER_COLUMNS, User};
use serde::{Deserialize, Serialize};
use serde_json::{Value, json};
use sqlx::PgConnection;
use time::OffsetDateTime;
use uuid::Uuid;
use super::{Body, St};
use crate::AppState;
use crate::auth::{
AuthUser, DUMMY_HASH, SessionInfo, create_session, hash_password, removal_cookie, session_cookie, user_agent,
validate_password, verify_password,
};
use crate::error::{ApiError, ApiResult};
use crate::views::UserView;
const VERIFY_EMAIL_TTL: time::Duration = time::Duration::days(3);
const RESET_PASSWORD_TTL: time::Duration = time::Duration::hours(1);
#[derive(Serialize)]
pub struct LoginResponse {
pub user: UserView,
pub session: SessionInfo,
/// `true` when this call created the account.
pub created: bool,
}
pub fn normalize_email(email: &str) -> Result<String, ApiError> {
let email = email.trim().to_lowercase();
let valid = email.len() <= 254
&& email.split_once('@').is_some_and(|(local, domain)| {
!local.is_empty() && domain.contains('.') && !domain.starts_with('.') && !domain.ends_with('.')
})
&& !email.chars().any(char::is_whitespace);
if valid { Ok(email) } else { Err(ApiError::BadRequest("invalid e-mail address".into())) }
}
pub fn validate_locale(state: &AppState, locale: Option<&str>) -> Result<String, ApiError> {
match locale {
None => Ok(state.config.supported_locales[0].clone()),
Some(l) if state.config.supported_locales.iter().any(|s| s == l) => Ok(l.to_string()),
Some(l) => Err(ApiError::BadRequest(format!(
"unsupported locale '{l}'; supported: {}",
state.config.supported_locales.join(", ")
))),
}
}
fn clean_name(name: Option<String>) -> Option<String> {
name.map(|n| n.trim().chars().take(100).collect::<String>()).filter(|n| !n.is_empty())
}
async fn load_user(conn: &mut PgConnection, id: Uuid) -> Result<User, ApiError> {
Ok(sqlx::query_as(&format!("SELECT {USER_COLUMNS} FROM users WHERE id = $1")).bind(id).fetch_one(conn).await?)
}
/// Gives the admin role to addresses listed in `BOOTSTRAP_ADMIN_EMAILS`.
async fn apply_bootstrap_admin(state: &AppState, conn: &mut PgConnection, user: &mut User) -> Result<(), ApiError> {
if !user.has_role(Role::Admin) && state.config.bootstrap_admin_emails.contains(&user.email) {
sqlx::query("UPDATE users SET roles = array_append(roles, 'admin'), updated_at = now() WHERE id = $1")
.bind(user.id)
.execute(&mut *conn)
.await?;
*user = load_user(conn, user.id).await?;
tracing::info!(user = %user.id, "admin role granted from BOOTSTRAP_ADMIN_EMAILS");
}
Ok(())
}
/// One-time token row; returns the secret to put into the e-mail link.
async fn issue_token(
conn: &mut PgConnection,
user_id: Uuid,
purpose: &str,
ttl: time::Duration,
) -> Result<String, ApiError> {
// A new link replaces the earlier unused ones.
sqlx::query("DELETE FROM auth_tokens WHERE user_id = $1 AND purpose = $2 AND used_at IS NULL")
.bind(user_id)
.bind(purpose)
.execute(&mut *conn)
.await?;
let token = db::new_token();
sqlx::query("INSERT INTO auth_tokens (id, user_id, purpose, token_hash, expires_at) VALUES ($1, $2, $3, $4, $5)")
.bind(Uuid::now_v7())
.bind(user_id)
.bind(purpose)
.bind(db::token_hash(&token))
.bind(OffsetDateTime::now_utc() + ttl)
.execute(conn)
.await?;
Ok(token)
}
/// Uses a one-time token; returns its user.
async fn consume_token(conn: &mut PgConnection, token: &str, purpose: &str) -> Result<Uuid, ApiError> {
let row: Option<(Uuid,)> = sqlx::query_as(
"UPDATE auth_tokens SET used_at = now() \
WHERE token_hash = $1 AND purpose = $2 AND used_at IS NULL AND expires_at > now() RETURNING user_id",
)
.bind(db::token_hash(token.trim()))
.bind(purpose)
.fetch_optional(conn)
.await?;
row.map(|(id,)| id).ok_or(ApiError::InvalidToken)
}
/// Queues an e-mail for the worker.
pub async fn queue_email(conn: &mut PgConnection, user: &User, template: &str, payload: Value) -> Result<(), ApiError> {
sqlx::query(
"INSERT INTO email_outbox (id, user_id, to_email, template, locale, payload) VALUES ($1, $2, $3, $4, $5, $6)",
)
.bind(Uuid::now_v7())
.bind(user.id)
.bind(&user.email)
.bind(template)
.bind(&user.locale)
.bind(payload)
.execute(conn)
.await?;
Ok(())
}
async fn queue_verification(state: &AppState, conn: &mut PgConnection, user: &User) -> Result<(), ApiError> {
let token = issue_token(conn, user.id, "verify_email", VERIFY_EMAIL_TTL).await?;
let url = format!("{}/verify-email?token={token}", state.config.public_base_url);
queue_email(conn, user, "verify_email", json!({ "url": url, "display_name": user.display_name })).await
}
fn login_response(
state: &AppState,
jar: CookieJar,
user: &User,
session: SessionInfo,
created: bool,
) -> impl IntoResponse + use<> {
let jar = jar.add(session_cookie(&state.config, &session));
let status = if created { StatusCode::CREATED } else { StatusCode::OK };
(status, jar, Json(LoginResponse { user: user.into(), session, created }))
}
// --- e-mail + password -----------------------------------------------------------------
#[derive(Deserialize)]
#[serde(deny_unknown_fields)]
pub struct RegisterRequest {
email: String,
password: String,
display_name: Option<String>,
locale: Option<String>,
}
/// Password endpoints answer 403 while `PASSWORD_LOGIN` is off.
pub fn password_login_enabled(state: &crate::AppState) -> Result<(), ApiError> {
if state.config.password_login {
Ok(())
} else {
Err(ApiError::Forbidden("e-mail and password login is disabled; use Google, Apple or Facebook".into()))
}
}
pub async fn register(
State(state): St,
headers: HeaderMap,
jar: CookieJar,
WithRejection(Json(req), _): Body<RegisterRequest>,
) -> ApiResult<impl IntoResponse> {
password_login_enabled(&state)?;
let email = normalize_email(&req.email)?;
validate_password(&req.password)?;
let locale = validate_locale(&state, req.locale.as_deref())?;
let hash = hash_password(req.password).await?;
let mut tx = state.db.begin().await?;
let exists: Option<(Uuid,)> =
sqlx::query_as("SELECT id FROM users WHERE email = $1").bind(&email).fetch_optional(&mut *tx).await?;
if exists.is_some() {
return Err(ApiError::conflict("email_taken", "an account with this e-mail address already exists"));
}
let user_id = Uuid::now_v7();
sqlx::query("INSERT INTO users (id, email, display_name, locale) VALUES ($1, $2, $3, $4)")
.bind(user_id)
.bind(&email)
.bind(clean_name(req.display_name))
.bind(&locale)
.execute(&mut *tx)
.await?;
sqlx::query("INSERT INTO auth_identities (id, user_id, provider, subject, password_hash, email) VALUES ($1, $2, 'password', $3, $4, $5)")
.bind(Uuid::now_v7())
.bind(user_id)
.bind(user_id.to_string())
.bind(hash)
.bind(&email)
.execute(&mut *tx)
.await?;
let mut user = load_user(&mut tx, user_id).await?;
apply_bootstrap_admin(&state, &mut tx, &mut user).await?;
queue_verification(&state, &mut tx, &user).await?;
tx.commit().await?;
let session = create_session(&state.db, &state.config, user.id, user_agent(&headers)).await?;
Ok(login_response(&state, jar, &user, session, true))
}
#[derive(Deserialize)]
#[serde(deny_unknown_fields)]
pub struct LoginRequest {
email: String,
password: String,
}
pub async fn login(
State(state): St,
headers: HeaderMap,
jar: CookieJar,
WithRejection(Json(req), _): Body<LoginRequest>,
) -> ApiResult<impl IntoResponse> {
password_login_enabled(&state)?;
let invalid = || ApiError::InvalidCredentials("wrong e-mail address or password".into());
let email = normalize_email(&req.email).map_err(|_| invalid())?;
state.login_limiter.check(&email)?;
let row: Option<(Uuid, String)> = sqlx::query_as(
"SELECT u.id, i.password_hash FROM users u \
JOIN auth_identities i ON i.user_id = u.id AND i.provider = 'password' WHERE u.email = $1",
)
.bind(&email)
.fetch_optional(&state.db)
.await?;
let Some((user_id, hash)) = row else {
// Same amount of work as a real check.
let _ = verify_password(req.password, DUMMY_HASH.clone()).await;
state.login_limiter.failed(&email);
return Err(invalid());
};
if !verify_password(req.password, hash).await? {
state.login_limiter.failed(&email);
return Err(invalid());
}
state.login_limiter.succeeded(&email);
let mut conn = state.db.acquire().await?;
sqlx::query("UPDATE auth_identities SET last_used_at = now() WHERE user_id = $1 AND provider = 'password'")
.bind(user_id)
.execute(&mut *conn)
.await?;
let mut user = load_user(&mut conn, user_id).await?;
apply_bootstrap_admin(&state, &mut conn, &mut user).await?;
drop(conn);
let session = create_session(&state.db, &state.config, user.id, user_agent(&headers)).await?;
Ok(login_response(&state, jar, &user, session, false))
}
// --- Google -----------------------------------------------------------------------------
#[derive(Deserialize)]
#[serde(deny_unknown_fields)]
pub struct GoogleRequest {
/// ID token (JWT) from Google Identity Services.
id_token: String,
}
/// Logs in with Google. An unknown Google account is linked to the existing
/// user with the same (Google-verified) e-mail address, or a new user is created.
pub async fn google(
State(state): St,
headers: HeaderMap,
jar: CookieJar,
WithRejection(Json(req), _): Body<GoogleRequest>,
) -> ApiResult<impl IntoResponse> {
let claims = state.google.verify(&req.id_token).await?;
let email = match (claims.email.as_deref(), claims.email_verified) {
(Some(e), true) => normalize_email(e)?,
_ => return Err(ApiError::InvalidCredentials("the Google account has no verified e-mail address".into())),
};
let mut tx = state.db.begin().await?;
let linked: Option<(Uuid,)> =
sqlx::query_as("SELECT user_id FROM auth_identities WHERE provider = 'google' AND subject = $1")
.bind(&claims.sub)
.fetch_optional(&mut *tx)
.await?;
let (user_id, created) = match linked {
Some((id,)) => {
sqlx::query("UPDATE auth_identities SET last_used_at = now() WHERE provider = 'google' AND subject = $1")
.bind(&claims.sub)
.execute(&mut *tx)
.await?;
(id, false)
}
None => {
let existing: Option<(Uuid,)> =
sqlx::query_as("SELECT id FROM users WHERE email = $1").bind(&email).fetch_optional(&mut *tx).await?;
let (id, created) = match existing {
Some((id,)) => {
// Google has verified the address, so it counts as verified here too.
sqlx::query(
"UPDATE users SET email_verified_at = COALESCE(email_verified_at, now()) WHERE id = $1",
)
.bind(id)
.execute(&mut *tx)
.await?;
(id, false)
}
None => {
let id = Uuid::now_v7();
let locale = claims
.locale
.as_deref()
.and_then(|l| l.split(['-', '_']).next())
.filter(|l| state.config.supported_locales.iter().any(|s| s == l))
.unwrap_or(&state.config.supported_locales[0])
.to_string();
sqlx::query(
"INSERT INTO users (id, email, email_verified_at, display_name, locale) VALUES ($1, $2, now(), $3, $4)",
)
.bind(id)
.bind(&email)
.bind(clean_name(claims.name.clone()))
.bind(locale)
.execute(&mut *tx)
.await?;
(id, true)
}
};
sqlx::query(
"INSERT INTO auth_identities (id, user_id, provider, subject, email, last_used_at) \
VALUES ($1, $2, 'google', $3, $4, now())",
)
.bind(Uuid::now_v7())
.bind(id)
.bind(&claims.sub)
.bind(&email)
.execute(&mut *tx)
.await?;
(id, created)
}
};
let mut user = load_user(&mut tx, user_id).await?;
apply_bootstrap_admin(&state, &mut tx, &mut user).await?;
tx.commit().await?;
let session = create_session(&state.db, &state.config, user.id, user_agent(&headers)).await?;
Ok(login_response(&state, jar, &user, session, created))
}
// --- logout -------------------------------------------------------------------------------
pub async fn logout(State(state): St, auth: AuthUser, jar: CookieJar) -> ApiResult<impl IntoResponse> {
sqlx::query("DELETE FROM sessions WHERE id = $1").bind(auth.session_id).execute(&state.db).await?;
Ok((StatusCode::NO_CONTENT, jar.add(removal_cookie(&state.config))))
}
/// Ends every session of the user (all devices).
pub async fn logout_all(State(state): St, auth: AuthUser, jar: CookieJar) -> ApiResult<impl IntoResponse> {
sqlx::query("DELETE FROM sessions WHERE user_id = $1").bind(auth.id()).execute(&state.db).await?;
Ok((StatusCode::NO_CONTENT, jar.add(removal_cookie(&state.config))))
}
// --- e-mail verification and password reset ------------------------------------------------
#[derive(Deserialize)]
#[serde(deny_unknown_fields)]
pub struct TokenRequest {
token: String,
}
pub async fn verify_email(State(state): St, WithRejection(Json(req), _): Body<TokenRequest>) -> ApiResult<Json<Value>> {
let mut tx = state.db.begin().await?;
let user_id = consume_token(&mut tx, &req.token, "verify_email").await?;
sqlx::query("UPDATE users SET email_verified_at = COALESCE(email_verified_at, now()) WHERE id = $1")
.bind(user_id)
.execute(&mut *tx)
.await?;
tx.commit().await?;
Ok(Json(json!({ "verified": true })))
}
pub async fn resend_verification(State(state): St, auth: AuthUser) -> ApiResult<StatusCode> {
if auth.user.email_verified_at.is_some() {
return Err(ApiError::conflict("already_verified", "the e-mail address is already verified"));
}
let mut tx = state.db.begin().await?;
queue_verification(&state, &mut tx, &auth.user).await?;
tx.commit().await?;
Ok(StatusCode::ACCEPTED)
}
#[derive(Deserialize)]
#[serde(deny_unknown_fields)]
pub struct ResetRequest {
email: String,
}
/// Always 202, so the response does not reveal whether the address is registered.
pub async fn request_password_reset(
State(state): St,
WithRejection(Json(req), _): Body<ResetRequest>,
) -> ApiResult<StatusCode> {
password_login_enabled(&state)?;
let Ok(email) = normalize_email(&req.email) else { return Ok(StatusCode::ACCEPTED) };
let mut tx = state.db.begin().await?;
let user: Option<User> = sqlx::query_as(&format!("SELECT {USER_COLUMNS} FROM users WHERE email = $1"))
.bind(&email)
.fetch_optional(&mut *tx)
.await?;
if let Some(user) = user {
let token = issue_token(&mut tx, user.id, "reset_password", RESET_PASSWORD_TTL).await?;
let url = format!("{}/reset-password?token={token}", state.config.public_base_url);
queue_email(&mut tx, &user, "reset_password", json!({ "url": url, "display_name": user.display_name })).await?;
}
tx.commit().await?;
Ok(StatusCode::ACCEPTED)
}
#[derive(Deserialize)]
#[serde(deny_unknown_fields)]
pub struct ResetConfirmRequest {
token: String,
password: String,
}
/// Sets a new password (adding the password login if the user had only
/// Google) and ends all sessions.
pub async fn confirm_password_reset(
State(state): St,
WithRejection(Json(req), _): Body<ResetConfirmRequest>,
) -> ApiResult<StatusCode> {
password_login_enabled(&state)?;
validate_password(&req.password)?;
let hash = hash_password(req.password).await?;
let mut tx = state.db.begin().await?;
let user_id = consume_token(&mut tx, &req.token, "reset_password").await?;
set_password(&mut tx, user_id, &hash).await?;
// The link arrived in the mailbox, so the address is verified.
sqlx::query("UPDATE users SET email_verified_at = COALESCE(email_verified_at, now()) WHERE id = $1")
.bind(user_id)
.execute(&mut *tx)
.await?;
sqlx::query("DELETE FROM sessions WHERE user_id = $1").bind(user_id).execute(&mut *tx).await?;
tx.commit().await?;
Ok(StatusCode::NO_CONTENT)
}
/// Creates or replaces the password identity.
pub async fn set_password(conn: &mut PgConnection, user_id: Uuid, hash: &str) -> Result<(), ApiError> {
sqlx::query(
"INSERT INTO auth_identities (id, user_id, provider, subject, password_hash, email) \
SELECT $1, u.id, 'password', u.id::text, $2, u.email FROM users u WHERE u.id = $3 \
ON CONFLICT (user_id, provider) DO UPDATE SET password_hash = EXCLUDED.password_hash",
)
.bind(Uuid::now_v7())
.bind(hash)
.bind(user_id)
.execute(conn)
.await?;
Ok(())
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn emails() {
assert_eq!(normalize_email(" Anna@Example.COM ").unwrap(), "anna@example.com");
assert!(normalize_email("anna").is_err());
assert!(normalize_email("anna@localhost").is_err());
assert!(normalize_email("an na@example.com").is_err());
}
}