19.8 KiB · text History 952e601
use axum::{
    extract::{Form, Query, State},
    http::{header::SET_COOKIE, HeaderMap, StatusCode},
    response::{Html, IntoResponse, Redirect, Response},
};
use minijinja::context;
use sea_orm::*;
use serde::Deserialize;
use tracing::error;

use super::render;
use crate::auth::{self, verification, CreateUserRequest, LoginRequest};
use crate::entities::{registration_tokens, users};
use crate::middleware::UserContext;
use crate::AppState;

/// The `Set-Cookie` value for a fresh session. `secure` adds `Secure` (set
/// when `PUBLIC_URL` is https; see `Config::secure_cookies`).
pub fn session_cookie_value(token: &str, duration_hours: i64, secure: bool) -> String {
    format!(
        "session_token={token}; HttpOnly; SameSite=Strict; Path=/; Max-Age={}{}",
        duration_hours * 3600,
        if secure { "; Secure" } else { "" }
    )
}

fn session_cookie(state: &AppState, token: &str) -> HeaderMap {
    let mut headers = HeaderMap::new();
    headers.insert(
        SET_COOKIE,
        session_cookie_value(token, state.config.session_duration_hours, state.config.secure_cookies())
            .parse()
            .unwrap(),
    );
    headers
}

/// Password login (and local registration) are offered: `OIDC_PASSWORD_LOGIN`
/// is not false and the login mode (neiam-auth v0.4 `OIDC_LOGIN_MODE`) is not
/// `sso_strict`. As mail-prism's `handlers/auth.rs`.
pub fn local_login(state: &AppState) -> bool {
    state.config.password_login && state.config.oidc.local_login_enabled()
}

/// Percent-encode a query value (everything but RFC 3986 unreserved).
fn query_escape(s: &str) -> String {
    s.bytes()
        .map(|b| match b {
            b'A'..=b'Z' | b'a'..=b'z' | b'0'..=b'9' | b'-' | b'.' | b'_' | b'~' => (b as char).to_string(),
            _ => format!("%{b:02X}"),
        })
        .collect()
}

#[derive(Debug, Deserialize)]
pub struct LoginForm {
    pub username: String,
    pub password: String,
}

#[derive(Debug, Default, Deserialize)]
pub struct LoginQuery {
    pub next: Option<String>,
    /// Set by logout: show the "also sign out of <provider>" links.
    pub signed_out: Option<String>,
    /// Set after a password reset: "Log in with the new one."
    pub reset: Option<String>,
}

fn login_page(state: &AppState, qs: &LoginQuery, error: Option<String>) -> Result<Html<String>, StatusCode> {
    let oidc = &state.config.oidc;
    let signed_out = qs.signed_out.is_some();
    render(
        state,
        "auth/login.html",
        context! {
            title => "Login",
            app_name => state.config.app_name,
            registration_open => state.config.registration_enabled,
            providers => oidc.enabled(),
            password_login => local_login(state),
            next => neiam_auth::safe_return_to(qs.next.as_deref()),
            signed_out => signed_out,
            reset => qs.reset.is_some(),
            logout_links => if signed_out { oidc.logout_links() } else { vec![] },
            error => error,
        },
    )
}

/// Show the login page.
pub async fn show_login(
    State(state): State<AppState>,
    Query(qs): Query<LoginQuery>,
) -> Result<Html<String>, StatusCode> {
    login_page(&state, &qs, None)
}

#[derive(Debug, Deserialize)]
pub struct RegisterQuery {
    pub token: Option<String>,
}

/// Show the registration page. With `REGISTRATION_ENABLED=false` (default), the
/// page only renders if a `?token=` invite link is present.
///
/// With no local login (`OIDC_LOGIN_MODE=sso_strict` or
/// `OIDC_PASSWORD_LOGIN=false`) an invite link goes to "Sign up with NEIAM"
/// (`/auth/oidc/<id>/login?invite=…`) instead, and anything else 404s.
pub async fn show_register(
    State(state): State<AppState>,
    Query(qs): Query<RegisterQuery>,
) -> Result<Response, StatusCode> {
    let invite_token = qs.token.as_deref().map(str::trim).filter(|s| !s.is_empty());
    if !local_login(&state) {
        return match (invite_token, state.config.oidc.enabled().into_iter().next()) {
            (Some(token), Some(p)) => {
                Ok(Redirect::to(&format!("{}?invite={}", p.login_url, query_escape(token))).into_response())
            }
            _ => Err(StatusCode::NOT_FOUND),
        };
    }
    if invite_token.is_none() && !state.config.registration_enabled {
        return Err(StatusCode::NOT_FOUND);
    }
    register_page(&state, invite_token, None, "", "", StatusCode::OK)
}

/// The registration form, fresh or with `error` and what was typed.
fn register_page(
    state: &AppState,
    invite_token: Option<&str>,
    error: Option<&str>,
    username: &str,
    email: &str,
    status: StatusCode,
) -> Result<Response, StatusCode> {
    let html = render(
        state,
        "auth/register.html",
        context! {
            title => "Register",
            app_name => state.config.app_name,
            invite_token => invite_token,
            registration_open => state.config.registration_enabled,
            providers => state.config.oidc.enabled(),
            stamp => crate::registration::stamp(&state.config),
            error => error,
            username => username,
            email => email,
        },
    )?;
    Ok((status, html).into_response())
}

/// Show the invite-management page (logged-in users only).
pub async fn show_invites(
    State(state): State<AppState>,
    Query(q): Query<InvitesQuery>,
    headers: HeaderMap,
    user_context: UserContext,
) -> Result<Response, StatusCode> {
    let view = super::focus::view_for(&state, q.view.as_deref(), Some(&user_context), &headers);
    let mine = registration_tokens::Entity::find()
        .filter(registration_tokens::Column::CreatedByUserId.eq(user_context.user.id))
        .order_by_desc(registration_tokens::Column::CreatedAt)
        .all(state.db.as_ref())
        .await
        .map_err(|e| {
            error!(error = %e, "load invites failed");
            StatusCode::INTERNAL_SERVER_ERROR
        })?;
    if view.mode == super::focus::ViewMode::Focus {
        let page = super::invites::invites_focus(&state, &user_context, mine).await?;
        return Ok(view.respond(page));
    }
    let page = render(
        &state,
        "auth/invites.html",
        context! {
            title => "Invites",
            app_name => state.config.app_name,
            user => user_context.user,
            invites => mine,
            now => chrono::Utc::now(),
        },
    )?;
    Ok(view.respond(page))
}

#[derive(Debug, Deserialize)]
pub struct InvitesQuery {
    /// `classic` or `focus`; see [`super::focus::resolve_view`].
    pub view: Option<String>,
}

#[derive(Debug, Deserialize)]
pub struct CreateInviteForm {
    pub email: Option<String>,
    /// A blank field (what an untouched number input submits) means the
    /// default, not a 422.
    #[serde(default, deserialize_with = "blank_as_none")]
    pub days: Option<i64>,
}

fn blank_as_none<'de, D: serde::Deserializer<'de>>(d: D) -> Result<Option<i64>, D::Error> {
    let raw: Option<String> = Option::deserialize(d)?;
    match raw.as_deref().map(str::trim) {
        None | Some("") => Ok(None),
        Some(s) => s.parse().map(Some).map_err(serde::de::Error::custom),
    }
}

/// Create a new invite token for the current user, then redirect to `/invites`.
pub async fn handle_create_invite(
    State(state): State<AppState>,
    user_context: UserContext,
    Form(form): Form<CreateInviteForm>,
) -> Result<Redirect, StatusCode> {
    let email = form.email.map(|s| s.trim().to_string()).filter(|s| !s.is_empty());
    let days = form
        .days
        .filter(|d| *d > 0)
        .unwrap_or(state.config.registration_token_duration_days);

    auth::create_registration_token(state.db.as_ref(), Some(user_context.user.id), email, days)
        .await
        .map_err(|e| {
            error!(error = %e, "create invite failed");
            StatusCode::INTERNAL_SERVER_ERROR
        })?;
    Ok(Redirect::to("/invites"))
}

/// Handle a login form submission.
pub async fn handle_login(
    State(state): State<AppState>,
    ip: crate::client_ip::ClientIp,
    Form(form): Form<LoginForm>,
) -> Result<Response, StatusCode> {
    // OIDC_PASSWORD_LOGIN=false or OIDC_LOGIN_MODE=sso_strict: no password
    // sign-in for anyone.
    if !local_login(&state) {
        return Err(StatusCode::FORBIDDEN);
    }
    let user = auth::authenticate_user(
        &state.db,
        LoginRequest {
            username: form.username,
            password: form.password,
        },
    )
    .await
    .map_err(|_| StatusCode::INTERNAL_SERVER_ERROR)?;
    let Some(user) = user else {
        let page = login_page(&state, &LoginQuery::default(), Some("Wrong username or password.".into()))?;
        return Ok((StatusCode::UNAUTHORIZED, page).into_response());
    };

    // A suspended account can't sign in; it's told why and until when.
    if let Some(s) = crate::policy::suspension(&user) {
        let page = login_page(&state, &LoginQuery::default(), Some(crate::policy::suspension_message(&s)))?;
        return Ok((StatusCode::FORBIDDEN, page).into_response());
    }

    // OIDC_LOGIN_MODE=sso: an account linked to a REQUIRED_FOR_LINKED provider
    // signs in through it only. Checked after the password, so a wrong
    // password still reads as one.
    if !neiam_auth::sea_orm::password_login_allowed(state.db.as_ref(), &state.config.oidc, user.id)
        .await
        .map_err(|_| StatusCode::INTERNAL_SERVER_ERROR)?
    {
        let page = login_page(
            &state,
            &LoginQuery::default(),
            Some("This account signs in with single sign-on. Use the button above.".into()),
        )?;
        return Ok((StatusCode::FORBIDDEN, page).into_response());
    }

    let session = auth::create_session(&state.db, user.id, state.config.session_duration_hours)
        .await
        .map_err(|_| StatusCode::INTERNAL_SERVER_ERROR)?;
    crate::ips::record(state.db.as_ref(), user.id, ip.0, crate::ips::Seen::SignIn).await;
    Ok((session_cookie(&state, &session.session_token), Redirect::to("/")).into_response())
}

#[derive(Debug, Deserialize)]
pub struct RegisterForm {
    pub username: String,
    pub email: String,
    pub password: String,
    pub confirm_password: String,
    /// Absent (not just empty) on the open form.
    #[serde(default)]
    pub registration_token: Option<String>,
    /// The honeypot: hidden from people, so anything in it is a bot.
    #[serde(default)]
    pub website: Option<String>,
    /// When the form was served, signed ([`crate::registration::stamp`]).
    #[serde(default)]
    pub stamp: Option<String>,
}

/// Handle a registration form submission: through an invite, or (with
/// `REGISTRATION_ENABLED`) without one, past the guards in
/// [`crate::registration`]. The new account starts unverified (it can read,
/// not post) and is mailed a verification link.
pub async fn handle_register(
    State(state): State<AppState>,
    ip: crate::client_ip::ClientIp,
    Form(form): Form<RegisterForm>,
) -> Result<Response, StatusCode> {
    if !local_login(&state) {
        return Err(StatusCode::FORBIDDEN);
    }
    let token = form.registration_token.as_deref().map(str::trim).filter(|t| !t.is_empty());
    let again = |msg: &str, status: StatusCode| register_page(&state, token, Some(msg), &form.username, &form.email, status);

    // Open sign-up (no invite): the honeypot, the fill time, the per-address
    // limit. Closed registration refuses it below anyway.
    if token.is_none() && state.config.registration_enabled {
        let guard = match crate::registration::check_form(&state.config, form.website.as_deref(), form.stamp.as_deref()) {
            Ok(()) => crate::registration::check_rate(state.db.as_ref(), &state.config, ip.0).await,
            Err(r) => Err(r),
        };
        if let Err(r) = guard {
            tracing::info!(ip = ?ip.0, refused = ?r, "open sign-up refused");
            let status = match r {
                crate::registration::Refused::TooMany => StatusCode::TOO_MANY_REQUESTS,
                _ => StatusCode::BAD_REQUEST,
            };
            return again(r.message(), status);
        }
    }
    if form.password != form.confirm_password {
        return again("The passwords don't match.", StatusCode::BAD_REQUEST);
    }

    let user = match auth::create_user(
        &state.db,
        CreateUserRequest {
            username: form.username.clone(),
            email: form.email.clone(),
            password: form.password.clone(),
            registration_token: token.map(str::to_string),
            open: state.config.registration_enabled,
        },
    )
    .await
    {
        Ok(u) => u,
        Err(auth::RegisterError::InviteRequired) => return Err(StatusCode::NOT_FOUND),
        Err(e) => {
            if matches!(e, auth::RegisterError::Internal(_)) {
                error!(error = %e, "registration failed");
            }
            let status = match e {
                auth::RegisterError::Internal(_) => StatusCode::INTERNAL_SERVER_ERROR,
                auth::RegisterError::Taken => StatusCode::CONFLICT,
                _ => StatusCode::BAD_REQUEST,
            };
            return again(e.message(), status);
        }
    };

    // Best effort: a failed send is logged, and the banner offers a resend.
    verification::send(&state.db, state.mailer.as_ref(), &state.config, &user).await;

    let session = auth::create_session(&state.db, user.id, state.config.session_duration_hours)
        .await
        .map_err(|_| StatusCode::INTERNAL_SERVER_ERROR)?;
    // Where it came from (staff see it; the per-address limit counts it).
    crate::ips::record(state.db.as_ref(), user.id, ip.0, crate::ips::Seen::Register).await;
    crate::moderation::log(
        state.db.as_ref(),
        crate::moderation::Actor::web(&user),
        "register",
        "user",
        Some(user.id),
        &user.username,
        Some(if token.is_some() { "with an invite" } else { "open sign-up" }),
    )
    .await;
    Ok((session_cookie(&state, &session.session_token), Redirect::to("/")).into_response())
}

/// Handle logout — delete the session and clear the cookie.
pub async fn handle_logout(
    State(state): State<AppState>,
    user_context: Option<UserContext>,
) -> impl IntoResponse {
    if let Some(context) = user_context {
        let _ = auth::delete_session(&state.db, &context.session.session_token).await;
    }
    let mut headers = HeaderMap::new();
    headers.insert(
        SET_COOKIE,
        "session_token=; HttpOnly; SameSite=Strict; Path=/; Max-Age=0".parse().unwrap(),
    );
    // `signed_out` shows "also sign out of NEIAM" links on the login page.
    (headers, Redirect::to("/login?signed_out=1"))
}

#[derive(Debug, Default, Deserialize)]
pub struct ProfileQuery {
    /// Result of a verification resend (`sent|recent|verified|failed`).
    pub verification: Option<String>,
    /// Preferences were just saved.
    pub saved: Option<String>,
}

/// Show the user profile page.
pub async fn show_profile(
    State(state): State<AppState>,
    Query(qs): Query<ProfileQuery>,
    user_context: UserContext,
) -> Result<Html<String>, StatusCode> {
    let oidc = &state.config.oidc;
    let linked = neiam_auth::sea_orm::identities_for_user(state.db.as_ref(), user_context.user.id)
        .await
        .map_err(|e| {
            error!(error = %e, "load linked identities failed");
            StatusCode::INTERNAL_SERVER_ERROR
        })?;
    let linked_issuers: Vec<&str> = linked.iter().map(|l| l.issuer.as_str()).collect();
    let identities: Vec<minijinja::Value> = linked
        .iter()
        .map(|l| {
            context! {
                label => oidc.label_for_issuer(&l.issuer).unwrap_or_else(|| l.provider.clone()),
                username => l.username.clone().unwrap_or_else(|| l.subject.clone()),
            }
        })
        .collect();
    // "Link <label> account" for each enabled provider not linked yet.
    let linkable: Vec<_> = oidc
        .enabled()
        .into_iter()
        .filter(|p| {
            oidc.get(&p.id)
                .is_some_and(|c| !linked_issuers.contains(&c.config().issuer.as_str()))
        })
        .collect();

    render(
        &state,
        "auth/profile.html",
        context! {
            title => "Profile",
            app_name => state.config.app_name,
            user => user_context.user.clone(),
            member_since => crate::timeutil::abs(user_context.user.created_at),
            last_login => user_context.user.last_login_at.map(crate::timeutil::rel),
            email_verified_at => user_context.user.email_verified_at.map(crate::timeutil::abs),
            verification => qs.verification,
            saved => qs.saved.is_some(),
            layout => super::focus::ViewMode::parse(&user_context.user.preferred_view)
                .unwrap_or(super::focus::ViewMode::Classic)
                .as_str(),
            mail_configured => state.config.mail_configured(),
            identities => identities,
            linkable => linkable,
            has_password => !auth::password::is_unusable_hash(&user_context.user.password_hash),
        },
    )
}

#[derive(Debug, Deserialize)]
pub struct SettingsForm {
    /// Present (checkbox) = enabled.
    pub reaction_notifications: Option<String>,
    /// "Layout": `classic` or `focus`.
    pub layout: Option<String>,
}

/// Update the current user's preference toggles from the profile panel.
pub async fn update_settings(
    State(state): State<AppState>,
    user_context: UserContext,
    Form(form): Form<SettingsForm>,
) -> Result<impl IntoResponse, StatusCode> {
    crate::actions::update_preferences(
        &state,
        &user_context.user,
        crate::actions::Preferences {
            reaction_notifications: Some(form.reaction_notifications.is_some()),
            layout: form.layout.as_deref().and_then(super::focus::ViewMode::parse),
            sort: None,
        },
    )
    .await?;
    // The profile is the default from now on: drop any per-page override.
    let mut headers = HeaderMap::new();
    headers.insert(SET_COOKIE, super::focus::clear_session_view_cookie());
    Ok((headers, Redirect::to("/profile?saved=1")))
}

#[derive(Debug, Deserialize)]
pub struct VerifyQuery {
    pub token: Option<String>,
}

/// `GET /verify-email?token=…` — redeem a verification link. Works signed in
/// or not (the link may be opened on another device).
pub async fn verify_email(
    State(state): State<AppState>,
    Query(qs): Query<VerifyQuery>,
    user_context: Option<UserContext>,
) -> Result<Response, StatusCode> {
    let outcome = match qs.token.as_deref().map(str::trim).filter(|t| !t.is_empty()) {
        Some(token) => verification::redeem(state.db.as_ref(), token).await.map_err(|e| {
            error!(error = %e, "redeem verification token failed");
            StatusCode::INTERNAL_SERVER_ERROR
        })?,
        None => verification::Redeemed::Invalid,
    };
    let (status, result, username) = match outcome {
        verification::Redeemed::Verified(name) => (StatusCode::OK, "verified", Some(name)),
        verification::Redeemed::Expired => (StatusCode::GONE, "expired", None),
        verification::Redeemed::Invalid => (StatusCode::BAD_REQUEST, "invalid", None),
    };
    // Reload so the banner reflects the new state on this very page.
    let user = match user_context {
        Some(c) => users::Entity::find_by_id(c.user.id).one(state.db.as_ref()).await.ok().flatten(),
        None => None,
    };
    let page = render(
        &state,
        "auth/verify_email.html",
        context! {
            title => "Verify email",
            app_name => state.config.app_name,
            user => user,
            result => result,
            username => username,
        },
    )?;
    Ok((status, page).into_response())
}

/// `POST /verify-email/resend` — mail a fresh link (rate-limited), then back
/// to the profile with the outcome.
pub async fn resend_verification(State(state): State<AppState>, user_context: UserContext) -> Redirect {
    let sent =
        verification::send_if_due(&state.db, state.mailer.as_ref(), &state.config, &user_context.user).await;
    Redirect::to(&format!("/profile?verification={}", sent.as_str()))
}