Files
sorsfonalak/services/backend/src/routes/mod.rs
T
fecoandClaude Opus 5.5 2a0830fda0
CI / test (push) Successful in 1m29s
CI / build (push) Successful in 9m7s
CI / deploy (push) Skipped
Invoices: issued in Billingo by the worker, downloadable on Számláim
A paid checkout queues an invoice row with every invoice detail (buyer,
tax type and number, item, net, VAT, gross). The worker's new 'invoices'
task creates the Billingo partner and the paid card invoice and e-mails
it (API v3), saving each step so a retry never issues a second invoice,
and keeps Billingo's whole answer; the PDF is fetched from Billingo when
the user downloads it from the new Számláim page (in the menu once there
is an invoice). Payments and invoices outlive a deleted account.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_012vLHzh5qUhFtmJhzkcTbXL
2026-11-20 07:52:34 +00:00

182 lines
8.5 KiB
Rust

//! HTTP routes.
//!
//! Guards: handlers that take [`AuthUser`](crate::auth::AuthUser) require a
//! session, [`AdminUser`](crate::auth::AdminUser) also the admin role.
//! Resources of other users answer 404, so their existence is not revealed.
//! Everything under `/v1/public` is open (shared links, invitation landing).
mod account;
mod admin;
mod analyses;
mod auth;
mod charts;
mod errors;
mod forecasts;
mod invitations;
mod invoices_user;
mod jobs;
mod models;
mod payments;
mod promo;
mod prompts;
mod questions;
mod recalculate;
mod shares;
mod synastries;
pub use recalculate::run as recalculate;
use std::sync::Arc;
use axum::extract::{Path, State};
use axum::http::{HeaderValue, Method, header};
use axum::routing::{delete, get, patch, post};
use axum::{Json, Router};
use axum_extra::extract::WithRejection;
use serde_json::{Value, json};
use tower_http::cors::{AllowOrigin, CorsLayer};
use tower_http::trace::{DefaultMakeSpan, DefaultOnResponse, TraceLayer};
use tracing::Level;
use uuid::Uuid;
use crate::AppState;
use crate::error::ApiError;
/// JSON request body with JSON error responses.
pub type Body<T> = WithRejection<Json<T>, ApiError>;
/// `{id}` path parameter.
pub type IdPath = WithRejection<Path<Uuid>, ApiError>;
pub type St = State<Arc<AppState>>;
/// For PATCH fields: missing = `None` (keep), `null` = `Some(None)` (clear).
pub fn double_option<'de, D, T>(d: D) -> Result<Option<Option<T>>, D::Error>
where
D: serde::Deserializer<'de>,
T: serde::Deserialize<'de>,
{
serde::Deserialize::deserialize(d).map(Some)
}
pub fn router(state: Arc<AppState>) -> Router {
Router::new()
.route("/healthz", get(health))
.route("/v1/config", get(public_config))
.route("/v1/packages", get(payments::catalog))
// login
.route("/v1/auth/register", post(auth::register))
.route("/v1/auth/login", post(auth::login))
.route("/v1/auth/google", post(auth::google))
.route("/v1/auth/logout", post(auth::logout))
.route("/v1/auth/logout-all", post(auth::logout_all))
.route("/v1/auth/verify-email", post(auth::verify_email))
.route("/v1/auth/resend-verification", post(auth::resend_verification))
.route("/v1/auth/password-reset", post(auth::request_password_reset))
.route("/v1/auth/password-reset/confirm", post(auth::confirm_password_reset))
// own account (GDPR export and deletion included)
.route("/v1/me", get(account::me).patch(account::update_me).delete(account::delete_me))
.route("/v1/me/password", post(account::change_password))
.route("/v1/me/export", get(account::export))
.route("/v1/credits", get(account::credits))
.route("/v1/payments/mock", post(payments::mock))
.route("/v1/payments/checkout", post(payments::checkout))
.route("/v1/payments/checkout/{id}", get(payments::checkout_status))
.route("/v1/payments/stripe/webhook", post(payments::stripe_webhook))
.route("/v1/invoices", get(invoices_user::list))
.route("/v1/invoices/{id}/pdf", get(invoices_user::pdf))
// charts
.route("/v1/charts", get(charts::list).post(charts::create))
.route("/v1/charts/{id}", get(charts::get_one).patch(charts::update).delete(charts::remove))
.route("/v1/charts/{id}/analyses", get(analyses::list_for_chart).post(analyses::request_for_chart))
.route("/v1/charts/{id}/summary", post(analyses::summary_for_chart))
.route("/v1/charts/{id}/forecasts", get(forecasts::list_for_chart).post(forecasts::create))
.route("/v1/forecasts/{id}", get(forecasts::get_one))
.route("/v1/forecasts/{id}/analyses", get(analyses::list_for_forecast).post(analyses::request_for_forecast))
// synastries and invitations
.route("/v1/synastries", get(synastries::list).post(synastries::create))
.route("/v1/synastries/{id}", get(synastries::get_one).delete(synastries::remove))
.route("/v1/synastries/{id}/analyses", get(analyses::list_for_synastry).post(analyses::request_for_synastry))
.route("/v1/invites", get(synastries::list_invites).post(synastries::create_invite))
.route("/v1/invites/{id}", delete(synastries::revoke_invite))
.route("/v1/invites/accept", post(synastries::accept_invite))
// analyses
.route("/v1/analyses/{id}", get(analyses::get_one))
.route("/v1/analyses/{id}/questions", get(questions::list).post(questions::ask))
.route("/v1/questions/{id}", get(questions::get_one))
// sharing
.route("/v1/promo-codes/redeem", post(promo::redeem))
.route("/v1/admin/promo-codes", get(promo::list).post(promo::create))
.route("/v1/admin/promo-codes/{id}/revoke", post(promo::revoke))
.route("/v1/shares", get(shares::list).post(shares::create))
.route("/v1/shares/{id}", delete(shares::revoke))
// public, no login
.route("/v1/public/shares/{slug}", get(shares::public_view))
.route("/v1/public/shares/{slug}/visit", post(shares::visit))
.route("/v1/public/invites/{token}", get(synastries::public_invite))
.route("/v1/public/invitations/unsubscribe", post(invitations::unsubscribe))
.route("/v1/public/invitations/{token}", get(invitations::public_view))
.route("/v1/public/waitlist", post(invitations::join_waitlist))
// administration
.route("/v1/admin/users", get(admin::list_users))
.route("/v1/admin/users/{id}", patch(admin::update_user))
.route("/v1/admin/users/{id}/credits", post(admin::adjust_credits))
.route("/v1/admin/users/{id}/packages", post(admin::grant_package))
.route("/v1/admin/invitations", get(invitations::list).post(invitations::create))
.route("/v1/admin/invitations/preview", post(invitations::preview))
.route("/v1/admin/invitations/{id}", delete(invitations::revoke))
.route("/v1/admin/invitations/{id}/resend", post(invitations::resend))
.route("/v1/admin/waitlist/{email}", delete(invitations::remove_from_waitlist))
.route("/v1/admin/prompts", get(prompts::list))
.route("/v1/admin/prompts/{kind}/{language}", axum::routing::put(prompts::save))
.route("/v1/admin/prompts/{kind}/{language}/preview", post(prompts::start_preview))
.route("/v1/admin/previews/{id}", get(prompts::get_preview))
.route("/v1/admin/errors", get(errors::list))
.route("/v1/admin/jobs", get(jobs::list))
.route("/v1/admin/jobs/restart", post(jobs::restart))
.route("/v1/admin/models", get(models::list))
.route("/v1/admin/models/catalog", get(models::catalog))
.route("/v1/admin/models/{kind}", axum::routing::put(models::save))
.route("/v1/admin/analyses/{id}/regenerate", post(analyses::regenerate))
.route("/v1/admin/questions/{id}/regenerate", post(questions::regenerate))
.layer(cors(&state.config.cors_allowed_origins))
.layer(
TraceLayer::new_for_http()
.make_span_with(DefaultMakeSpan::new().level(Level::INFO))
.on_response(DefaultOnResponse::new().level(Level::INFO)),
)
.with_state(state)
}
/// Cookies are sent cross-origin only to the listed origins.
fn cors(origins: &[String]) -> CorsLayer {
CorsLayer::new()
.allow_origin(AllowOrigin::list(origins.iter().filter_map(|o| HeaderValue::from_str(o).ok())))
.allow_methods([Method::GET, Method::POST, Method::PATCH, Method::DELETE])
.allow_headers([header::CONTENT_TYPE, header::AUTHORIZATION])
.allow_credentials(true)
}
async fn health(State(state): St) -> Result<Json<Value>, ApiError> {
sqlx::query("SELECT 1").execute(&state.db).await?;
Ok(Json(json!({ "status": "ok" })))
}
/// What the frontend needs to know before login.
async fn public_config(State(state): St) -> Json<Value> {
let c = &state.config;
Json(json!({
"google_login": { "enabled": state.google.enabled(), "client_id": c.google_client_ids.first() },
"locales": c.supported_locales,
"password_login": c.password_login,
"mock_payments": payments::method(c) == Some("mock"),
// "stripe", "mock" or null; Stripe purchases are for admins only
// until PURCHASES_OPEN (and always with a test key).
"payments": payments::method(c),
"payments_admins_only": payments::admins_only(c),
"payments_test": c.stripe.as_ref().is_some_and(|s| s.test_mode()),
"user_invites": c.user_invites,
"referral_rewards": c.referral_rewards,
"signup_mode": c.signup_mode.as_str(),
"password_min_length": crate::auth::MIN_PASSWORD_LEN,
}))
}