Invoicing: the invoice request is marked before it goes to Billingo; a retry after a lost answer looks the invoice up under the invoice's own partner instead of issuing a second one. An invoice issued but never e-mailed counts as issued (downloadable). A Hungarian company with only an EU VAT number is invoiced without a domestic tax number, the EU number in the comment. Security: the login redirect takes only plain local paths (no backslash); the waitlist rate limit and share visits use X-Real-IP, which Caddy sets from Cloudflare's address, not the spoofable first X-Forwarded-For entry; a Google/Apple sign-in to an unconfirmed password account removes its password and sessions; a person's birth data can no longer be published through a share. Credits and jobs: analysis requests are serialized per user, so a double click queues and pays once; a forecast analysis also fixes a person's birth data; admins can restart stuck tarot readings; a worker forgets an attempt an admin restarted, so a stop does not requeue it; two people accepting one comparison invite at once get one comparison. Expired invitations are no longer accepted by e-mail, and unsubscribing revokes the invitation's promo codes too. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> Claude-Session: https://claude.ai/code/session_012vLHzh5qUhFtmJhzkcTbXL
196 lines
9.5 KiB
Rust
196 lines
9.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;
|
|
pub(crate) mod payments;
|
|
mod promo;
|
|
mod prompts;
|
|
mod questions;
|
|
mod recalculate;
|
|
mod shares;
|
|
mod synastries;
|
|
mod tarot;
|
|
|
|
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::TraceLayer;
|
|
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)
|
|
}
|
|
|
|
/// The visitor's address from `X-Real-IP`: Caddy sets it (overwriting what
|
|
/// the browser sent) from Cloudflare's `CF-Connecting-IP`, trusted only from
|
|
/// Cloudflare's ranges, and the frontend's proxy passes it on. Not
|
|
/// `X-Forwarded-For`, whose first entry the browser can write.
|
|
pub(crate) fn client_ip(headers: &axum::http::HeaderMap) -> Option<String> {
|
|
let ip = headers.get("x-real-ip")?.to_str().ok()?.trim();
|
|
(!ip.is_empty()).then(|| ip.to_string())
|
|
}
|
|
|
|
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/apple", post(auth::apple))
|
|
.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))
|
|
.route("/v1/tarot/readings", get(tarot::list).post(tarot::create))
|
|
.route("/v1/tarot/readings/{id}", get(tarot::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))
|
|
// The request log: masked paths, health checks only when they fail.
|
|
.layer(TraceLayer::new_for_http().make_span_with(service_kit::RequestLog).on_response(service_kit::RequestLog))
|
|
.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() },
|
|
"apple_login": { "enabled": state.apple.enabled(), "client_id": c.apple_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()),
|
|
// "AAM" (alanyi adómentes: the prices carry no VAT) or a rate like "27%".
|
|
"vat": c.invoice_vat.code(),
|
|
// Buyers accept the ÁSZF on Stripe's page (off until the opening).
|
|
"terms_consent": c.terms_consent,
|
|
"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,
|
|
}))
|
|
}
|