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.
use crate::{AppState, models::user};
use axum::{Json, extract::State, http::StatusCode};
use ryuk::{api::{ApiAuth, ApiError}, proxy::ClientIp};
use sea_orm::EntityTrait;
use serde::{Deserialize, Serialize};
use utoipa::ToSchema;

#[derive(Serialize, ToSchema)]
pub struct Me {
    id: i64,
    name: String,
    email: String,
    email_verified: bool,
}

/// Who the credential acts for. Never exposes the password hash.
#[utoipa::path(get, path = "/me", security(("api_key" = []), ("oauth2" = ["profile"])),
    responses((status = 200, body = Me, description = "The signed-in user"), (status = 401, description = "Missing or invalid credential"), (status = 403, description = "Missing scope profile, or the credential is not bound to a user")))]
pub async fn show(State(s): State<AppState>, ApiAuth(p): ApiAuth) -> Result<Json<Me>, ApiError> {
    p.require("profile")?;
    let uid = p.user_id.ok_or(ApiError {
        status: axum::http::StatusCode::FORBIDDEN,
        code: "forbidden",
        message: "this credential is not bound to a user".into(),
    })?;
    let u = user::Entity::find_by_id(uid).one(&s.db).await?.ok_or_else(ApiError::unauthorized)?;
    Ok(Json(Me { id: u.id, name: u.name, email: u.email, email_verified: u.email_verified_at.is_some() }))
}

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

/// Permanently delete the account and everything of the user's: posts, push devices, API keys, OAuth
/// grants, linked identities and sessions. Irreversible; the credential used stops working at once.
#[utoipa::path(delete, path = "/me", request_body = DeleteMe, security(("api_key" = []), ("oauth2" = ["account"])),
    responses((status = 204, description = "Deleted"), (status = 401, description = "Missing or invalid credential"), (status = 403, description = "Missing scope account, or no user"), (status = 422, description = "confirm is not DELETE, or the password is missing or wrong")))]
pub async fn destroy(State(s): State<AppState>, ClientIp(ip): ClientIp, ApiAuth(p): ApiAuth, Json(i): Json<DeleteMe>) -> Result<StatusCode, ApiError> {
    p.require("account")?;
    let uid = super::owner(&p)?;
    if i.confirm != "DELETE" {
        return Err(ApiError::validation([("confirm".to_string(), vec!["Type DELETE to confirm".to_string()])].into()));
    }
    let u = user::Entity::find_by_id(uid).one(&s.db).await?.ok_or_else(ApiError::unauthorized)?;
    let checked = crate::account::confirm_password(&s, ip, &u, i.password.as_deref()).await.map_err(|e| {
        tracing::error!(error = %e, "password check failed");
        ApiError::internal()
    })?;
    if let Err(msg) = checked {
        return Err(ApiError::validation([("password".to_string(), vec![msg])].into()));
    }
    // Generic 500 (the detail is only logged); deletion is idempotent, so the client may simply retry.
    crate::account::delete_user(&s, uid).await.map_err(|e| {
        tracing::error!(error = %e, "account deletion failed");
        ApiError::internal()
    })?;
    Ok(StatusCode::NO_CONTENT)
}