ryuk-cli 0.1.0

The `ryuk` command: scaffold a Ryuk app (axum, SeaORM, Inertia/Svelte), generate controllers, models, jobs and mails, run migrations and the dev server.
//! Account security pages (web group): authorized apps, push devices, log out everywhere,
//! change password, delete account. Every handler acts on the session user only.
use super::AppError;
use crate::{AppState, account, models::user};
use axum::{
    extract::{Path, State},
    response::Response,
};
use ryuk::{
    auth::{self, Auth},
    inertia::{self, Inertia},
    proxy::ClientIp,
    session::Session,
    validation::Form,
};
use sea_orm::{ActiveModelTrait, ActiveValue::{Set, Unchanged}, EntityTrait};
use serde::Deserialize;
use serde_json::{Value, json};
use std::collections::BTreeMap;
use utoipa::ToSchema;
use validator::Validate;

const PAGE: &str = "/settings/security";

#[derive(Deserialize, Validate, ToSchema)]
pub struct PasswordForm {
    /// Required when the account has a password (not for social-only accounts setting their first one).
    current_password: Option<String>,
    #[validate(length(min = 8, message = "Password must be at least 8 characters"))]
    #[validate(must_match(other = "password_confirmation", message = "Passwords do not match"))]
    password: String,
    password_confirmation: String,
}

#[derive(Deserialize, Validate, ToSchema)]
pub struct DeleteForm {
    /// Must be exactly `DELETE`.
    confirm: String,
    /// Required when the account has a password.
    password: Option<String>,
}

fn field(name: &str, msg: &str) -> BTreeMap<String, String> {
    BTreeMap::from([(name.to_string(), msg.to_string())])
}

async fn find(s: &AppState, uid: i64) -> Result<Option<user::Model>, AppError> {
    Ok(user::Entity::find_by_id(uid).one(&s.db).await?)
}

fn grants_json(g: Vec<ryuk::oauth_server::Grant>) -> Vec<Value> {
    g.into_iter().map(|g| json!(g)).collect()
}

#[utoipa::path(get, path = "/settings/security", responses((status = 200, description = "Authorized apps, devices and account security")))]
pub async fn index(State(s): State<AppState>, Auth(uid): Auth, inertia: Inertia) -> Result<Response, AppError> {
    let Some(u) = find(&s, uid).await? else {
        return Ok(inertia::redirect("/login"));
    };
    let devices: Vec<Value> = s
        .push
        .devices()
        .list(uid)
        .await?
        .into_iter()
        .map(|d| json!({ "id": d.id, "platform": d.platform.as_str(), "name": d.name, "app_id": d.app_id, "created_at": d.created_at, "last_seen_at": d.last_seen_at }))
        .collect();
    let props = json!({
        "grants": grants_json(s.oauth.list_grants(uid).await?),
        "devices": devices,
        "passkeys": s.passkeys.list(uid).await?,
        "has_password": u.has_usable_password,
        "sessions": s.session_store.count_for_user(uid).await?,
    });
    Ok(inertia.render("Settings/Security", props))
}

#[utoipa::path(post, path = "/settings/security/grants/{id}/revoke", params(("id" = String, Path, description = "Grant id")),
    responses((status = 303, description = "Back to the security page")))]
pub async fn revoke_grant(State(s): State<AppState>, Auth(uid): Auth, Path(id): Path<String>, session: Session) -> Result<Response, AppError> {
    // Owner-checked in the library: someone else's id is simply "not found".
    if s.oauth.revoke_grant(uid, &id).await? {
        inertia::flash(&session, "success", "App access revoked.").await;
    } else {
        inertia::flash(&session, "error", "App not found.").await;
    }
    Ok(inertia::redirect(PAGE))
}

#[utoipa::path(post, path = "/settings/security/devices/{id}/revoke", params(("id" = i64, Path, description = "Device id")),
    responses((status = 303, description = "Back to the security page")))]
pub async fn revoke_device(State(s): State<AppState>, Auth(uid): Auth, Path(id): Path<i64>, session: Session) -> Result<Response, AppError> {
    if s.push.devices().unregister(uid, id).await? {
        inertia::flash(&session, "success", "Device removed.").await;
    } else {
        inertia::flash(&session, "error", "Device not found.").await;
    }
    Ok(inertia::redirect(PAGE))
}

#[utoipa::path(post, path = "/settings/security/logout-everywhere",
    responses((status = 303, description = "Every session and OAuth grant is revoked; back to login")))]
pub async fn logout_everywhere(State(s): State<AppState>, Auth(uid): Auth, session: Session) -> Result<Response, AppError> {
    account::sign_out_everywhere(&s, uid).await?;
    s.api_keys.revoke_all(uid).await?; // "everywhere" includes machine credentials
    auth::logout(&session).await; // the current session too (its row is already gone; this clears the cookie)
    inertia::flash(&session, "success", "You were logged out everywhere.").await;
    Ok(inertia::redirect("/login"))
}

#[utoipa::path(post, path = "/settings/password", request_body = PasswordForm,
    responses((status = 303, description = "Back to the security page; other sessions and OAuth grants are revoked")))]
pub async fn change_password(
    State(s): State<AppState>,
    ClientIp(ip): ClientIp,
    Auth(uid): Auth,
    session: Session,
    Form(f): Form<PasswordForm>,
) -> Result<Response, AppError> {
    let Some(u) = find(&s, uid).await? else {
        return Ok(inertia::redirect("/login"));
    };
    if let Err(msg) = account::confirm_password(&s, ip, &u, f.current_password.as_deref()).await? {
        inertia::flash_errors(&session, field("current_password", &msg)).await;
        return Ok(inertia::redirect(PAGE));
    }
    user::ActiveModel {
        id: Unchanged(uid),
        password: Set(auth::hash_password_async(f.password.clone()).await?),
        has_usable_password: Set(true),
        ..Default::default()
    }
    .update(&s.db)
    .await?;
    // Everything else that could act as the user is revoked; this browser stays signed in (fresh session id).
    account::sign_out_everywhere(&s, uid).await?;
    auth::login(&session, uid).await?;
    inertia::flash(&session, "success", "Password updated. Other devices were signed out.").await;
    Ok(inertia::redirect(PAGE))
}

#[utoipa::path(post, path = "/settings/delete-account", request_body = DeleteForm,
    responses((status = 303, description = "Account deleted: home; or back with an error")))]
pub async fn delete_account(
    State(s): State<AppState>,
    ClientIp(ip): ClientIp,
    Auth(uid): Auth,
    session: Session,
    Form(f): Form<DeleteForm>,
) -> Result<Response, AppError> {
    let Some(u) = find(&s, uid).await? else {
        return Ok(inertia::redirect("/login"));
    };
    if f.confirm != "DELETE" {
        inertia::flash_errors(&session, field("confirm", "Type DELETE to confirm.")).await;
        return Ok(inertia::redirect(PAGE));
    }
    if let Err(msg) = account::confirm_password(&s, ip, &u, f.password.as_deref()).await? {
        inertia::flash_errors(&session, field("password", &msg)).await;
        return Ok(inertia::redirect(PAGE));
    }
    account::delete_user(&s, uid).await?;
    auth::logout(&session).await;
    inertia::flash(&session, "success", "Your account was deleted.").await;
    Ok(inertia::redirect("/"))
}