Add horoscope-api, synastry, and backend services
- horoscope-api: Swiss Ephemeris natal charts, timezone/place resolution, POST /v1/natal and POST /v1/synastry - backend: users with roles, email/password and Google login, saved charts, synastries and invites, analyses with credit ledger, public shares, admin - shared crates: astro-engine, db (migrations), horoscope-client, service-kit - docker-compose with postgres, legacy Java project for reference Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> Claude-Session: https://claude.ai/code/session_012vLHzh5qUhFtmJhzkcTbXL
This commit is contained in:
@@ -0,0 +1,34 @@
|
||||
[package]
|
||||
name = "backend"
|
||||
description = "Sorsfonalak backend: users, login, charts, synastries, analyses, credits, sharing"
|
||||
edition.workspace = true
|
||||
version.workspace = true
|
||||
license.workspace = true
|
||||
publish.workspace = true
|
||||
|
||||
[dependencies]
|
||||
db.workspace = true
|
||||
horoscope-client.workspace = true
|
||||
service-kit.workspace = true
|
||||
anyhow.workspace = true
|
||||
argon2.workspace = true
|
||||
password-hash = { version = "0.5", features = ["getrandom"] }
|
||||
axum.workspace = true
|
||||
axum-extra.workspace = true
|
||||
jsonwebtoken.workspace = true
|
||||
reqwest.workspace = true
|
||||
serde.workspace = true
|
||||
serde_json.workspace = true
|
||||
sha2.workspace = true
|
||||
sqlx.workspace = true
|
||||
thiserror.workspace = true
|
||||
time.workspace = true
|
||||
tokio.workspace = true
|
||||
tower-http.workspace = true
|
||||
tracing.workspace = true
|
||||
uuid.workspace = true
|
||||
|
||||
[dev-dependencies]
|
||||
jsonwebtoken = { workspace = true, features = ["use_pem"] }
|
||||
tower = { version = "0.5", features = ["util"] }
|
||||
http-body-util = "0.1"
|
||||
@@ -0,0 +1,30 @@
|
||||
# syntax=docker/dockerfile:1
|
||||
#
|
||||
# Build from the repository root:
|
||||
# docker build -f services/backend/Dockerfile -t sorsfonalak/backend .
|
||||
|
||||
ARG RUST_VERSION=1.99
|
||||
|
||||
# --- 1. static (musl) build ----------------------------------------------------
|
||||
FROM rust:${RUST_VERSION}-alpine AS build
|
||||
RUN apk add --no-cache musl-dev
|
||||
WORKDIR /app
|
||||
COPY Cargo.toml Cargo.lock ./
|
||||
COPY crates crates
|
||||
COPY services services
|
||||
RUN --mount=type=cache,target=/usr/local/cargo/registry \
|
||||
--mount=type=cache,target=/app/target \
|
||||
cargo build --release --locked -p backend \
|
||||
&& cp target/release/backend /backend
|
||||
|
||||
# --- 2. runtime: the binary only (TLS roots are compiled in via webpki-roots) ---
|
||||
FROM scratch
|
||||
COPY --from=build /backend /backend
|
||||
ENV BIND_ADDR=0.0.0.0:8081 \
|
||||
LOG_FORMAT=json \
|
||||
RUST_LOG=info
|
||||
USER 65532:65532
|
||||
EXPOSE 8081
|
||||
HEALTHCHECK --interval=30s --timeout=3s --start-period=10s --retries=3 \
|
||||
CMD ["/backend", "healthcheck"]
|
||||
ENTRYPOINT ["/backend"]
|
||||
@@ -0,0 +1,112 @@
|
||||
# backend
|
||||
|
||||
Felhasználók, belépés, mentett születési képletek, szinasztriák és meghívók, szöveges elemzések, kreditek és nyilvános megosztás. A képleteket a `horoscope-api` számolja, az adatok PostgreSQL-ben vannak. A migrációk a `crates/db/migrations` mappában vannak, és induláskor lefutnak.
|
||||
|
||||
## Konfiguráció (környezeti változók)
|
||||
|
||||
| Változó | Alapérték | Jelentés |
|
||||
|---|---|---|
|
||||
| `DATABASE_URL` | – (kötelező) | PostgreSQL kapcsolat |
|
||||
| `HOROSCOPE_API_URL` | `http://localhost:8080` | a számító szolgáltatás |
|
||||
| `PUBLIC_BASE_URL` | `http://localhost:3000` | a frontend címe; erre mutatnak a meghívó-, e-mail- és megosztási linkek |
|
||||
| `CORS_ALLOWED_ORIGINS` | `PUBLIC_BASE_URL` | vesszővel elválasztott origin-lista; csak ezekről küld a böngésző sütit |
|
||||
| `COOKIE_SECURE` | `true` | csak helyi, sima HTTP-s fejlesztéshez legyen `false` |
|
||||
| `COOKIE_DOMAIN` | – | pl. `.sorsfonalak.hu`, ha a frontend és az API más aldomainen fut |
|
||||
| `SESSION_TTL_DAYS` | `30` | a munkamenet élettartama |
|
||||
| `GOOGLE_CLIENT_IDS` | – | Google OAuth kliens-azonosító(k); üresen a Google-belépés ki van kapcsolva |
|
||||
| `BOOTSTRAP_ADMIN_EMAILS` | – | ezek a címek regisztrációkor vagy belépéskor admin szerepet kapnak (így lesz meg az első admin) |
|
||||
| `SUPPORTED_LOCALES` | `hu,en` | felület- és elemzésnyelvek; az első az alapértelmezett |
|
||||
| `MONTHLY_FREE_CREDITS` | `10` | havi ingyenes kreditkeret |
|
||||
| `ANALYSIS_COST` | `1` | egy új elemzés ára kreditben |
|
||||
| `LLM_MODELS` | `openrouter/auto` | választható OpenRouter-modellek; az első az alapértelmezett |
|
||||
| `ANALYSIS_PROMPT_VERSION` | `v1` | a prompt verziója (az elemzés-gyorsítótár kulcsának része) |
|
||||
| `MAX_CHARTS_PER_USER` | `50` | ennyi képletet menthet egy felhasználó |
|
||||
| `BIND_ADDR`, `LOG_FORMAT`, `RUST_LOG` | `0.0.0.0:8081`, `text`, `info` | |
|
||||
|
||||
## Belépés és jogosultság
|
||||
|
||||
- **Munkamenet:** véletlen token, HttpOnly + SameSite=Lax sütiben (`sf_session`). A belépési válasz törzsében is ott van, hogy nem böngészős kliens `Authorization: Bearer <token>` fejléccel küldhesse vissza. Az adatbázis csak a token SHA-256 hash-ét tárolja, így a munkamenet visszavonható (kijelentkezés, jelszócsere, fióktörlés).
|
||||
- **E-mail + jelszó:**
|
||||
- a jelszó legalább 10 karakter, Argon2id hash-sel tárolva;
|
||||
- címenként 15 percen belül 10 hibás próbálkozás után átmenetileg tiltás jár;
|
||||
- ismeretlen címnél is ugyanannyi ideig tart a válasz.
|
||||
- **Google:** a frontend a Google Identity Services gombbal vagy a One Tap felülettel szerez ID tokent, és elküldi a `POST /v1/auth/google` végpontra. A backend Google kulcsaival ellenőrzi az aláírást, a kiállítót és a kliens-azonosítót.
|
||||
- Ismeretlen Google-fióknál, ha a Google által igazolt e-mail-címmel már van felhasználó, ahhoz kapcsolja; ha nincs, újat hoz létre.
|
||||
- Ugyanaz a felhasználó több belépési móddal is rendelkezhet (`auth_identities`). A Facebook, az Apple és a passkey ugyanígy adható hozzá.
|
||||
- **Szerepek** (`users.roles`, tömb): `user` (alap), `creator` (cikkírás, 2. fázis), `admin`.
|
||||
- **Guardok:**
|
||||
- `AuthUser`: belépés kell (401);
|
||||
- `AdminUser`: admin szerep is kell (403).
|
||||
- Más felhasználó erőforrására 404 a válasz, így a létezése sem derül ki.
|
||||
- Minden `/v1/public/...` végpont nyilvános.
|
||||
|
||||
## Végpontok
|
||||
|
||||
| Végpont | Guard | Leírás |
|
||||
|---|---|---|
|
||||
| `GET /v1/config` | – | Google kliens-azonosító, nyelvek, modellek, kreditárak |
|
||||
| `POST /v1/auth/register` | – | `{email, password, display_name?, locale?}` → munkamenet; megerősítő e-mailt küld |
|
||||
| `POST /v1/auth/login` | – | `{email, password}` |
|
||||
| `POST /v1/auth/google` | – | `{id_token}`; `created: true`, ha most jött létre a fiók |
|
||||
| `POST /v1/auth/logout`, `/logout-all` | user | kijelentkezés erről, illetve minden eszközről |
|
||||
| `POST /v1/auth/verify-email` | – | `{token}` az e-mailben kapott linkből |
|
||||
| `POST /v1/auth/resend-verification` | user | |
|
||||
| `POST /v1/auth/password-reset` | – | `{email}`; mindig 202 |
|
||||
| `POST /v1/auth/password-reset/confirm` | – | `{token, password}`; minden munkamenet megszűnik |
|
||||
| `GET`/`PATCH`/`DELETE /v1/me` | user | profil (`display_name`, `locale`); törlés: `{confirm: "DELETE"}` |
|
||||
| `POST /v1/me/password` | user | `{current_password?, new_password}`; Google-fiókhoz jelszót is ad |
|
||||
| `GET /v1/me/export` | user | GDPR: minden adat egy JSON-ban |
|
||||
| `GET /v1/credits` | user | egyenleg és kreditmozgások |
|
||||
| `GET`/`POST /v1/charts` | user | képletek listája; új képlet: `{label, is_primary, birth}`, ahol a `birth` a horoscope-api `/v1/natal` kérésformátuma |
|
||||
| `GET`/`PATCH`/`DELETE /v1/charts/{id}` | tulajdonos | a születési adat nem módosítható: a javított képlet új képlet |
|
||||
| `GET`/`POST /v1/synastries` | user | `{chart1_id, chart2_id}`, mindkét képlet a sajátod |
|
||||
| `GET`/`DELETE /v1/synastries/{id}` | résztvevő | |
|
||||
| `GET`/`POST /v1/invites` | user | „Mennyire illünk össze?” link; alapból a saját (primary) képlettel |
|
||||
| `DELETE /v1/invites/{id}` | meghívó | visszavonás |
|
||||
| `GET /v1/public/invites/{token}` | – | a meghívó landing oldalának adatai |
|
||||
| `POST /v1/invites/accept` | user | `{token, chart_id?}`: elkészül a szinasztria, mindketten látják, a meghívó e-mailt kap |
|
||||
| `GET`/`POST /v1/charts/{id}/analyses` | tulajdonos | `{language?, model?}` |
|
||||
| `GET`/`POST /v1/synastries/{id}/analyses` | résztvevő | |
|
||||
| `GET /v1/analyses/{id}` | jogosult | |
|
||||
| `GET`/`POST /v1/shares`, `DELETE /v1/shares/{id}` | user | `{kind: chart\|synastry\|analysis, target_id, title?, show_birth_data?}` |
|
||||
| `GET /v1/public/shares/{slug}` | – | a megosztott tartalom (oldal + OG-kép adatai) |
|
||||
| `GET /v1/admin/users?q=` | admin | felhasználók kereséssel, szerepekkel, kreditekkel |
|
||||
| `PATCH /v1/admin/users/{id}` | admin | `{roles: [...]}`; a saját admin szerep nem vehető el |
|
||||
| `POST /v1/admin/users/{id}/credits` | admin | `{delta, note?}` |
|
||||
|
||||
Hibák formátuma: `{"error": {"code", "message"}}`. A születési adatok hibái (például ismeretlen hely, javaslatokkal együtt) változatlanul jönnek tovább a horoscope-api-ból.
|
||||
|
||||
## Adatmodell
|
||||
|
||||
| Tábla | Mire |
|
||||
|---|---|
|
||||
| `users` | e-mail, megerősítés, név, nyelv, `roles text[]` |
|
||||
| `auth_identities` | belépési módok: `password` (hash) / `google` (sub) / később `facebook`, `apple` |
|
||||
| `sessions`, `auth_tokens` | munkamenetek; egyszer használatos e-mail-tokenek (megerősítés, jelszó-visszaállítás) |
|
||||
| `charts` | a felhasználó képletei: `birth_data` (kérés), `result` (teljes számítás), `chart_hash`, `is_primary` (legfeljebb egy) |
|
||||
| `synastries` | két képlet összevetése (`result`: fényszögek, házak, kompozit), `synastry_hash` |
|
||||
| `synastry_invites` | meghívó linkek: token hash, lejárat, ki fogadta el, melyik szinasztria lett belőle |
|
||||
| `analyses` | szöveges elemzések: típus, nyelv, modell, promptverzió, `cache_key`, állapot (`pending` → `running` → `done`/`failed`), strukturált `content` |
|
||||
| `credit_ledger` | csak hozzáírható kreditnapló; az egyenleg `SUM(delta)`; havi keret lustán, egyszer havonta |
|
||||
| `shares` | nyilvános linkek: véletlen `slug`, mit mutat, `show_birth_data`, nézettség, visszavonás |
|
||||
| `email_outbox` | kimenő e-mailek; a worker küldi ki |
|
||||
|
||||
**Adatvédelem:**
|
||||
- A születési adatokból a `name` mező nem kerül tárolásra, és nem megy tovább a számításhoz (később az LLM-hez sem).
|
||||
- A nyilvános megosztás alapból nem mutat születési dátumot, időt és helyet. A `show_birth_data: true` csak a megosztó saját képletére vonatkozik, a partneréire soha.
|
||||
- A szinasztria másik fele csak a pozíciókat látja, a születési adatokat nem.
|
||||
- A fiók törlése mindent töröl, ami a felhasználóhoz tartozik, beleértve a más által létrehozott, de az ő képletét használó szinasztriákat is.
|
||||
|
||||
## Elemzések és kreditek
|
||||
|
||||
- **Kérés:** a `POST .../analyses` létrehoz egy `pending` elemzést, és levonja az `ANALYSIS_COST` kreditet; a szöveget később a worker írja meg. Ha nincs elég kredit, 402 `insufficient_credits` a válasz.
|
||||
- **Gyorsítótár:** a kulcs `sha256(típus | képlet- vagy szinasztria-hash | promptverzió | modell | nyelv)`.
|
||||
- Ha ugyanarra a képletre már kértek ilyet, ugyanazt adja vissza (200).
|
||||
- Ha bárhol van kész elemzés ugyanezzel a kulccsal (például ugyanaz a születési adat egy másik felhasználónál), ingyen átmásolja (201, `done`).
|
||||
|
||||
## Ami még hátravan (a worker dolga)
|
||||
|
||||
- e-mailek kiküldése az `email_outbox`-ból;
|
||||
- az elemzések megírása (OpenRouter, strukturált JSON, streaming);
|
||||
- sikertelen elemzésnél a kredit visszatérítése (`refund`);
|
||||
- lejárt munkamenetek és tokenek takarítása.
|
||||
@@ -0,0 +1,254 @@
|
||||
//! Sessions, passwords and the request guards.
|
||||
//!
|
||||
//! A session is an opaque random token. The client receives it as an
|
||||
//! HttpOnly cookie (`sf_session`) and in the login response body (for
|
||||
//! non-browser clients, sent back as `Authorization: Bearer <token>`); the
|
||||
//! database keeps only its SHA-256 hash, so sessions can be revoked.
|
||||
|
||||
use std::collections::HashMap;
|
||||
use std::sync::{Arc, Mutex};
|
||||
use std::time::{Duration, Instant};
|
||||
|
||||
use argon2::Argon2;
|
||||
use argon2::password_hash::rand_core::OsRng;
|
||||
use argon2::password_hash::{PasswordHash, PasswordHasher, PasswordVerifier, SaltString};
|
||||
use axum::extract::FromRequestParts;
|
||||
use axum::http::header::{AUTHORIZATION, USER_AGENT};
|
||||
use axum::http::request::Parts;
|
||||
use axum_extra::extract::cookie::{Cookie, CookieJar, SameSite};
|
||||
use db::{Role, User};
|
||||
use serde::Serialize;
|
||||
use sqlx::PgPool;
|
||||
use time::OffsetDateTime;
|
||||
use uuid::Uuid;
|
||||
|
||||
use crate::AppState;
|
||||
use crate::config::Config;
|
||||
use crate::error::ApiError;
|
||||
|
||||
pub const SESSION_COOKIE: &str = "sf_session";
|
||||
pub const MIN_PASSWORD_LEN: usize = 10;
|
||||
pub const MAX_PASSWORD_LEN: usize = 256;
|
||||
|
||||
// --- guards ------------------------------------------------------------------------
|
||||
|
||||
/// Guard: a logged-in user (401 otherwise).
|
||||
#[derive(Debug, Clone)]
|
||||
pub struct AuthUser {
|
||||
pub user: User,
|
||||
pub session_id: Uuid,
|
||||
}
|
||||
|
||||
impl AuthUser {
|
||||
pub fn id(&self) -> Uuid {
|
||||
self.user.id
|
||||
}
|
||||
|
||||
pub fn require(&self, role: Role) -> Result<(), ApiError> {
|
||||
if self.user.has_role(role) {
|
||||
Ok(())
|
||||
} else {
|
||||
Err(ApiError::Forbidden(format!("the '{}' role is required", role.as_str())))
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
fn session_token(parts: &Parts) -> Option<String> {
|
||||
if let Some(value) = parts.headers.get(AUTHORIZATION).and_then(|v| v.to_str().ok())
|
||||
&& let Some(token) = value.strip_prefix("Bearer ")
|
||||
{
|
||||
return Some(token.trim().to_string());
|
||||
}
|
||||
CookieJar::from_headers(&parts.headers).get(SESSION_COOKIE).map(|c| c.value().to_string())
|
||||
}
|
||||
|
||||
impl FromRequestParts<Arc<AppState>> for AuthUser {
|
||||
type Rejection = ApiError;
|
||||
|
||||
async fn from_request_parts(parts: &mut Parts, state: &Arc<AppState>) -> Result<Self, Self::Rejection> {
|
||||
let token = session_token(parts).ok_or(ApiError::Unauthorized)?;
|
||||
let (session_id, user) = db::user_by_session(&state.db, &token).await?.ok_or(ApiError::Unauthorized)?;
|
||||
Ok(AuthUser { user, session_id })
|
||||
}
|
||||
}
|
||||
|
||||
/// Guard: a logged-in user with the admin role (401 / 403 otherwise).
|
||||
pub struct AdminUser(pub AuthUser);
|
||||
|
||||
impl FromRequestParts<Arc<AppState>> for AdminUser {
|
||||
type Rejection = ApiError;
|
||||
|
||||
async fn from_request_parts(parts: &mut Parts, state: &Arc<AppState>) -> Result<Self, Self::Rejection> {
|
||||
let user = AuthUser::from_request_parts(parts, state).await?;
|
||||
user.require(Role::Admin)?;
|
||||
Ok(AdminUser(user))
|
||||
}
|
||||
}
|
||||
|
||||
pub fn user_agent(parts_headers: &axum::http::HeaderMap) -> Option<String> {
|
||||
parts_headers.get(USER_AGENT).and_then(|v| v.to_str().ok()).map(|s| s.chars().take(300).collect())
|
||||
}
|
||||
|
||||
// --- sessions ----------------------------------------------------------------------
|
||||
|
||||
#[derive(Debug, Serialize)]
|
||||
pub struct SessionInfo {
|
||||
pub token: String,
|
||||
#[serde(with = "time::serde::rfc3339")]
|
||||
pub expires_at: OffsetDateTime,
|
||||
}
|
||||
|
||||
pub async fn create_session(
|
||||
pool: &PgPool,
|
||||
config: &Config,
|
||||
user_id: Uuid,
|
||||
user_agent: Option<String>,
|
||||
) -> Result<SessionInfo, ApiError> {
|
||||
let token = db::new_token();
|
||||
let expires_at = OffsetDateTime::now_utc() + time::Duration::days(config.session_ttl_days);
|
||||
sqlx::query("INSERT INTO sessions (id, user_id, token_hash, expires_at, user_agent) VALUES ($1, $2, $3, $4, $5)")
|
||||
.bind(Uuid::now_v7())
|
||||
.bind(user_id)
|
||||
.bind(db::token_hash(&token))
|
||||
.bind(expires_at)
|
||||
.bind(user_agent)
|
||||
.execute(pool)
|
||||
.await?;
|
||||
sqlx::query("UPDATE users SET last_login_at = now() WHERE id = $1").bind(user_id).execute(pool).await?;
|
||||
// Housekeeping: drop this user's expired sessions.
|
||||
sqlx::query("DELETE FROM sessions WHERE user_id = $1 AND expires_at <= now()").bind(user_id).execute(pool).await?;
|
||||
Ok(SessionInfo { token, expires_at })
|
||||
}
|
||||
|
||||
pub fn session_cookie(config: &Config, session: &SessionInfo) -> Cookie<'static> {
|
||||
let mut cookie = Cookie::build((SESSION_COOKIE, session.token.clone()))
|
||||
.path("/")
|
||||
.http_only(true)
|
||||
.secure(config.cookie_secure)
|
||||
.same_site(SameSite::Lax)
|
||||
.max_age(time::Duration::days(config.session_ttl_days))
|
||||
.build();
|
||||
if let Some(domain) = &config.cookie_domain {
|
||||
cookie.set_domain(domain.clone());
|
||||
}
|
||||
cookie
|
||||
}
|
||||
|
||||
pub fn removal_cookie(config: &Config) -> Cookie<'static> {
|
||||
let mut cookie = Cookie::build((SESSION_COOKIE, "")).path("/").max_age(time::Duration::ZERO).build();
|
||||
if let Some(domain) = &config.cookie_domain {
|
||||
cookie.set_domain(domain.clone());
|
||||
}
|
||||
cookie
|
||||
}
|
||||
|
||||
// --- passwords ---------------------------------------------------------------------
|
||||
|
||||
pub fn validate_password(password: &str) -> Result<(), ApiError> {
|
||||
let len = password.chars().count();
|
||||
if len < MIN_PASSWORD_LEN {
|
||||
return Err(ApiError::BadRequest(format!("the password must be at least {MIN_PASSWORD_LEN} characters long")));
|
||||
}
|
||||
if len > MAX_PASSWORD_LEN {
|
||||
return Err(ApiError::BadRequest(format!("the password must be at most {MAX_PASSWORD_LEN} characters long")));
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// Argon2id hash (PHC string); CPU-heavy, so it runs on the blocking pool.
|
||||
pub async fn hash_password(password: String) -> Result<String, ApiError> {
|
||||
tokio::task::spawn_blocking(move || {
|
||||
let salt = SaltString::generate(&mut OsRng);
|
||||
Argon2::default().hash_password(password.as_bytes(), &salt).map(|h| h.to_string())
|
||||
})
|
||||
.await
|
||||
.map_err(|e| ApiError::Internal(e.to_string()))?
|
||||
.map_err(|e| ApiError::Internal(format!("password hashing: {e}")))
|
||||
}
|
||||
|
||||
pub async fn verify_password(password: String, hash: String) -> Result<bool, ApiError> {
|
||||
tokio::task::spawn_blocking(move || {
|
||||
let parsed = PasswordHash::new(&hash).map_err(|e| e.to_string())?;
|
||||
Ok::<bool, String>(Argon2::default().verify_password(password.as_bytes(), &parsed).is_ok())
|
||||
})
|
||||
.await
|
||||
.map_err(|e| ApiError::Internal(e.to_string()))?
|
||||
.map_err(|e| ApiError::Internal(format!("stored password hash: {e}")))
|
||||
}
|
||||
|
||||
/// A precomputed hash verified when the e-mail is unknown, so the response
|
||||
/// time does not reveal which addresses are registered.
|
||||
pub static DUMMY_HASH: std::sync::LazyLock<String> = std::sync::LazyLock::new(|| {
|
||||
let salt = SaltString::generate(&mut OsRng);
|
||||
Argon2::default().hash_password(b"dummy password", &salt).expect("hashing works").to_string()
|
||||
});
|
||||
|
||||
// --- brute-force protection ----------------------------------------------------------
|
||||
|
||||
/// Counts failed logins per e-mail address in a sliding window (in memory,
|
||||
/// per backend instance).
|
||||
pub struct LoginLimiter {
|
||||
max_failures: u32,
|
||||
window: Duration,
|
||||
failures: Mutex<HashMap<String, (u32, Instant)>>,
|
||||
}
|
||||
|
||||
impl LoginLimiter {
|
||||
pub fn new(max_failures: u32, window: Duration) -> Self {
|
||||
Self { max_failures, window, failures: Mutex::new(HashMap::new()) }
|
||||
}
|
||||
|
||||
pub fn check(&self, key: &str) -> Result<(), ApiError> {
|
||||
let mut map = self.failures.lock().expect("limiter lock");
|
||||
match map.get(key) {
|
||||
Some(&(count, since)) if since.elapsed() < self.window && count >= self.max_failures => {
|
||||
Err(ApiError::TooManyRequests)
|
||||
}
|
||||
Some(&(_, since)) if since.elapsed() >= self.window => {
|
||||
map.remove(key);
|
||||
Ok(())
|
||||
}
|
||||
_ => Ok(()),
|
||||
}
|
||||
}
|
||||
|
||||
pub fn failed(&self, key: &str) {
|
||||
let mut map = self.failures.lock().expect("limiter lock");
|
||||
if map.len() > 100_000 {
|
||||
let window = self.window;
|
||||
map.retain(|_, (_, since)| since.elapsed() < window);
|
||||
}
|
||||
let entry = map.entry(key.to_string()).or_insert((0, Instant::now()));
|
||||
entry.0 += 1;
|
||||
}
|
||||
|
||||
pub fn succeeded(&self, key: &str) {
|
||||
self.failures.lock().expect("limiter lock").remove(key);
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
#[tokio::test]
|
||||
async fn password_roundtrip() {
|
||||
let hash = hash_password("correct horse battery".into()).await.unwrap();
|
||||
assert!(hash.starts_with("$argon2id$"));
|
||||
assert!(verify_password("correct horse battery".into(), hash.clone()).await.unwrap());
|
||||
assert!(!verify_password("wrong password!!".into(), hash).await.unwrap());
|
||||
assert!(validate_password("short").is_err());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn limiter_blocks_after_failures() {
|
||||
let limiter = LoginLimiter::new(2, Duration::from_secs(60));
|
||||
assert!(limiter.check("a").is_ok());
|
||||
limiter.failed("a");
|
||||
limiter.failed("a");
|
||||
assert!(limiter.check("a").is_err());
|
||||
assert!(limiter.check("b").is_ok());
|
||||
limiter.succeeded("a");
|
||||
assert!(limiter.check("a").is_ok());
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,133 @@
|
||||
//! Configuration from the environment.
|
||||
|
||||
use anyhow::{Context, bail};
|
||||
|
||||
#[derive(Debug, Clone)]
|
||||
pub struct Config {
|
||||
/// `DATABASE_URL` (required).
|
||||
pub database_url: String,
|
||||
/// `HOROSCOPE_API_URL` (default `http://localhost:8080`).
|
||||
pub horoscope_api_url: String,
|
||||
/// `PUBLIC_BASE_URL`: the frontend's address, used in invitation and
|
||||
/// e-mail links (default `http://localhost:3000`).
|
||||
pub public_base_url: String,
|
||||
/// `CORS_ALLOWED_ORIGINS`: comma-separated origins allowed to call the API
|
||||
/// with cookies (default: `PUBLIC_BASE_URL`).
|
||||
pub cors_allowed_origins: Vec<String>,
|
||||
/// `COOKIE_SECURE` (default `true`); set `false` only for plain-HTTP development.
|
||||
pub cookie_secure: bool,
|
||||
/// `COOKIE_DOMAIN`: e.g. `.sorsfonalak.hu` to share the session between
|
||||
/// the frontend and the API subdomain (default: host-only cookie).
|
||||
pub cookie_domain: Option<String>,
|
||||
/// `SESSION_TTL_DAYS` (default 30).
|
||||
pub session_ttl_days: i64,
|
||||
/// `GOOGLE_CLIENT_IDS`: comma-separated OAuth client ids accepted as the
|
||||
/// ID token audience; empty disables Google login.
|
||||
pub google_client_ids: Vec<String>,
|
||||
/// `GOOGLE_JWKS_URL` (default Google's certificate endpoint).
|
||||
pub google_jwks_url: String,
|
||||
/// `BOOTSTRAP_ADMIN_EMAILS`: these users get the admin role when they
|
||||
/// register or log in (to create the first administrator).
|
||||
pub bootstrap_admin_emails: Vec<String>,
|
||||
/// `SUPPORTED_LOCALES` (default `hu,en`); the first is the default.
|
||||
pub supported_locales: Vec<String>,
|
||||
/// `MONTHLY_FREE_CREDITS` (default 10).
|
||||
pub monthly_free_credits: i32,
|
||||
/// `ANALYSIS_COST` credits per new analysis (default 1).
|
||||
pub analysis_cost: i32,
|
||||
/// `LLM_MODELS`: comma-separated OpenRouter model ids users may choose;
|
||||
/// the first is the default (default `openrouter/auto`).
|
||||
pub llm_models: Vec<String>,
|
||||
/// `ANALYSIS_PROMPT_VERSION` (default `v1`); part of the analysis cache key.
|
||||
pub prompt_version: String,
|
||||
/// `MAX_CHARTS_PER_USER` (default 50).
|
||||
pub max_charts_per_user: i64,
|
||||
}
|
||||
|
||||
fn var(name: &str) -> Option<String> {
|
||||
std::env::var(name).ok().map(|v| v.trim().to_string()).filter(|v| !v.is_empty())
|
||||
}
|
||||
|
||||
fn list(name: &str) -> Vec<String> {
|
||||
var(name)
|
||||
.map(|v| v.split(',').map(|s| s.trim().to_string()).filter(|s| !s.is_empty()).collect())
|
||||
.unwrap_or_default()
|
||||
}
|
||||
|
||||
fn parsed<T: std::str::FromStr>(name: &str, default: T) -> anyhow::Result<T>
|
||||
where
|
||||
T::Err: std::fmt::Display,
|
||||
{
|
||||
match var(name) {
|
||||
Some(v) => v.parse().map_err(|e| anyhow::anyhow!("invalid {name} '{v}': {e}")),
|
||||
None => Ok(default),
|
||||
}
|
||||
}
|
||||
|
||||
impl Config {
|
||||
pub fn from_env() -> anyhow::Result<Self> {
|
||||
let public_base_url =
|
||||
var("PUBLIC_BASE_URL").unwrap_or_else(|| "http://localhost:3000".into()).trim_end_matches('/').to_string();
|
||||
let mut cors_allowed_origins = list("CORS_ALLOWED_ORIGINS");
|
||||
if cors_allowed_origins.is_empty() {
|
||||
cors_allowed_origins.push(public_base_url.clone());
|
||||
}
|
||||
let mut supported_locales = list("SUPPORTED_LOCALES");
|
||||
if supported_locales.is_empty() {
|
||||
supported_locales = vec!["hu".into(), "en".into()];
|
||||
}
|
||||
let mut llm_models = list("LLM_MODELS");
|
||||
if llm_models.is_empty() {
|
||||
llm_models.push("openrouter/auto".into());
|
||||
}
|
||||
let config = Self {
|
||||
database_url: var("DATABASE_URL").context("DATABASE_URL is required")?,
|
||||
horoscope_api_url: var("HOROSCOPE_API_URL").unwrap_or_else(|| "http://localhost:8080".into()),
|
||||
public_base_url,
|
||||
cors_allowed_origins,
|
||||
cookie_secure: parsed("COOKIE_SECURE", true)?,
|
||||
cookie_domain: var("COOKIE_DOMAIN"),
|
||||
session_ttl_days: parsed("SESSION_TTL_DAYS", 30)?,
|
||||
google_client_ids: list("GOOGLE_CLIENT_IDS"),
|
||||
google_jwks_url: var("GOOGLE_JWKS_URL")
|
||||
.unwrap_or_else(|| "https://www.googleapis.com/oauth2/v3/certs".into()),
|
||||
bootstrap_admin_emails: list("BOOTSTRAP_ADMIN_EMAILS").into_iter().map(|e| e.to_lowercase()).collect(),
|
||||
supported_locales,
|
||||
monthly_free_credits: parsed("MONTHLY_FREE_CREDITS", 10)?,
|
||||
analysis_cost: parsed("ANALYSIS_COST", 1)?,
|
||||
llm_models,
|
||||
prompt_version: var("ANALYSIS_PROMPT_VERSION").unwrap_or_else(|| "v1".into()),
|
||||
max_charts_per_user: parsed("MAX_CHARTS_PER_USER", 50)?,
|
||||
};
|
||||
if config.session_ttl_days < 1 {
|
||||
bail!("SESSION_TTL_DAYS must be at least 1");
|
||||
}
|
||||
if config.monthly_free_credits < 0 || config.analysis_cost < 0 {
|
||||
bail!("MONTHLY_FREE_CREDITS and ANALYSIS_COST must not be negative");
|
||||
}
|
||||
Ok(config)
|
||||
}
|
||||
|
||||
/// Defaults for tests.
|
||||
#[cfg(test)]
|
||||
pub fn for_tests(database_url: String, horoscope_api_url: String, google_jwks_url: String) -> Self {
|
||||
Self {
|
||||
database_url,
|
||||
horoscope_api_url,
|
||||
public_base_url: "https://sorsfonalak.test".into(),
|
||||
cors_allowed_origins: vec!["https://sorsfonalak.test".into()],
|
||||
cookie_secure: true,
|
||||
cookie_domain: None,
|
||||
session_ttl_days: 30,
|
||||
google_client_ids: vec!["test-client.apps.googleusercontent.com".into()],
|
||||
google_jwks_url,
|
||||
bootstrap_admin_emails: vec!["admin@example.com".into()],
|
||||
supported_locales: vec!["hu".into(), "en".into()],
|
||||
monthly_free_credits: 2,
|
||||
analysis_cost: 1,
|
||||
llm_models: vec!["openrouter/auto".into(), "anthropic/claude-test".into()],
|
||||
prompt_version: "v1".into(),
|
||||
max_charts_per_user: 50,
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,78 @@
|
||||
//! Credit ledger: every LLM call costs credits; users get a free monthly
|
||||
//! allowance, granted lazily on the first balance query or spend of a month.
|
||||
|
||||
use sqlx::{PgConnection, PgPool};
|
||||
use time::OffsetDateTime;
|
||||
use uuid::Uuid;
|
||||
|
||||
use crate::error::ApiError;
|
||||
|
||||
pub fn current_period() -> String {
|
||||
let now = OffsetDateTime::now_utc();
|
||||
format!("{:04}-{:02}", now.year(), u8::from(now.month()))
|
||||
}
|
||||
|
||||
/// Grants this month's free credits if not granted yet.
|
||||
pub async fn ensure_monthly_grant(conn: &mut PgConnection, user_id: Uuid, amount: i32) -> Result<(), ApiError> {
|
||||
if amount <= 0 {
|
||||
return Ok(());
|
||||
}
|
||||
sqlx::query(
|
||||
"INSERT INTO credit_ledger (id, user_id, delta, reason, period, note) \
|
||||
VALUES ($1, $2, $3, 'monthly_grant', $4, 'monthly free credits') \
|
||||
ON CONFLICT (user_id, period) WHERE reason = 'monthly_grant' DO NOTHING",
|
||||
)
|
||||
.bind(Uuid::now_v7())
|
||||
.bind(user_id)
|
||||
.bind(amount)
|
||||
.bind(current_period())
|
||||
.execute(conn)
|
||||
.await?;
|
||||
Ok(())
|
||||
}
|
||||
|
||||
pub async fn balance_of(conn: &mut PgConnection, user_id: Uuid) -> Result<i64, ApiError> {
|
||||
let (balance,): (i64,) =
|
||||
sqlx::query_as("SELECT COALESCE(SUM(delta), 0)::bigint FROM credit_ledger WHERE user_id = $1")
|
||||
.bind(user_id)
|
||||
.fetch_one(conn)
|
||||
.await?;
|
||||
Ok(balance)
|
||||
}
|
||||
|
||||
/// Current balance including this month's allowance.
|
||||
pub async fn balance(pool: &PgPool, user_id: Uuid, monthly: i32) -> Result<i64, ApiError> {
|
||||
let mut conn = pool.acquire().await?;
|
||||
ensure_monthly_grant(&mut conn, user_id, monthly).await?;
|
||||
balance_of(&mut conn, user_id).await
|
||||
}
|
||||
|
||||
/// Spends `cost` credits inside the caller's transaction. The user row is
|
||||
/// locked so concurrent requests cannot overspend.
|
||||
pub async fn spend(
|
||||
tx: &mut PgConnection,
|
||||
user_id: Uuid,
|
||||
cost: i32,
|
||||
monthly: i32,
|
||||
reason: &str,
|
||||
analysis_id: Option<Uuid>,
|
||||
) -> Result<(), ApiError> {
|
||||
if cost <= 0 {
|
||||
return Ok(());
|
||||
}
|
||||
sqlx::query("SELECT id FROM users WHERE id = $1 FOR UPDATE").bind(user_id).execute(&mut *tx).await?;
|
||||
ensure_monthly_grant(tx, user_id, monthly).await?;
|
||||
let balance = balance_of(tx, user_id).await?;
|
||||
if balance < i64::from(cost) {
|
||||
return Err(ApiError::InsufficientCredits { needed: cost, balance });
|
||||
}
|
||||
sqlx::query("INSERT INTO credit_ledger (id, user_id, delta, reason, analysis_id) VALUES ($1, $2, $3, $4, $5)")
|
||||
.bind(Uuid::now_v7())
|
||||
.bind(user_id)
|
||||
.bind(-cost)
|
||||
.bind(reason)
|
||||
.bind(analysis_id)
|
||||
.execute(tx)
|
||||
.await?;
|
||||
Ok(())
|
||||
}
|
||||
@@ -0,0 +1,119 @@
|
||||
use axum::Json;
|
||||
use axum::extract::rejection::{JsonRejection, PathRejection, QueryRejection};
|
||||
use axum::http::StatusCode;
|
||||
use axum::response::{IntoResponse, Response};
|
||||
use horoscope_client::HoroscopeError;
|
||||
use serde_json::{Value, json};
|
||||
|
||||
/// API error, rendered as `{"error": {"code", "message"}}`.
|
||||
#[derive(Debug, thiserror::Error)]
|
||||
pub enum ApiError {
|
||||
#[error("{0}")]
|
||||
BadRequest(String),
|
||||
#[error("authentication required")]
|
||||
Unauthorized,
|
||||
#[error("{0}")]
|
||||
InvalidCredentials(String),
|
||||
#[error("{0}")]
|
||||
Forbidden(String),
|
||||
#[error("{0} not found")]
|
||||
NotFound(&'static str),
|
||||
#[error("{message}")]
|
||||
Conflict { code: &'static str, message: String },
|
||||
#[error("{0}")]
|
||||
Gone(String),
|
||||
#[error("the link is invalid or has expired")]
|
||||
InvalidToken,
|
||||
#[error("not enough credits: {needed} needed, {balance} available")]
|
||||
InsufficientCredits { needed: i32, balance: i64 },
|
||||
#[error("too many attempts; try again later")]
|
||||
TooManyRequests,
|
||||
/// Birth data rejected by the horoscope service; its error object is passed through.
|
||||
#[error("invalid birth data")]
|
||||
BirthData { status: StatusCode, body: Value },
|
||||
#[error("horoscope service unavailable")]
|
||||
HoroscopeUnavailable(String),
|
||||
#[error("internal error")]
|
||||
Internal(String),
|
||||
}
|
||||
|
||||
impl ApiError {
|
||||
pub fn conflict(code: &'static str, message: impl Into<String>) -> Self {
|
||||
ApiError::Conflict { code, message: message.into() }
|
||||
}
|
||||
|
||||
fn status_and_code(&self) -> (StatusCode, &'static str) {
|
||||
match self {
|
||||
ApiError::BadRequest(_) => (StatusCode::BAD_REQUEST, "bad_request"),
|
||||
ApiError::Unauthorized => (StatusCode::UNAUTHORIZED, "unauthorized"),
|
||||
ApiError::InvalidCredentials(_) => (StatusCode::UNAUTHORIZED, "invalid_credentials"),
|
||||
ApiError::Forbidden(_) => (StatusCode::FORBIDDEN, "forbidden"),
|
||||
ApiError::NotFound(_) => (StatusCode::NOT_FOUND, "not_found"),
|
||||
ApiError::Conflict { code, .. } => (StatusCode::CONFLICT, code),
|
||||
ApiError::Gone(_) => (StatusCode::GONE, "gone"),
|
||||
ApiError::InvalidToken => (StatusCode::BAD_REQUEST, "invalid_token"),
|
||||
ApiError::InsufficientCredits { .. } => (StatusCode::PAYMENT_REQUIRED, "insufficient_credits"),
|
||||
ApiError::TooManyRequests => (StatusCode::TOO_MANY_REQUESTS, "too_many_requests"),
|
||||
ApiError::BirthData { status, .. } => (*status, "invalid_birth_data"),
|
||||
ApiError::HoroscopeUnavailable(_) => (StatusCode::BAD_GATEWAY, "horoscope_unavailable"),
|
||||
ApiError::Internal(_) => (StatusCode::INTERNAL_SERVER_ERROR, "internal_error"),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
impl IntoResponse for ApiError {
|
||||
fn into_response(self) -> Response {
|
||||
let (status, code) = self.status_and_code();
|
||||
match &self {
|
||||
ApiError::Internal(detail) | ApiError::HoroscopeUnavailable(detail) => {
|
||||
tracing::error!(error = %detail, code, "request failed");
|
||||
}
|
||||
_ => {}
|
||||
}
|
||||
let body = match self {
|
||||
// Keep the horoscope service's code, message and place suggestions.
|
||||
ApiError::BirthData { body, .. } => {
|
||||
body.get("error").cloned().map(|e| json!({ "error": e })).unwrap_or(body)
|
||||
}
|
||||
other => json!({ "error": { "code": code, "message": other.to_string() } }),
|
||||
};
|
||||
(status, Json(body)).into_response()
|
||||
}
|
||||
}
|
||||
|
||||
impl From<sqlx::Error> for ApiError {
|
||||
fn from(e: sqlx::Error) -> Self {
|
||||
ApiError::Internal(format!("database: {e}"))
|
||||
}
|
||||
}
|
||||
|
||||
impl From<HoroscopeError> for ApiError {
|
||||
fn from(e: HoroscopeError) -> Self {
|
||||
match e {
|
||||
HoroscopeError::Rejected { status, body } => {
|
||||
ApiError::BirthData { status: StatusCode::from_u16(status).unwrap_or(StatusCode::BAD_REQUEST), body }
|
||||
}
|
||||
HoroscopeError::Unavailable(detail) => ApiError::HoroscopeUnavailable(detail),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
impl From<JsonRejection> for ApiError {
|
||||
fn from(rejection: JsonRejection) -> Self {
|
||||
ApiError::BadRequest(rejection.body_text())
|
||||
}
|
||||
}
|
||||
|
||||
impl From<QueryRejection> for ApiError {
|
||||
fn from(rejection: QueryRejection) -> Self {
|
||||
ApiError::BadRequest(rejection.body_text())
|
||||
}
|
||||
}
|
||||
|
||||
impl From<PathRejection> for ApiError {
|
||||
fn from(rejection: PathRejection) -> Self {
|
||||
ApiError::BadRequest(rejection.body_text())
|
||||
}
|
||||
}
|
||||
|
||||
pub type ApiResult<T> = Result<T, ApiError>;
|
||||
@@ -0,0 +1,107 @@
|
||||
//! Google Sign-In: verification of Google ID tokens.
|
||||
//!
|
||||
//! The frontend obtains an ID token with Google Identity Services (button or
|
||||
//! One Tap) and posts it to `POST /v1/auth/google`. The token is a JWT signed
|
||||
//! by Google; it is verified here against Google's published keys (JWKS,
|
||||
//! cached), the configured client ids (audience) and the issuer.
|
||||
|
||||
use std::time::{Duration, Instant};
|
||||
|
||||
use jsonwebtoken::{Algorithm, DecodingKey, Validation, decode, decode_header};
|
||||
use serde::Deserialize;
|
||||
use tokio::sync::RwLock;
|
||||
|
||||
use crate::error::ApiError;
|
||||
|
||||
const ISSUERS: [&str; 2] = ["accounts.google.com", "https://accounts.google.com"];
|
||||
const JWKS_MAX_AGE: Duration = Duration::from_secs(3600);
|
||||
|
||||
#[derive(Debug, Deserialize)]
|
||||
pub struct GoogleClaims {
|
||||
/// Stable Google account id.
|
||||
pub sub: String,
|
||||
pub email: Option<String>,
|
||||
#[serde(default)]
|
||||
pub email_verified: bool,
|
||||
pub name: Option<String>,
|
||||
pub locale: Option<String>,
|
||||
}
|
||||
|
||||
#[derive(Debug, Clone, Deserialize)]
|
||||
struct Jwk {
|
||||
kid: String,
|
||||
n: String,
|
||||
e: String,
|
||||
}
|
||||
|
||||
#[derive(Debug, Deserialize)]
|
||||
struct JwkSet {
|
||||
keys: Vec<Jwk>,
|
||||
}
|
||||
|
||||
pub struct GoogleVerifier {
|
||||
client_ids: Vec<String>,
|
||||
jwks_url: String,
|
||||
http: reqwest::Client,
|
||||
cache: RwLock<Option<(Instant, Vec<Jwk>)>>,
|
||||
}
|
||||
|
||||
impl GoogleVerifier {
|
||||
pub fn new(client_ids: Vec<String>, jwks_url: String) -> Self {
|
||||
let http = reqwest::Client::builder().timeout(Duration::from_secs(10)).build().expect("static configuration");
|
||||
Self { client_ids, jwks_url, http, cache: RwLock::new(None) }
|
||||
}
|
||||
|
||||
pub fn enabled(&self) -> bool {
|
||||
!self.client_ids.is_empty()
|
||||
}
|
||||
|
||||
async fn fetch_keys(&self) -> Result<Vec<Jwk>, ApiError> {
|
||||
let set: JwkSet = self
|
||||
.http
|
||||
.get(&self.jwks_url)
|
||||
.send()
|
||||
.await
|
||||
.and_then(|r| r.error_for_status())
|
||||
.map_err(|e| ApiError::Internal(format!("fetching Google keys: {e}")))?
|
||||
.json()
|
||||
.await
|
||||
.map_err(|e| ApiError::Internal(format!("parsing Google keys: {e}")))?;
|
||||
Ok(set.keys)
|
||||
}
|
||||
|
||||
/// The key with `kid`; the key set is refetched when it is stale or the
|
||||
/// key is unknown (Google rotates its keys).
|
||||
async fn key(&self, kid: &str) -> Result<Jwk, ApiError> {
|
||||
if let Some((fetched, keys)) = self.cache.read().await.as_ref()
|
||||
&& fetched.elapsed() < JWKS_MAX_AGE
|
||||
&& let Some(k) = keys.iter().find(|k| k.kid == kid)
|
||||
{
|
||||
return Ok(k.clone());
|
||||
}
|
||||
let keys = self.fetch_keys().await?;
|
||||
let found = keys.iter().find(|k| k.kid == kid).cloned();
|
||||
*self.cache.write().await = Some((Instant::now(), keys));
|
||||
found.ok_or_else(|| ApiError::InvalidCredentials("the Google token is signed with an unknown key".into()))
|
||||
}
|
||||
|
||||
pub async fn verify(&self, id_token: &str) -> Result<GoogleClaims, ApiError> {
|
||||
if !self.enabled() {
|
||||
return Err(ApiError::Forbidden("Google login is not configured".into()));
|
||||
}
|
||||
let invalid =
|
||||
|e: jsonwebtoken::errors::Error| ApiError::InvalidCredentials(format!("invalid Google token: {e}"));
|
||||
let header = decode_header(id_token).map_err(invalid)?;
|
||||
if header.alg != Algorithm::RS256 {
|
||||
return Err(ApiError::InvalidCredentials("invalid Google token: unexpected algorithm".into()));
|
||||
}
|
||||
let kid = header.kid.ok_or_else(|| ApiError::InvalidCredentials("invalid Google token: no key id".into()))?;
|
||||
let jwk = self.key(&kid).await?;
|
||||
let key = DecodingKey::from_rsa_components(&jwk.n, &jwk.e).map_err(invalid)?;
|
||||
let mut validation = Validation::new(Algorithm::RS256);
|
||||
validation.set_audience(&self.client_ids);
|
||||
validation.set_issuer(&ISSUERS);
|
||||
validation.set_required_spec_claims(&["exp", "iss", "aud", "sub"]);
|
||||
Ok(decode::<GoogleClaims>(id_token, &key, &validation).map_err(invalid)?.claims)
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,73 @@
|
||||
//! Sorsfonalak backend: users, login, charts, synastries, analyses, credits
|
||||
//! and public sharing. Charts are calculated by the horoscope-api service.
|
||||
//!
|
||||
//! Configuration: see [`config::Config`]; plus `BIND_ADDR` (default
|
||||
//! `0.0.0.0:8081`), `LOG_FORMAT` and `RUST_LOG`.
|
||||
//! Database migrations run at startup.
|
||||
//!
|
||||
//! `backend healthcheck` performs a local health check (for Docker).
|
||||
|
||||
mod auth;
|
||||
mod config;
|
||||
mod credits;
|
||||
mod error;
|
||||
mod google;
|
||||
mod routes;
|
||||
#[cfg(test)]
|
||||
mod tests;
|
||||
mod views;
|
||||
|
||||
use std::sync::Arc;
|
||||
use std::time::Duration;
|
||||
|
||||
use anyhow::Context;
|
||||
use horoscope_client::HoroscopeClient;
|
||||
use sqlx::PgPool;
|
||||
|
||||
use crate::auth::LoginLimiter;
|
||||
use crate::config::Config;
|
||||
use crate::google::GoogleVerifier;
|
||||
|
||||
const DEFAULT_BIND_ADDR: &str = "0.0.0.0:8081";
|
||||
|
||||
pub struct AppState {
|
||||
pub db: PgPool,
|
||||
pub config: Config,
|
||||
pub horoscope: HoroscopeClient,
|
||||
pub google: GoogleVerifier,
|
||||
pub login_limiter: LoginLimiter,
|
||||
}
|
||||
|
||||
impl AppState {
|
||||
pub fn new(db: PgPool, config: Config) -> Self {
|
||||
Self {
|
||||
horoscope: HoroscopeClient::new(&config.horoscope_api_url),
|
||||
google: GoogleVerifier::new(config.google_client_ids.clone(), config.google_jwks_url.clone()),
|
||||
login_limiter: LoginLimiter::new(10, Duration::from_secs(15 * 60)),
|
||||
db,
|
||||
config,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[tokio::main]
|
||||
async fn main() -> anyhow::Result<()> {
|
||||
let addr = service_kit::bind_addr(DEFAULT_BIND_ADDR)?;
|
||||
if std::env::args().nth(1).as_deref() == Some("healthcheck") {
|
||||
return service_kit::healthcheck(addr);
|
||||
}
|
||||
service_kit::init_logging();
|
||||
let config = Config::from_env()?;
|
||||
let pool = db::connect(&config.database_url).await.context("connecting to the database")?;
|
||||
db::MIGRATOR.run(&pool).await.context("running database migrations")?;
|
||||
tracing::info!(
|
||||
google_login = !config.google_client_ids.is_empty(),
|
||||
horoscope_api = %config.horoscope_api_url,
|
||||
"database ready"
|
||||
);
|
||||
let app = routes::router(Arc::new(AppState::new(pool, config)));
|
||||
let listener = tokio::net::TcpListener::bind(addr).await.with_context(|| format!("binding {addr}"))?;
|
||||
tracing::info!(%addr, "listening");
|
||||
axum::serve(listener, app).with_graceful_shutdown(service_kit::shutdown_signal()).await?;
|
||||
Ok(())
|
||||
}
|
||||
@@ -0,0 +1,182 @@
|
||||
//! The logged-in user's own account: profile, password, credits, GDPR data
|
||||
//! export and account deletion.
|
||||
|
||||
use axum::Json;
|
||||
use axum::extract::State;
|
||||
use axum::http::StatusCode;
|
||||
use axum::response::IntoResponse;
|
||||
use axum_extra::extract::{CookieJar, WithRejection};
|
||||
use serde::Deserialize;
|
||||
use serde_json::{Value, json};
|
||||
use time::OffsetDateTime;
|
||||
use uuid::Uuid;
|
||||
|
||||
use super::auth::{set_password, validate_locale};
|
||||
use super::{Body, St};
|
||||
use crate::auth::{AuthUser, hash_password, removal_cookie, validate_password, verify_password};
|
||||
use crate::credits;
|
||||
use crate::error::{ApiError, ApiResult};
|
||||
use crate::views::{UserView, rfc3339, rfc3339_opt};
|
||||
|
||||
pub async fn me(State(state): St, auth: AuthUser) -> ApiResult<Json<Value>> {
|
||||
let providers: Vec<(String,)> =
|
||||
sqlx::query_as("SELECT provider FROM auth_identities WHERE user_id = $1 ORDER BY created_at")
|
||||
.bind(auth.id())
|
||||
.fetch_all(&state.db)
|
||||
.await?;
|
||||
let primary: Option<(Uuid,)> = sqlx::query_as("SELECT id FROM charts WHERE owner_id = $1 AND is_primary")
|
||||
.bind(auth.id())
|
||||
.fetch_optional(&state.db)
|
||||
.await?;
|
||||
let balance = credits::balance(&state.db, auth.id(), state.config.monthly_free_credits).await?;
|
||||
Ok(Json(json!({
|
||||
"user": UserView::from(&auth.user),
|
||||
"providers": providers.into_iter().map(|(p,)| p).collect::<Vec<_>>(),
|
||||
"primary_chart_id": primary.map(|(id,)| id),
|
||||
"credits": balance,
|
||||
})))
|
||||
}
|
||||
|
||||
#[derive(Deserialize)]
|
||||
#[serde(deny_unknown_fields)]
|
||||
pub struct UpdateMe {
|
||||
/// `null` clears the name.
|
||||
#[serde(default, deserialize_with = "super::double_option")]
|
||||
display_name: Option<Option<String>>,
|
||||
locale: Option<String>,
|
||||
}
|
||||
|
||||
pub async fn update_me(
|
||||
State(state): St,
|
||||
auth: AuthUser,
|
||||
WithRejection(Json(req), _): Body<UpdateMe>,
|
||||
) -> ApiResult<Json<Value>> {
|
||||
let locale = match req.locale.as_deref() {
|
||||
Some(l) => validate_locale(&state, Some(l))?,
|
||||
None => auth.user.locale.clone(),
|
||||
};
|
||||
let display_name = match req.display_name {
|
||||
Some(name) => name.map(|n| n.trim().chars().take(100).collect::<String>()).filter(|n| !n.is_empty()),
|
||||
None => auth.user.display_name.clone(),
|
||||
};
|
||||
sqlx::query("UPDATE users SET display_name = $1, locale = $2, updated_at = now() WHERE id = $3")
|
||||
.bind(&display_name)
|
||||
.bind(&locale)
|
||||
.bind(auth.id())
|
||||
.execute(&state.db)
|
||||
.await?;
|
||||
let mut user = auth.user.clone();
|
||||
user.display_name = display_name;
|
||||
user.locale = locale;
|
||||
Ok(Json(json!({ "user": UserView::from(&user) })))
|
||||
}
|
||||
|
||||
#[derive(Deserialize)]
|
||||
#[serde(deny_unknown_fields)]
|
||||
pub struct ChangePassword {
|
||||
/// Required when the account already has a password.
|
||||
current_password: Option<String>,
|
||||
new_password: String,
|
||||
}
|
||||
|
||||
/// Changes (or, for Google-only accounts, adds) the password; other sessions end.
|
||||
pub async fn change_password(
|
||||
State(state): St,
|
||||
auth: AuthUser,
|
||||
WithRejection(Json(req), _): Body<ChangePassword>,
|
||||
) -> ApiResult<StatusCode> {
|
||||
validate_password(&req.new_password)?;
|
||||
let existing: Option<(String,)> =
|
||||
sqlx::query_as("SELECT password_hash FROM auth_identities WHERE user_id = $1 AND provider = 'password'")
|
||||
.bind(auth.id())
|
||||
.fetch_optional(&state.db)
|
||||
.await?;
|
||||
if let Some((hash,)) = existing {
|
||||
let current =
|
||||
req.current_password.ok_or_else(|| ApiError::BadRequest("current_password is required".into()))?;
|
||||
if !verify_password(current, hash).await? {
|
||||
return Err(ApiError::InvalidCredentials("the current password is wrong".into()));
|
||||
}
|
||||
}
|
||||
let hash = hash_password(req.new_password).await?;
|
||||
let mut tx = state.db.begin().await?;
|
||||
set_password(&mut tx, auth.id(), &hash).await?;
|
||||
sqlx::query("DELETE FROM sessions WHERE user_id = $1 AND id <> $2")
|
||||
.bind(auth.id())
|
||||
.bind(auth.session_id)
|
||||
.execute(&mut *tx)
|
||||
.await?;
|
||||
tx.commit().await?;
|
||||
Ok(StatusCode::NO_CONTENT)
|
||||
}
|
||||
|
||||
pub async fn credits(State(state): St, auth: AuthUser) -> ApiResult<Json<Value>> {
|
||||
let balance = credits::balance(&state.db, auth.id(), state.config.monthly_free_credits).await?;
|
||||
type Row = (Uuid, i32, String, Option<String>, Option<Uuid>, Option<String>, OffsetDateTime);
|
||||
let ledger: Vec<Row> = sqlx::query_as(
|
||||
"SELECT id, delta, reason, period, analysis_id, note, created_at FROM credit_ledger \
|
||||
WHERE user_id = $1 ORDER BY created_at DESC LIMIT 100",
|
||||
)
|
||||
.bind(auth.id())
|
||||
.fetch_all(&state.db)
|
||||
.await?;
|
||||
Ok(Json(json!({
|
||||
"balance": balance,
|
||||
"monthly_free_credits": state.config.monthly_free_credits,
|
||||
"analysis_cost": state.config.analysis_cost,
|
||||
"period": credits::current_period(),
|
||||
"ledger": ledger.into_iter().map(|(id, delta, reason, period, analysis_id, note, at)| json!({
|
||||
"id": id, "delta": delta, "reason": reason, "period": period,
|
||||
"analysis_id": analysis_id, "note": note, "created_at": rfc3339(at),
|
||||
})).collect::<Vec<_>>(),
|
||||
})))
|
||||
}
|
||||
|
||||
/// GDPR: everything stored about the user, as one JSON document.
|
||||
pub async fn export(State(state): St, auth: AuthUser) -> ApiResult<impl IntoResponse> {
|
||||
let id = auth.id();
|
||||
let rows = |sql: &'static str| {
|
||||
let pool = state.db.clone();
|
||||
async move {
|
||||
let rows: Vec<(Value,)> = sqlx::query_as(sql).bind(id).fetch_all(&pool).await?;
|
||||
Ok::<Vec<Value>, ApiError>(rows.into_iter().map(|(v,)| v).collect())
|
||||
}
|
||||
};
|
||||
let document = json!({
|
||||
"exported_at": rfc3339(OffsetDateTime::now_utc()),
|
||||
"user": UserView::from(&auth.user),
|
||||
"last_login_at": rfc3339_opt(auth.user.last_login_at),
|
||||
"login_methods": rows("SELECT json_build_object('provider', provider, 'email', email, 'created_at', created_at, 'last_used_at', last_used_at) FROM auth_identities WHERE user_id = $1").await?,
|
||||
"sessions": rows("SELECT json_build_object('created_at', created_at, 'expires_at', expires_at, 'user_agent', user_agent) FROM sessions WHERE user_id = $1").await?,
|
||||
"charts": rows("SELECT json_build_object('id', id, 'label', label, 'is_primary', is_primary, 'birth_data', birth_data, 'result', result, 'created_at', created_at) FROM charts WHERE owner_id = $1").await?,
|
||||
"synastries": rows("SELECT json_build_object('id', s.id, 'owner_id', s.owner_id, 'chart1_id', s.chart1_id, 'chart2_id', s.chart2_id, 'result', s.result, 'created_at', s.created_at) FROM synastries s JOIN charts c1 ON c1.id = s.chart1_id JOIN charts c2 ON c2.id = s.chart2_id WHERE s.owner_id = $1 OR c1.owner_id = $1 OR c2.owner_id = $1").await?,
|
||||
"invites": rows("SELECT json_build_object('id', id, 'chart_id', inviter_chart_id, 'message', message, 'created_at', created_at, 'expires_at', expires_at, 'accepted_at', accepted_at) FROM synastry_invites WHERE inviter_id = $1").await?,
|
||||
"analyses": rows("SELECT json_build_object('id', a.id, 'kind', a.kind, 'chart_id', a.chart_id, 'synastry_id', a.synastry_id, 'language', a.language, 'model', a.model, 'status', a.status, 'content', a.content, 'created_at', a.created_at) FROM analyses a WHERE a.requested_by = $1 OR a.chart_id IN (SELECT id FROM charts WHERE owner_id = $1)").await?,
|
||||
"credit_ledger": rows("SELECT json_build_object('delta', delta, 'reason', reason, 'period', period, 'note', note, 'created_at', created_at) FROM credit_ledger WHERE user_id = $1 ORDER BY created_at").await?,
|
||||
"shares": rows("SELECT json_build_object('slug', slug, 'kind', kind, 'title', title, 'show_birth_data', show_birth_data, 'view_count', view_count, 'created_at', created_at, 'revoked_at', revoked_at) FROM shares WHERE owner_id = $1").await?,
|
||||
});
|
||||
Ok(([("content-disposition", "attachment; filename=\"sorsfonalak-export.json\"")], Json(document)))
|
||||
}
|
||||
|
||||
#[derive(Deserialize)]
|
||||
#[serde(deny_unknown_fields)]
|
||||
pub struct DeleteMe {
|
||||
/// Must be the string `DELETE`.
|
||||
confirm: String,
|
||||
}
|
||||
|
||||
/// GDPR: deletes the account and everything that belongs to it (charts,
|
||||
/// synastries using them, analyses, shares, sessions, credits).
|
||||
pub async fn delete_me(
|
||||
State(state): St,
|
||||
auth: AuthUser,
|
||||
jar: CookieJar,
|
||||
WithRejection(Json(req), _): Body<DeleteMe>,
|
||||
) -> ApiResult<impl IntoResponse> {
|
||||
if req.confirm != "DELETE" {
|
||||
return Err(ApiError::BadRequest("set confirm to \"DELETE\" to delete the account".into()));
|
||||
}
|
||||
sqlx::query("DELETE FROM users WHERE id = $1").bind(auth.id()).execute(&state.db).await?;
|
||||
tracing::info!(user = %auth.id(), "account deleted");
|
||||
Ok((StatusCode::NO_CONTENT, jar.add(removal_cookie(&state.config))))
|
||||
}
|
||||
@@ -0,0 +1,129 @@
|
||||
//! Administration (admin role only): users, roles, credits.
|
||||
|
||||
use axum::Json;
|
||||
use axum::extract::{Path, Query, State};
|
||||
use axum::http::StatusCode;
|
||||
use axum_extra::extract::WithRejection;
|
||||
use db::Role;
|
||||
use serde::Deserialize;
|
||||
use serde_json::{Value, json};
|
||||
use time::OffsetDateTime;
|
||||
use uuid::Uuid;
|
||||
|
||||
use super::{Body, IdPath, St};
|
||||
use crate::auth::AdminUser;
|
||||
use crate::error::{ApiError, ApiResult};
|
||||
use crate::views::{rfc3339, rfc3339_opt};
|
||||
|
||||
#[derive(Deserialize)]
|
||||
pub struct UserQuery {
|
||||
/// Part of the e-mail address or display name.
|
||||
q: Option<String>,
|
||||
limit: Option<i64>,
|
||||
offset: Option<i64>,
|
||||
}
|
||||
|
||||
pub async fn list_users(
|
||||
State(state): St,
|
||||
_admin: AdminUser,
|
||||
WithRejection(Query(query), _): WithRejection<Query<UserQuery>, ApiError>,
|
||||
) -> ApiResult<Json<Value>> {
|
||||
let limit = query.limit.unwrap_or(50).clamp(1, 200);
|
||||
let offset = query.offset.unwrap_or(0).max(0);
|
||||
let pattern = query.q.as_deref().map(|q| format!("%{}%", q.trim().replace(['%', '_'], "")));
|
||||
type Row = (Uuid, String, Option<String>, Vec<String>, bool, OffsetDateTime, Option<OffsetDateTime>, i64, i64);
|
||||
let rows: Vec<Row> = sqlx::query_as(
|
||||
"SELECT u.id, u.email, u.display_name, u.roles, u.email_verified_at IS NOT NULL, u.created_at, u.last_login_at, \
|
||||
(SELECT count(*) FROM charts c WHERE c.owner_id = u.id), \
|
||||
(SELECT COALESCE(SUM(delta), 0)::bigint FROM credit_ledger l WHERE l.user_id = u.id) \
|
||||
FROM users u \
|
||||
WHERE $1::text IS NULL OR u.email ILIKE $1 OR u.display_name ILIKE $1 \
|
||||
ORDER BY u.created_at DESC LIMIT $2 OFFSET $3",
|
||||
)
|
||||
.bind(pattern)
|
||||
.bind(limit)
|
||||
.bind(offset)
|
||||
.fetch_all(&state.db)
|
||||
.await?;
|
||||
let users: Vec<Value> = rows
|
||||
.into_iter()
|
||||
.map(|(id, email, name, roles, verified, created, last_login, charts, credits)| {
|
||||
json!({
|
||||
"id": id, "email": email, "display_name": name, "roles": roles, "email_verified": verified,
|
||||
"created_at": rfc3339(created), "last_login_at": rfc3339_opt(last_login),
|
||||
"charts": charts, "credits": credits,
|
||||
})
|
||||
})
|
||||
.collect();
|
||||
Ok(Json(json!({ "users": users, "limit": limit, "offset": offset })))
|
||||
}
|
||||
|
||||
#[derive(Deserialize)]
|
||||
#[serde(deny_unknown_fields)]
|
||||
pub struct UpdateUser {
|
||||
roles: Vec<Role>,
|
||||
}
|
||||
|
||||
pub async fn update_user(
|
||||
State(state): St,
|
||||
AdminUser(admin): AdminUser,
|
||||
WithRejection(Path(id), _): IdPath,
|
||||
WithRejection(Json(req), _): Body<UpdateUser>,
|
||||
) -> ApiResult<Json<Value>> {
|
||||
let mut roles: Vec<&str> = req.roles.iter().map(|r| r.as_str()).collect();
|
||||
roles.sort_unstable();
|
||||
roles.dedup();
|
||||
if roles.is_empty() {
|
||||
return Err(ApiError::BadRequest("at least one role is required".into()));
|
||||
}
|
||||
if id == admin.id() && !roles.contains(&Role::Admin.as_str()) {
|
||||
return Err(ApiError::conflict("own_admin_role", "you cannot remove your own admin role"));
|
||||
}
|
||||
let row: Option<(Uuid, Vec<String>)> =
|
||||
sqlx::query_as("UPDATE users SET roles = $1, updated_at = now() WHERE id = $2 RETURNING id, roles")
|
||||
.bind(&roles)
|
||||
.bind(id)
|
||||
.fetch_optional(&state.db)
|
||||
.await?;
|
||||
let (id, roles) = row.ok_or(ApiError::NotFound("user"))?;
|
||||
tracing::info!(admin = %admin.id(), user = %id, ?roles, "roles changed");
|
||||
Ok(Json(json!({ "id": id, "roles": roles })))
|
||||
}
|
||||
|
||||
#[derive(Deserialize)]
|
||||
#[serde(deny_unknown_fields)]
|
||||
pub struct AdjustCredits {
|
||||
/// Positive to add, negative to take away.
|
||||
delta: i32,
|
||||
note: Option<String>,
|
||||
}
|
||||
|
||||
pub async fn adjust_credits(
|
||||
State(state): St,
|
||||
AdminUser(admin): AdminUser,
|
||||
WithRejection(Path(id), _): IdPath,
|
||||
WithRejection(Json(req), _): Body<AdjustCredits>,
|
||||
) -> ApiResult<(StatusCode, Json<Value>)> {
|
||||
if req.delta == 0 {
|
||||
return Err(ApiError::BadRequest("delta must not be 0".into()));
|
||||
}
|
||||
let exists: Option<(Uuid,)> =
|
||||
sqlx::query_as("SELECT id FROM users WHERE id = $1").bind(id).fetch_optional(&state.db).await?;
|
||||
exists.ok_or(ApiError::NotFound("user"))?;
|
||||
sqlx::query(
|
||||
"INSERT INTO credit_ledger (id, user_id, delta, reason, note, created_by) VALUES ($1, $2, $3, 'admin_adjust', $4, $5)",
|
||||
)
|
||||
.bind(Uuid::now_v7())
|
||||
.bind(id)
|
||||
.bind(req.delta)
|
||||
.bind(req.note.map(|n| n.chars().take(500).collect::<String>()))
|
||||
.bind(admin.id())
|
||||
.execute(&state.db)
|
||||
.await?;
|
||||
let (balance,): (i64,) =
|
||||
sqlx::query_as("SELECT COALESCE(SUM(delta), 0)::bigint FROM credit_ledger WHERE user_id = $1")
|
||||
.bind(id)
|
||||
.fetch_one(&state.db)
|
||||
.await?;
|
||||
Ok((StatusCode::CREATED, Json(json!({ "user_id": id, "balance": balance }))))
|
||||
}
|
||||
@@ -0,0 +1,265 @@
|
||||
//! Text analyses (LLM) of charts and synastries.
|
||||
//!
|
||||
//! A request creates a `pending` analysis and spends credits; the worker
|
||||
//! writes the text later. A finished analysis with the same cache key (same
|
||||
//! chart or synastry hash, prompt version, model and language) is copied
|
||||
//! instead, free of charge, so the same chart is never paid for twice.
|
||||
|
||||
use axum::Json;
|
||||
use axum::body::Bytes;
|
||||
use axum::extract::{Path, State};
|
||||
use axum::http::StatusCode;
|
||||
use axum_extra::extract::WithRejection;
|
||||
use serde::Deserialize;
|
||||
use serde_json::{Value, json};
|
||||
use sqlx::PgPool;
|
||||
use time::OffsetDateTime;
|
||||
use uuid::Uuid;
|
||||
|
||||
use super::auth::validate_locale;
|
||||
use super::charts::{find_chart, owned_chart};
|
||||
use super::synastries::{load_synastry, visible_synastry};
|
||||
use super::{IdPath, St};
|
||||
use crate::AppState;
|
||||
use crate::auth::AuthUser;
|
||||
use crate::credits;
|
||||
use crate::error::{ApiError, ApiResult};
|
||||
use crate::views::{rfc3339, rfc3339_opt, sha256_hex};
|
||||
|
||||
#[derive(Debug, Clone, sqlx::FromRow)]
|
||||
pub struct AnalysisRow {
|
||||
pub id: Uuid,
|
||||
pub kind: String,
|
||||
pub chart_id: Option<Uuid>,
|
||||
pub synastry_id: Option<Uuid>,
|
||||
pub language: String,
|
||||
pub model: String,
|
||||
pub prompt_version: String,
|
||||
pub status: String,
|
||||
pub content: Option<Value>,
|
||||
pub error: Option<String>,
|
||||
pub credits_charged: i32,
|
||||
pub created_at: OffsetDateTime,
|
||||
pub completed_at: Option<OffsetDateTime>,
|
||||
}
|
||||
|
||||
const ANALYSIS_COLUMNS: &str = "id, kind, chart_id, synastry_id, language, model, prompt_version, status, content, \
|
||||
error, credits_charged, created_at, completed_at";
|
||||
|
||||
impl AnalysisRow {
|
||||
pub fn view(&self) -> Value {
|
||||
json!({
|
||||
"id": self.id,
|
||||
"kind": self.kind,
|
||||
"chart_id": self.chart_id,
|
||||
"synastry_id": self.synastry_id,
|
||||
"language": self.language,
|
||||
"model": self.model,
|
||||
"prompt_version": self.prompt_version,
|
||||
"status": self.status,
|
||||
"content": self.content,
|
||||
"error": self.error,
|
||||
"credits_charged": self.credits_charged,
|
||||
"created_at": rfc3339(self.created_at),
|
||||
"completed_at": rfc3339_opt(self.completed_at),
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
pub async fn find_analysis(db: &PgPool, id: Uuid) -> Result<Option<AnalysisRow>, ApiError> {
|
||||
Ok(sqlx::query_as(&format!("SELECT {ANALYSIS_COLUMNS} FROM analyses WHERE id = $1"))
|
||||
.bind(id)
|
||||
.fetch_optional(db)
|
||||
.await?)
|
||||
}
|
||||
|
||||
/// Whether `user` may read the analysis: the chart's owner, or a member of
|
||||
/// the synastry.
|
||||
pub async fn can_see(db: &PgPool, analysis: &AnalysisRow, user: Uuid) -> Result<bool, ApiError> {
|
||||
if let Some(chart_id) = analysis.chart_id {
|
||||
return Ok(find_chart(db, chart_id).await?.is_some_and(|c| c.owner_id == user));
|
||||
}
|
||||
if let Some(synastry_id) = analysis.synastry_id {
|
||||
return Ok(load_synastry(db, synastry_id).await?.is_some_and(|s| s.is_member(user)));
|
||||
}
|
||||
Ok(false)
|
||||
}
|
||||
|
||||
#[derive(Deserialize, Default)]
|
||||
#[serde(deny_unknown_fields)]
|
||||
pub struct AnalysisRequest {
|
||||
/// Defaults to the user's locale.
|
||||
language: Option<String>,
|
||||
/// One of the configured models; defaults to the first.
|
||||
model: Option<String>,
|
||||
}
|
||||
|
||||
/// The request body is optional: empty means all defaults.
|
||||
fn optional_body(body: &[u8]) -> Result<AnalysisRequest, ApiError> {
|
||||
if body.iter().all(u8::is_ascii_whitespace) {
|
||||
return Ok(AnalysisRequest::default());
|
||||
}
|
||||
serde_json::from_slice(body).map_err(|e| ApiError::BadRequest(format!("invalid request body: {e}")))
|
||||
}
|
||||
|
||||
enum Target {
|
||||
Natal { chart_id: Uuid, hash: String },
|
||||
Synastry { synastry_id: Uuid, hash: String },
|
||||
}
|
||||
|
||||
async fn request(
|
||||
state: &AppState,
|
||||
auth: &AuthUser,
|
||||
target: Target,
|
||||
req: AnalysisRequest,
|
||||
) -> ApiResult<(StatusCode, Json<Value>)> {
|
||||
let language = validate_locale(state, Some(req.language.as_deref().unwrap_or(&auth.user.locale)))?;
|
||||
let model = req.model.unwrap_or_else(|| state.config.llm_models[0].clone());
|
||||
if !state.config.llm_models.contains(&model) {
|
||||
return Err(ApiError::BadRequest(format!(
|
||||
"unknown model '{model}'; available: {}",
|
||||
state.config.llm_models.join(", ")
|
||||
)));
|
||||
}
|
||||
let (kind, hash, chart_id, synastry_id) = match &target {
|
||||
Target::Natal { chart_id, hash } => ("natal", hash, Some(*chart_id), None),
|
||||
Target::Synastry { synastry_id, hash } => ("synastry", hash, None, Some(*synastry_id)),
|
||||
};
|
||||
let prompt_version = &state.config.prompt_version;
|
||||
let cache_key = sha256_hex(&format!("{kind}|{hash}|{prompt_version}|{model}|{language}"));
|
||||
|
||||
// Already requested for this chart/synastry: return it.
|
||||
let existing: Option<AnalysisRow> = sqlx::query_as(&format!(
|
||||
"SELECT {ANALYSIS_COLUMNS} FROM analyses \
|
||||
WHERE (chart_id = $1 OR synastry_id = $2) AND cache_key = $3 AND status <> 'failed' \
|
||||
ORDER BY created_at DESC LIMIT 1"
|
||||
))
|
||||
.bind(chart_id)
|
||||
.bind(synastry_id)
|
||||
.bind(&cache_key)
|
||||
.fetch_optional(&state.db)
|
||||
.await?;
|
||||
if let Some(row) = existing {
|
||||
return Ok((StatusCode::OK, Json(row.view())));
|
||||
}
|
||||
|
||||
let insert = format!(
|
||||
"INSERT INTO analyses (id, kind, chart_id, synastry_id, requested_by, language, model, prompt_version, \
|
||||
cache_key, status, content, input_tokens, output_tokens, credits_charged, completed_at) \
|
||||
VALUES ($1, $2, $3, $4, $5, $6, $7, $8, $9, $10, $11, $12, $13, $14, $15) RETURNING {ANALYSIS_COLUMNS}"
|
||||
);
|
||||
let id = Uuid::now_v7();
|
||||
|
||||
// The same chart elsewhere (another user, same birth data) was already analysed: copy it.
|
||||
let cached: Option<(Value, Option<i32>, Option<i32>)> = sqlx::query_as(
|
||||
"SELECT content, input_tokens, output_tokens FROM analyses WHERE cache_key = $1 AND status = 'done' LIMIT 1",
|
||||
)
|
||||
.bind(&cache_key)
|
||||
.fetch_optional(&state.db)
|
||||
.await?;
|
||||
if let Some((content, input_tokens, output_tokens)) = cached {
|
||||
let row: AnalysisRow = sqlx::query_as(&insert)
|
||||
.bind(id)
|
||||
.bind(kind)
|
||||
.bind(chart_id)
|
||||
.bind(synastry_id)
|
||||
.bind(auth.id())
|
||||
.bind(&language)
|
||||
.bind(&model)
|
||||
.bind(prompt_version)
|
||||
.bind(&cache_key)
|
||||
.bind("done")
|
||||
.bind(content)
|
||||
.bind(input_tokens)
|
||||
.bind(output_tokens)
|
||||
.bind(0)
|
||||
.bind(OffsetDateTime::now_utc())
|
||||
.fetch_one(&state.db)
|
||||
.await?;
|
||||
return Ok((StatusCode::CREATED, Json(row.view())));
|
||||
}
|
||||
|
||||
// New analysis: spend credits and queue it for the worker.
|
||||
let cost = state.config.analysis_cost;
|
||||
let mut tx = state.db.begin().await?;
|
||||
let row: AnalysisRow = sqlx::query_as(&insert)
|
||||
.bind(id)
|
||||
.bind(kind)
|
||||
.bind(chart_id)
|
||||
.bind(synastry_id)
|
||||
.bind(auth.id())
|
||||
.bind(&language)
|
||||
.bind(&model)
|
||||
.bind(prompt_version)
|
||||
.bind(&cache_key)
|
||||
.bind("pending")
|
||||
.bind(None::<Value>)
|
||||
.bind(None::<i32>)
|
||||
.bind(None::<i32>)
|
||||
.bind(cost)
|
||||
.bind(None::<OffsetDateTime>)
|
||||
.fetch_one(&mut *tx)
|
||||
.await?;
|
||||
credits::spend(&mut tx, auth.id(), cost, state.config.monthly_free_credits, "analysis", Some(id)).await?;
|
||||
tx.commit().await?;
|
||||
Ok((StatusCode::ACCEPTED, Json(row.view())))
|
||||
}
|
||||
|
||||
async fn list_where(db: &PgPool, column: &str, id: Uuid) -> Result<Json<Value>, ApiError> {
|
||||
let rows: Vec<AnalysisRow> = sqlx::query_as(&format!(
|
||||
"SELECT {ANALYSIS_COLUMNS} FROM analyses WHERE {column} = $1 ORDER BY created_at DESC"
|
||||
))
|
||||
.bind(id)
|
||||
.fetch_all(db)
|
||||
.await?;
|
||||
Ok(Json(json!({ "analyses": rows.iter().map(AnalysisRow::view).collect::<Vec<_>>() })))
|
||||
}
|
||||
|
||||
pub async fn list_for_chart(
|
||||
State(state): St,
|
||||
auth: AuthUser,
|
||||
WithRejection(Path(id), _): IdPath,
|
||||
) -> ApiResult<Json<Value>> {
|
||||
owned_chart(&state.db, id, auth.id()).await?;
|
||||
list_where(&state.db, "chart_id", id).await
|
||||
}
|
||||
|
||||
pub async fn request_for_chart(
|
||||
State(state): St,
|
||||
auth: AuthUser,
|
||||
WithRejection(Path(id), _): IdPath,
|
||||
body: Bytes,
|
||||
) -> ApiResult<(StatusCode, Json<Value>)> {
|
||||
let chart = owned_chart(&state.db, id, auth.id()).await?;
|
||||
let req = optional_body(&body)?;
|
||||
request(&state, &auth, Target::Natal { chart_id: chart.id, hash: chart.chart_hash }, req).await
|
||||
}
|
||||
|
||||
pub async fn list_for_synastry(
|
||||
State(state): St,
|
||||
auth: AuthUser,
|
||||
WithRejection(Path(id), _): IdPath,
|
||||
) -> ApiResult<Json<Value>> {
|
||||
visible_synastry(&state.db, id, auth.id()).await?;
|
||||
list_where(&state.db, "synastry_id", id).await
|
||||
}
|
||||
|
||||
pub async fn request_for_synastry(
|
||||
State(state): St,
|
||||
auth: AuthUser,
|
||||
WithRejection(Path(id), _): IdPath,
|
||||
body: Bytes,
|
||||
) -> ApiResult<(StatusCode, Json<Value>)> {
|
||||
let s = visible_synastry(&state.db, id, auth.id()).await?;
|
||||
let req = optional_body(&body)?;
|
||||
let target = Target::Synastry { synastry_id: s.synastry.id, hash: s.synastry.synastry_hash };
|
||||
request(&state, &auth, target, req).await
|
||||
}
|
||||
|
||||
pub async fn get_one(State(state): St, auth: AuthUser, WithRejection(Path(id), _): IdPath) -> ApiResult<Json<Value>> {
|
||||
let analysis = find_analysis(&state.db, id).await?.ok_or(ApiError::NotFound("analysis"))?;
|
||||
if !can_see(&state.db, &analysis, auth.id()).await? {
|
||||
return Err(ApiError::NotFound("analysis"));
|
||||
}
|
||||
Ok(Json(analysis.view()))
|
||||
}
|
||||
@@ -0,0 +1,466 @@
|
||||
//! Registration and login: e-mail + password, Google; e-mail verification,
|
||||
//! password reset, logout.
|
||||
|
||||
use axum::Json;
|
||||
use axum::extract::State;
|
||||
use axum::http::{HeaderMap, StatusCode};
|
||||
use axum::response::IntoResponse;
|
||||
use axum_extra::extract::{CookieJar, WithRejection};
|
||||
use db::{Role, USER_COLUMNS, User};
|
||||
use serde::{Deserialize, Serialize};
|
||||
use serde_json::{Value, json};
|
||||
use sqlx::PgConnection;
|
||||
use time::OffsetDateTime;
|
||||
use uuid::Uuid;
|
||||
|
||||
use super::{Body, St};
|
||||
use crate::AppState;
|
||||
use crate::auth::{
|
||||
AuthUser, DUMMY_HASH, SessionInfo, create_session, hash_password, removal_cookie, session_cookie, user_agent,
|
||||
validate_password, verify_password,
|
||||
};
|
||||
use crate::error::{ApiError, ApiResult};
|
||||
use crate::views::UserView;
|
||||
|
||||
const VERIFY_EMAIL_TTL: time::Duration = time::Duration::days(3);
|
||||
const RESET_PASSWORD_TTL: time::Duration = time::Duration::hours(1);
|
||||
|
||||
#[derive(Serialize)]
|
||||
pub struct LoginResponse {
|
||||
pub user: UserView,
|
||||
pub session: SessionInfo,
|
||||
/// `true` when this call created the account.
|
||||
pub created: bool,
|
||||
}
|
||||
|
||||
pub fn normalize_email(email: &str) -> Result<String, ApiError> {
|
||||
let email = email.trim().to_lowercase();
|
||||
let valid = email.len() <= 254
|
||||
&& email.split_once('@').is_some_and(|(local, domain)| {
|
||||
!local.is_empty() && domain.contains('.') && !domain.starts_with('.') && !domain.ends_with('.')
|
||||
})
|
||||
&& !email.chars().any(char::is_whitespace);
|
||||
if valid { Ok(email) } else { Err(ApiError::BadRequest("invalid e-mail address".into())) }
|
||||
}
|
||||
|
||||
pub fn validate_locale(state: &AppState, locale: Option<&str>) -> Result<String, ApiError> {
|
||||
match locale {
|
||||
None => Ok(state.config.supported_locales[0].clone()),
|
||||
Some(l) if state.config.supported_locales.iter().any(|s| s == l) => Ok(l.to_string()),
|
||||
Some(l) => Err(ApiError::BadRequest(format!(
|
||||
"unsupported locale '{l}'; supported: {}",
|
||||
state.config.supported_locales.join(", ")
|
||||
))),
|
||||
}
|
||||
}
|
||||
|
||||
fn clean_name(name: Option<String>) -> Option<String> {
|
||||
name.map(|n| n.trim().chars().take(100).collect::<String>()).filter(|n| !n.is_empty())
|
||||
}
|
||||
|
||||
async fn load_user(conn: &mut PgConnection, id: Uuid) -> Result<User, ApiError> {
|
||||
Ok(sqlx::query_as(&format!("SELECT {USER_COLUMNS} FROM users WHERE id = $1")).bind(id).fetch_one(conn).await?)
|
||||
}
|
||||
|
||||
/// Gives the admin role to addresses listed in `BOOTSTRAP_ADMIN_EMAILS`.
|
||||
async fn apply_bootstrap_admin(state: &AppState, conn: &mut PgConnection, user: &mut User) -> Result<(), ApiError> {
|
||||
if !user.has_role(Role::Admin) && state.config.bootstrap_admin_emails.contains(&user.email) {
|
||||
sqlx::query("UPDATE users SET roles = array_append(roles, 'admin'), updated_at = now() WHERE id = $1")
|
||||
.bind(user.id)
|
||||
.execute(&mut *conn)
|
||||
.await?;
|
||||
*user = load_user(conn, user.id).await?;
|
||||
tracing::info!(user = %user.id, "admin role granted from BOOTSTRAP_ADMIN_EMAILS");
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// One-time token row; returns the secret to put into the e-mail link.
|
||||
async fn issue_token(
|
||||
conn: &mut PgConnection,
|
||||
user_id: Uuid,
|
||||
purpose: &str,
|
||||
ttl: time::Duration,
|
||||
) -> Result<String, ApiError> {
|
||||
// A new link replaces the earlier unused ones.
|
||||
sqlx::query("DELETE FROM auth_tokens WHERE user_id = $1 AND purpose = $2 AND used_at IS NULL")
|
||||
.bind(user_id)
|
||||
.bind(purpose)
|
||||
.execute(&mut *conn)
|
||||
.await?;
|
||||
let token = db::new_token();
|
||||
sqlx::query("INSERT INTO auth_tokens (id, user_id, purpose, token_hash, expires_at) VALUES ($1, $2, $3, $4, $5)")
|
||||
.bind(Uuid::now_v7())
|
||||
.bind(user_id)
|
||||
.bind(purpose)
|
||||
.bind(db::token_hash(&token))
|
||||
.bind(OffsetDateTime::now_utc() + ttl)
|
||||
.execute(conn)
|
||||
.await?;
|
||||
Ok(token)
|
||||
}
|
||||
|
||||
/// Uses a one-time token; returns its user.
|
||||
async fn consume_token(conn: &mut PgConnection, token: &str, purpose: &str) -> Result<Uuid, ApiError> {
|
||||
let row: Option<(Uuid,)> = sqlx::query_as(
|
||||
"UPDATE auth_tokens SET used_at = now() \
|
||||
WHERE token_hash = $1 AND purpose = $2 AND used_at IS NULL AND expires_at > now() RETURNING user_id",
|
||||
)
|
||||
.bind(db::token_hash(token.trim()))
|
||||
.bind(purpose)
|
||||
.fetch_optional(conn)
|
||||
.await?;
|
||||
row.map(|(id,)| id).ok_or(ApiError::InvalidToken)
|
||||
}
|
||||
|
||||
/// Queues an e-mail for the worker.
|
||||
pub async fn queue_email(conn: &mut PgConnection, user: &User, template: &str, payload: Value) -> Result<(), ApiError> {
|
||||
sqlx::query(
|
||||
"INSERT INTO email_outbox (id, user_id, to_email, template, locale, payload) VALUES ($1, $2, $3, $4, $5, $6)",
|
||||
)
|
||||
.bind(Uuid::now_v7())
|
||||
.bind(user.id)
|
||||
.bind(&user.email)
|
||||
.bind(template)
|
||||
.bind(&user.locale)
|
||||
.bind(payload)
|
||||
.execute(conn)
|
||||
.await?;
|
||||
Ok(())
|
||||
}
|
||||
|
||||
async fn queue_verification(state: &AppState, conn: &mut PgConnection, user: &User) -> Result<(), ApiError> {
|
||||
let token = issue_token(conn, user.id, "verify_email", VERIFY_EMAIL_TTL).await?;
|
||||
let url = format!("{}/verify-email?token={token}", state.config.public_base_url);
|
||||
queue_email(conn, user, "verify_email", json!({ "url": url, "display_name": user.display_name })).await
|
||||
}
|
||||
|
||||
fn login_response(
|
||||
state: &AppState,
|
||||
jar: CookieJar,
|
||||
user: &User,
|
||||
session: SessionInfo,
|
||||
created: bool,
|
||||
) -> impl IntoResponse + use<> {
|
||||
let jar = jar.add(session_cookie(&state.config, &session));
|
||||
let status = if created { StatusCode::CREATED } else { StatusCode::OK };
|
||||
(status, jar, Json(LoginResponse { user: user.into(), session, created }))
|
||||
}
|
||||
|
||||
// --- e-mail + password -----------------------------------------------------------------
|
||||
|
||||
#[derive(Deserialize)]
|
||||
#[serde(deny_unknown_fields)]
|
||||
pub struct RegisterRequest {
|
||||
email: String,
|
||||
password: String,
|
||||
display_name: Option<String>,
|
||||
locale: Option<String>,
|
||||
}
|
||||
|
||||
pub async fn register(
|
||||
State(state): St,
|
||||
headers: HeaderMap,
|
||||
jar: CookieJar,
|
||||
WithRejection(Json(req), _): Body<RegisterRequest>,
|
||||
) -> ApiResult<impl IntoResponse> {
|
||||
let email = normalize_email(&req.email)?;
|
||||
validate_password(&req.password)?;
|
||||
let locale = validate_locale(&state, req.locale.as_deref())?;
|
||||
let hash = hash_password(req.password).await?;
|
||||
|
||||
let mut tx = state.db.begin().await?;
|
||||
let exists: Option<(Uuid,)> =
|
||||
sqlx::query_as("SELECT id FROM users WHERE email = $1").bind(&email).fetch_optional(&mut *tx).await?;
|
||||
if exists.is_some() {
|
||||
return Err(ApiError::conflict("email_taken", "an account with this e-mail address already exists"));
|
||||
}
|
||||
let user_id = Uuid::now_v7();
|
||||
sqlx::query("INSERT INTO users (id, email, display_name, locale) VALUES ($1, $2, $3, $4)")
|
||||
.bind(user_id)
|
||||
.bind(&email)
|
||||
.bind(clean_name(req.display_name))
|
||||
.bind(&locale)
|
||||
.execute(&mut *tx)
|
||||
.await?;
|
||||
sqlx::query("INSERT INTO auth_identities (id, user_id, provider, subject, password_hash, email) VALUES ($1, $2, 'password', $3, $4, $5)")
|
||||
.bind(Uuid::now_v7())
|
||||
.bind(user_id)
|
||||
.bind(user_id.to_string())
|
||||
.bind(hash)
|
||||
.bind(&email)
|
||||
.execute(&mut *tx)
|
||||
.await?;
|
||||
let mut user = load_user(&mut tx, user_id).await?;
|
||||
apply_bootstrap_admin(&state, &mut tx, &mut user).await?;
|
||||
queue_verification(&state, &mut tx, &user).await?;
|
||||
tx.commit().await?;
|
||||
|
||||
let session = create_session(&state.db, &state.config, user.id, user_agent(&headers)).await?;
|
||||
Ok(login_response(&state, jar, &user, session, true))
|
||||
}
|
||||
|
||||
#[derive(Deserialize)]
|
||||
#[serde(deny_unknown_fields)]
|
||||
pub struct LoginRequest {
|
||||
email: String,
|
||||
password: String,
|
||||
}
|
||||
|
||||
pub async fn login(
|
||||
State(state): St,
|
||||
headers: HeaderMap,
|
||||
jar: CookieJar,
|
||||
WithRejection(Json(req), _): Body<LoginRequest>,
|
||||
) -> ApiResult<impl IntoResponse> {
|
||||
let invalid = || ApiError::InvalidCredentials("wrong e-mail address or password".into());
|
||||
let email = normalize_email(&req.email).map_err(|_| invalid())?;
|
||||
state.login_limiter.check(&email)?;
|
||||
|
||||
let row: Option<(Uuid, String)> = sqlx::query_as(
|
||||
"SELECT u.id, i.password_hash FROM users u \
|
||||
JOIN auth_identities i ON i.user_id = u.id AND i.provider = 'password' WHERE u.email = $1",
|
||||
)
|
||||
.bind(&email)
|
||||
.fetch_optional(&state.db)
|
||||
.await?;
|
||||
let Some((user_id, hash)) = row else {
|
||||
// Same amount of work as a real check.
|
||||
let _ = verify_password(req.password, DUMMY_HASH.clone()).await;
|
||||
state.login_limiter.failed(&email);
|
||||
return Err(invalid());
|
||||
};
|
||||
if !verify_password(req.password, hash).await? {
|
||||
state.login_limiter.failed(&email);
|
||||
return Err(invalid());
|
||||
}
|
||||
state.login_limiter.succeeded(&email);
|
||||
|
||||
let mut conn = state.db.acquire().await?;
|
||||
sqlx::query("UPDATE auth_identities SET last_used_at = now() WHERE user_id = $1 AND provider = 'password'")
|
||||
.bind(user_id)
|
||||
.execute(&mut *conn)
|
||||
.await?;
|
||||
let mut user = load_user(&mut conn, user_id).await?;
|
||||
apply_bootstrap_admin(&state, &mut conn, &mut user).await?;
|
||||
drop(conn);
|
||||
let session = create_session(&state.db, &state.config, user.id, user_agent(&headers)).await?;
|
||||
Ok(login_response(&state, jar, &user, session, false))
|
||||
}
|
||||
|
||||
// --- Google -----------------------------------------------------------------------------
|
||||
|
||||
#[derive(Deserialize)]
|
||||
#[serde(deny_unknown_fields)]
|
||||
pub struct GoogleRequest {
|
||||
/// ID token (JWT) from Google Identity Services.
|
||||
id_token: String,
|
||||
}
|
||||
|
||||
/// Logs in with Google. An unknown Google account is linked to the existing
|
||||
/// user with the same (Google-verified) e-mail address, or a new user is created.
|
||||
pub async fn google(
|
||||
State(state): St,
|
||||
headers: HeaderMap,
|
||||
jar: CookieJar,
|
||||
WithRejection(Json(req), _): Body<GoogleRequest>,
|
||||
) -> ApiResult<impl IntoResponse> {
|
||||
let claims = state.google.verify(&req.id_token).await?;
|
||||
let email = match (claims.email.as_deref(), claims.email_verified) {
|
||||
(Some(e), true) => normalize_email(e)?,
|
||||
_ => return Err(ApiError::InvalidCredentials("the Google account has no verified e-mail address".into())),
|
||||
};
|
||||
|
||||
let mut tx = state.db.begin().await?;
|
||||
let linked: Option<(Uuid,)> =
|
||||
sqlx::query_as("SELECT user_id FROM auth_identities WHERE provider = 'google' AND subject = $1")
|
||||
.bind(&claims.sub)
|
||||
.fetch_optional(&mut *tx)
|
||||
.await?;
|
||||
let (user_id, created) = match linked {
|
||||
Some((id,)) => {
|
||||
sqlx::query("UPDATE auth_identities SET last_used_at = now() WHERE provider = 'google' AND subject = $1")
|
||||
.bind(&claims.sub)
|
||||
.execute(&mut *tx)
|
||||
.await?;
|
||||
(id, false)
|
||||
}
|
||||
None => {
|
||||
let existing: Option<(Uuid,)> =
|
||||
sqlx::query_as("SELECT id FROM users WHERE email = $1").bind(&email).fetch_optional(&mut *tx).await?;
|
||||
let (id, created) = match existing {
|
||||
Some((id,)) => {
|
||||
// Google has verified the address, so it counts as verified here too.
|
||||
sqlx::query(
|
||||
"UPDATE users SET email_verified_at = COALESCE(email_verified_at, now()) WHERE id = $1",
|
||||
)
|
||||
.bind(id)
|
||||
.execute(&mut *tx)
|
||||
.await?;
|
||||
(id, false)
|
||||
}
|
||||
None => {
|
||||
let id = Uuid::now_v7();
|
||||
let locale = claims
|
||||
.locale
|
||||
.as_deref()
|
||||
.and_then(|l| l.split(['-', '_']).next())
|
||||
.filter(|l| state.config.supported_locales.iter().any(|s| s == l))
|
||||
.unwrap_or(&state.config.supported_locales[0])
|
||||
.to_string();
|
||||
sqlx::query(
|
||||
"INSERT INTO users (id, email, email_verified_at, display_name, locale) VALUES ($1, $2, now(), $3, $4)",
|
||||
)
|
||||
.bind(id)
|
||||
.bind(&email)
|
||||
.bind(clean_name(claims.name.clone()))
|
||||
.bind(locale)
|
||||
.execute(&mut *tx)
|
||||
.await?;
|
||||
(id, true)
|
||||
}
|
||||
};
|
||||
sqlx::query(
|
||||
"INSERT INTO auth_identities (id, user_id, provider, subject, email, last_used_at) \
|
||||
VALUES ($1, $2, 'google', $3, $4, now())",
|
||||
)
|
||||
.bind(Uuid::now_v7())
|
||||
.bind(id)
|
||||
.bind(&claims.sub)
|
||||
.bind(&email)
|
||||
.execute(&mut *tx)
|
||||
.await?;
|
||||
(id, created)
|
||||
}
|
||||
};
|
||||
let mut user = load_user(&mut tx, user_id).await?;
|
||||
apply_bootstrap_admin(&state, &mut tx, &mut user).await?;
|
||||
tx.commit().await?;
|
||||
|
||||
let session = create_session(&state.db, &state.config, user.id, user_agent(&headers)).await?;
|
||||
Ok(login_response(&state, jar, &user, session, created))
|
||||
}
|
||||
|
||||
// --- logout -------------------------------------------------------------------------------
|
||||
|
||||
pub async fn logout(State(state): St, auth: AuthUser, jar: CookieJar) -> ApiResult<impl IntoResponse> {
|
||||
sqlx::query("DELETE FROM sessions WHERE id = $1").bind(auth.session_id).execute(&state.db).await?;
|
||||
Ok((StatusCode::NO_CONTENT, jar.add(removal_cookie(&state.config))))
|
||||
}
|
||||
|
||||
/// Ends every session of the user (all devices).
|
||||
pub async fn logout_all(State(state): St, auth: AuthUser, jar: CookieJar) -> ApiResult<impl IntoResponse> {
|
||||
sqlx::query("DELETE FROM sessions WHERE user_id = $1").bind(auth.id()).execute(&state.db).await?;
|
||||
Ok((StatusCode::NO_CONTENT, jar.add(removal_cookie(&state.config))))
|
||||
}
|
||||
|
||||
// --- e-mail verification and password reset ------------------------------------------------
|
||||
|
||||
#[derive(Deserialize)]
|
||||
#[serde(deny_unknown_fields)]
|
||||
pub struct TokenRequest {
|
||||
token: String,
|
||||
}
|
||||
|
||||
pub async fn verify_email(State(state): St, WithRejection(Json(req), _): Body<TokenRequest>) -> ApiResult<Json<Value>> {
|
||||
let mut tx = state.db.begin().await?;
|
||||
let user_id = consume_token(&mut tx, &req.token, "verify_email").await?;
|
||||
sqlx::query("UPDATE users SET email_verified_at = COALESCE(email_verified_at, now()) WHERE id = $1")
|
||||
.bind(user_id)
|
||||
.execute(&mut *tx)
|
||||
.await?;
|
||||
tx.commit().await?;
|
||||
Ok(Json(json!({ "verified": true })))
|
||||
}
|
||||
|
||||
pub async fn resend_verification(State(state): St, auth: AuthUser) -> ApiResult<StatusCode> {
|
||||
if auth.user.email_verified_at.is_some() {
|
||||
return Err(ApiError::conflict("already_verified", "the e-mail address is already verified"));
|
||||
}
|
||||
let mut tx = state.db.begin().await?;
|
||||
queue_verification(&state, &mut tx, &auth.user).await?;
|
||||
tx.commit().await?;
|
||||
Ok(StatusCode::ACCEPTED)
|
||||
}
|
||||
|
||||
#[derive(Deserialize)]
|
||||
#[serde(deny_unknown_fields)]
|
||||
pub struct ResetRequest {
|
||||
email: String,
|
||||
}
|
||||
|
||||
/// Always 202, so the response does not reveal whether the address is registered.
|
||||
pub async fn request_password_reset(
|
||||
State(state): St,
|
||||
WithRejection(Json(req), _): Body<ResetRequest>,
|
||||
) -> ApiResult<StatusCode> {
|
||||
let Ok(email) = normalize_email(&req.email) else { return Ok(StatusCode::ACCEPTED) };
|
||||
let mut tx = state.db.begin().await?;
|
||||
let user: Option<User> = sqlx::query_as(&format!("SELECT {USER_COLUMNS} FROM users WHERE email = $1"))
|
||||
.bind(&email)
|
||||
.fetch_optional(&mut *tx)
|
||||
.await?;
|
||||
if let Some(user) = user {
|
||||
let token = issue_token(&mut tx, user.id, "reset_password", RESET_PASSWORD_TTL).await?;
|
||||
let url = format!("{}/reset-password?token={token}", state.config.public_base_url);
|
||||
queue_email(&mut tx, &user, "reset_password", json!({ "url": url, "display_name": user.display_name })).await?;
|
||||
}
|
||||
tx.commit().await?;
|
||||
Ok(StatusCode::ACCEPTED)
|
||||
}
|
||||
|
||||
#[derive(Deserialize)]
|
||||
#[serde(deny_unknown_fields)]
|
||||
pub struct ResetConfirmRequest {
|
||||
token: String,
|
||||
password: String,
|
||||
}
|
||||
|
||||
/// Sets a new password (adding the password login if the user had only
|
||||
/// Google) and ends all sessions.
|
||||
pub async fn confirm_password_reset(
|
||||
State(state): St,
|
||||
WithRejection(Json(req), _): Body<ResetConfirmRequest>,
|
||||
) -> ApiResult<StatusCode> {
|
||||
validate_password(&req.password)?;
|
||||
let hash = hash_password(req.password).await?;
|
||||
let mut tx = state.db.begin().await?;
|
||||
let user_id = consume_token(&mut tx, &req.token, "reset_password").await?;
|
||||
set_password(&mut tx, user_id, &hash).await?;
|
||||
// The link arrived in the mailbox, so the address is verified.
|
||||
sqlx::query("UPDATE users SET email_verified_at = COALESCE(email_verified_at, now()) WHERE id = $1")
|
||||
.bind(user_id)
|
||||
.execute(&mut *tx)
|
||||
.await?;
|
||||
sqlx::query("DELETE FROM sessions WHERE user_id = $1").bind(user_id).execute(&mut *tx).await?;
|
||||
tx.commit().await?;
|
||||
Ok(StatusCode::NO_CONTENT)
|
||||
}
|
||||
|
||||
/// Creates or replaces the password identity.
|
||||
pub async fn set_password(conn: &mut PgConnection, user_id: Uuid, hash: &str) -> Result<(), ApiError> {
|
||||
sqlx::query(
|
||||
"INSERT INTO auth_identities (id, user_id, provider, subject, password_hash, email) \
|
||||
SELECT $1, u.id, 'password', u.id::text, $2, u.email FROM users u WHERE u.id = $3 \
|
||||
ON CONFLICT (user_id, provider) DO UPDATE SET password_hash = EXCLUDED.password_hash",
|
||||
)
|
||||
.bind(Uuid::now_v7())
|
||||
.bind(hash)
|
||||
.bind(user_id)
|
||||
.execute(conn)
|
||||
.await?;
|
||||
Ok(())
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
#[test]
|
||||
fn emails() {
|
||||
assert_eq!(normalize_email(" Anna@Example.COM ").unwrap(), "anna@example.com");
|
||||
assert!(normalize_email("anna").is_err());
|
||||
assert!(normalize_email("anna@localhost").is_err());
|
||||
assert!(normalize_email("an na@example.com").is_err());
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,222 @@
|
||||
//! Natal charts of a user: their own (primary) chart and charts of others
|
||||
//! they entered (partner, family). Calculated by the horoscope service.
|
||||
|
||||
use axum::Json;
|
||||
use axum::extract::State;
|
||||
use axum::http::StatusCode;
|
||||
use axum_extra::extract::WithRejection;
|
||||
use serde::Deserialize;
|
||||
use serde_json::{Value, json};
|
||||
use sqlx::{PgExecutor, PgPool};
|
||||
use time::OffsetDateTime;
|
||||
use uuid::Uuid;
|
||||
|
||||
use super::{Body, IdPath, St};
|
||||
use crate::AppState;
|
||||
use crate::auth::AuthUser;
|
||||
use crate::error::{ApiError, ApiResult};
|
||||
use crate::views::{chart_hash, chart_highlights, rfc3339};
|
||||
|
||||
#[derive(Debug, Clone, sqlx::FromRow)]
|
||||
pub struct ChartRow {
|
||||
pub id: Uuid,
|
||||
pub owner_id: Uuid,
|
||||
pub label: String,
|
||||
pub is_primary: bool,
|
||||
pub birth_data: Value,
|
||||
pub result: Value,
|
||||
pub chart_hash: String,
|
||||
pub created_at: OffsetDateTime,
|
||||
pub updated_at: OffsetDateTime,
|
||||
}
|
||||
|
||||
const CHART_COLUMNS: &str = "id, owner_id, label, is_primary, birth_data, result, chart_hash, created_at, updated_at";
|
||||
|
||||
impl ChartRow {
|
||||
/// Full view for the owner.
|
||||
pub fn owner_view(&self) -> Value {
|
||||
json!({
|
||||
"id": self.id,
|
||||
"label": self.label,
|
||||
"is_primary": self.is_primary,
|
||||
"birth_data": self.birth_data,
|
||||
"highlights": chart_highlights(&self.result),
|
||||
"chart": self.result,
|
||||
"chart_hash": self.chart_hash,
|
||||
"created_at": rfc3339(self.created_at),
|
||||
"updated_at": rfc3339(self.updated_at),
|
||||
})
|
||||
}
|
||||
|
||||
pub fn summary_view(&self) -> Value {
|
||||
json!({
|
||||
"id": self.id,
|
||||
"label": self.label,
|
||||
"is_primary": self.is_primary,
|
||||
"highlights": chart_highlights(&self.result),
|
||||
"created_at": rfc3339(self.created_at),
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
pub async fn find_chart(db: impl PgExecutor<'_>, id: Uuid) -> Result<Option<ChartRow>, ApiError> {
|
||||
Ok(sqlx::query_as(&format!("SELECT {CHART_COLUMNS} FROM charts WHERE id = $1")).bind(id).fetch_optional(db).await?)
|
||||
}
|
||||
|
||||
/// A chart of `owner`; 404 for missing charts and charts of others.
|
||||
pub async fn owned_chart(db: &PgPool, id: Uuid, owner: Uuid) -> Result<ChartRow, ApiError> {
|
||||
find_chart(db, id).await?.filter(|c| c.owner_id == owner).ok_or(ApiError::NotFound("chart"))
|
||||
}
|
||||
|
||||
pub async fn primary_chart(db: &PgPool, owner: Uuid) -> Result<Option<ChartRow>, ApiError> {
|
||||
Ok(sqlx::query_as(&format!("SELECT {CHART_COLUMNS} FROM charts WHERE owner_id = $1 AND is_primary"))
|
||||
.bind(owner)
|
||||
.fetch_optional(db)
|
||||
.await?)
|
||||
}
|
||||
|
||||
fn clean_label(label: &str) -> Result<String, ApiError> {
|
||||
let label: String = label.trim().chars().take(100).collect();
|
||||
if label.is_empty() { Err(ApiError::BadRequest("label must not be empty".into())) } else { Ok(label) }
|
||||
}
|
||||
|
||||
pub async fn list(State(state): St, auth: AuthUser) -> ApiResult<Json<Value>> {
|
||||
let rows: Vec<ChartRow> = sqlx::query_as(&format!(
|
||||
"SELECT {CHART_COLUMNS} FROM charts WHERE owner_id = $1 ORDER BY is_primary DESC, created_at DESC"
|
||||
))
|
||||
.bind(auth.id())
|
||||
.fetch_all(&state.db)
|
||||
.await?;
|
||||
Ok(Json(json!({ "charts": rows.iter().map(ChartRow::summary_view).collect::<Vec<_>>() })))
|
||||
}
|
||||
|
||||
#[derive(Deserialize)]
|
||||
#[serde(deny_unknown_fields)]
|
||||
pub struct CreateChart {
|
||||
/// Shown in lists, e.g. "Saját" or "Anna".
|
||||
label: String,
|
||||
/// The user's own chart (replaces the previous one as primary).
|
||||
#[serde(default)]
|
||||
is_primary: bool,
|
||||
/// Birth data in the format of the horoscope service's `POST /v1/natal`
|
||||
/// (date, time, country, place, ..., options).
|
||||
birth: Value,
|
||||
}
|
||||
|
||||
/// Calculates a chart from birth data; the `name` field is dropped so no
|
||||
/// personal name reaches the calculation (or, later, the LLM).
|
||||
pub async fn calculate(state: &AppState, birth: Value) -> Result<(Value, Value, String), ApiError> {
|
||||
let Value::Object(mut birth) = birth else {
|
||||
return Err(ApiError::BadRequest("birth must be an object".into()));
|
||||
};
|
||||
birth.remove("name");
|
||||
let birth = Value::Object(birth);
|
||||
let result = state.horoscope.natal(&birth).await?;
|
||||
let hash = chart_hash(&result);
|
||||
Ok((birth, result, hash))
|
||||
}
|
||||
|
||||
pub async fn create(
|
||||
State(state): St,
|
||||
auth: AuthUser,
|
||||
WithRejection(Json(req), _): Body<CreateChart>,
|
||||
) -> ApiResult<(StatusCode, Json<Value>)> {
|
||||
let label = clean_label(&req.label)?;
|
||||
let (count,): (i64,) =
|
||||
sqlx::query_as("SELECT count(*) FROM charts WHERE owner_id = $1").bind(auth.id()).fetch_one(&state.db).await?;
|
||||
if count >= state.config.max_charts_per_user {
|
||||
return Err(ApiError::conflict(
|
||||
"chart_limit_reached",
|
||||
format!("at most {} charts can be saved", state.config.max_charts_per_user),
|
||||
));
|
||||
}
|
||||
let (birth, result, hash) = calculate(&state, req.birth).await?;
|
||||
|
||||
let mut tx = state.db.begin().await?;
|
||||
if req.is_primary {
|
||||
sqlx::query("UPDATE charts SET is_primary = false, updated_at = now() WHERE owner_id = $1 AND is_primary")
|
||||
.bind(auth.id())
|
||||
.execute(&mut *tx)
|
||||
.await?;
|
||||
}
|
||||
let row: ChartRow = sqlx::query_as(&format!(
|
||||
"INSERT INTO charts (id, owner_id, label, is_primary, birth_data, result, chart_hash) \
|
||||
VALUES ($1, $2, $3, $4, $5, $6, $7) RETURNING {CHART_COLUMNS}"
|
||||
))
|
||||
.bind(Uuid::now_v7())
|
||||
.bind(auth.id())
|
||||
.bind(label)
|
||||
.bind(req.is_primary)
|
||||
.bind(birth)
|
||||
.bind(result)
|
||||
.bind(hash)
|
||||
.fetch_one(&mut *tx)
|
||||
.await?;
|
||||
tx.commit().await?;
|
||||
Ok((StatusCode::CREATED, Json(row.owner_view())))
|
||||
}
|
||||
|
||||
pub async fn get_one(
|
||||
State(state): St,
|
||||
auth: AuthUser,
|
||||
WithRejection(axum::extract::Path(id), _): IdPath,
|
||||
) -> ApiResult<Json<Value>> {
|
||||
Ok(Json(owned_chart(&state.db, id, auth.id()).await?.owner_view()))
|
||||
}
|
||||
|
||||
#[derive(Deserialize)]
|
||||
#[serde(deny_unknown_fields)]
|
||||
pub struct UpdateChart {
|
||||
label: Option<String>,
|
||||
is_primary: Option<bool>,
|
||||
}
|
||||
|
||||
/// Renames the chart or changes which chart is the user's own. Birth data is
|
||||
/// not editable: a corrected chart is a new chart (analyses belong to the old one).
|
||||
pub async fn update(
|
||||
State(state): St,
|
||||
auth: AuthUser,
|
||||
WithRejection(axum::extract::Path(id), _): IdPath,
|
||||
WithRejection(Json(req), _): Body<UpdateChart>,
|
||||
) -> ApiResult<Json<Value>> {
|
||||
let chart = owned_chart(&state.db, id, auth.id()).await?;
|
||||
let label = match &req.label {
|
||||
Some(l) => clean_label(l)?,
|
||||
None => chart.label.clone(),
|
||||
};
|
||||
let is_primary = req.is_primary.unwrap_or(chart.is_primary);
|
||||
let mut tx = state.db.begin().await?;
|
||||
if is_primary && !chart.is_primary {
|
||||
sqlx::query("UPDATE charts SET is_primary = false, updated_at = now() WHERE owner_id = $1 AND is_primary")
|
||||
.bind(auth.id())
|
||||
.execute(&mut *tx)
|
||||
.await?;
|
||||
}
|
||||
let row: ChartRow = sqlx::query_as(&format!(
|
||||
"UPDATE charts SET label = $1, is_primary = $2, updated_at = now() WHERE id = $3 RETURNING {CHART_COLUMNS}"
|
||||
))
|
||||
.bind(label)
|
||||
.bind(is_primary)
|
||||
.bind(id)
|
||||
.fetch_one(&mut *tx)
|
||||
.await?;
|
||||
tx.commit().await?;
|
||||
Ok(Json(row.owner_view()))
|
||||
}
|
||||
|
||||
/// Deletes the chart with its synastries, analyses and shares.
|
||||
pub async fn remove(
|
||||
State(state): St,
|
||||
auth: AuthUser,
|
||||
WithRejection(axum::extract::Path(id), _): IdPath,
|
||||
) -> ApiResult<StatusCode> {
|
||||
let result = sqlx::query("DELETE FROM charts WHERE id = $1 AND owner_id = $2")
|
||||
.bind(id)
|
||||
.bind(auth.id())
|
||||
.execute(&state.db)
|
||||
.await?;
|
||||
if result.rows_affected() == 0 {
|
||||
return Err(ApiError::NotFound("chart"));
|
||||
}
|
||||
Ok(StatusCode::NO_CONTENT)
|
||||
}
|
||||
@@ -0,0 +1,123 @@
|
||||
//! 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 shares;
|
||||
mod synastries;
|
||||
|
||||
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))
|
||||
// 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))
|
||||
// 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))
|
||||
// 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))
|
||||
// sharing
|
||||
.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/invites/{token}", get(synastries::public_invite))
|
||||
// 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))
|
||||
.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,
|
||||
"llm_models": c.llm_models,
|
||||
"analysis_cost": c.analysis_cost,
|
||||
"monthly_free_credits": c.monthly_free_credits,
|
||||
"password_min_length": crate::auth::MIN_PASSWORD_LEN,
|
||||
}))
|
||||
}
|
||||
@@ -0,0 +1,211 @@
|
||||
//! Public sharing links. Creating and revoking a link needs login; opening
|
||||
//! one (`GET /v1/public/shares/{slug}`) does not. The public view never
|
||||
//! contains birth data unless the owner allowed it for their own chart.
|
||||
|
||||
use axum::Json;
|
||||
use axum::extract::{Path, State};
|
||||
use axum::http::StatusCode;
|
||||
use axum_extra::extract::WithRejection;
|
||||
use serde::Deserialize;
|
||||
use serde_json::{Value, json};
|
||||
use sqlx::PgPool;
|
||||
use time::OffsetDateTime;
|
||||
use uuid::Uuid;
|
||||
|
||||
use super::analyses::{can_see, find_analysis};
|
||||
use super::charts::{ChartRow, find_chart, owned_chart};
|
||||
use super::synastries::{VisibleSynastry, load_synastry, visible_synastry};
|
||||
use super::{Body, IdPath, St};
|
||||
use crate::auth::AuthUser;
|
||||
use crate::error::{ApiError, ApiResult};
|
||||
use crate::views::{public_chart, rfc3339, rfc3339_opt};
|
||||
|
||||
#[derive(Debug, Clone, Copy, PartialEq, Eq, Deserialize)]
|
||||
#[serde(rename_all = "snake_case")]
|
||||
pub enum ShareKind {
|
||||
Chart,
|
||||
Synastry,
|
||||
Analysis,
|
||||
}
|
||||
|
||||
#[derive(Debug, sqlx::FromRow)]
|
||||
struct ShareRow {
|
||||
id: Uuid,
|
||||
owner_id: Uuid,
|
||||
slug: String,
|
||||
kind: String,
|
||||
chart_id: Option<Uuid>,
|
||||
synastry_id: Option<Uuid>,
|
||||
analysis_id: Option<Uuid>,
|
||||
title: Option<String>,
|
||||
show_birth_data: bool,
|
||||
view_count: i64,
|
||||
created_at: OffsetDateTime,
|
||||
revoked_at: Option<OffsetDateTime>,
|
||||
}
|
||||
|
||||
const SHARE_COLUMNS: &str = "id, owner_id, slug, kind, chart_id, synastry_id, analysis_id, title, show_birth_data, \
|
||||
view_count, created_at, revoked_at";
|
||||
|
||||
/// 96 random bits, 16 URL-safe characters.
|
||||
fn new_slug() -> String {
|
||||
db::random_token(12)
|
||||
}
|
||||
|
||||
impl ShareRow {
|
||||
fn view(&self, base_url: &str) -> Value {
|
||||
json!({
|
||||
"id": self.id,
|
||||
"slug": self.slug,
|
||||
"url": format!("{base_url}/s/{}", self.slug),
|
||||
"kind": self.kind,
|
||||
"chart_id": self.chart_id,
|
||||
"synastry_id": self.synastry_id,
|
||||
"analysis_id": self.analysis_id,
|
||||
"title": self.title,
|
||||
"show_birth_data": self.show_birth_data,
|
||||
"view_count": self.view_count,
|
||||
"created_at": rfc3339(self.created_at),
|
||||
"revoked_at": rfc3339_opt(self.revoked_at),
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
#[derive(Deserialize)]
|
||||
#[serde(deny_unknown_fields)]
|
||||
pub struct CreateShare {
|
||||
kind: ShareKind,
|
||||
/// Id of the chart, synastry or analysis.
|
||||
target_id: Uuid,
|
||||
title: Option<String>,
|
||||
/// Show birth date, time and place (only ever of the sharer's own charts).
|
||||
#[serde(default)]
|
||||
show_birth_data: bool,
|
||||
}
|
||||
|
||||
pub async fn create(
|
||||
State(state): St,
|
||||
auth: AuthUser,
|
||||
WithRejection(Json(req), _): Body<CreateShare>,
|
||||
) -> ApiResult<(StatusCode, Json<Value>)> {
|
||||
let (chart_id, synastry_id, analysis_id, kind) = match req.kind {
|
||||
ShareKind::Chart => {
|
||||
owned_chart(&state.db, req.target_id, auth.id()).await?;
|
||||
(Some(req.target_id), None, None, "chart")
|
||||
}
|
||||
ShareKind::Synastry => {
|
||||
visible_synastry(&state.db, req.target_id, auth.id()).await?;
|
||||
(None, Some(req.target_id), None, "synastry")
|
||||
}
|
||||
ShareKind::Analysis => {
|
||||
let analysis = find_analysis(&state.db, req.target_id).await?.ok_or(ApiError::NotFound("analysis"))?;
|
||||
if !can_see(&state.db, &analysis, auth.id()).await? {
|
||||
return Err(ApiError::NotFound("analysis"));
|
||||
}
|
||||
if analysis.status != "done" {
|
||||
return Err(ApiError::conflict("analysis_not_ready", "only finished analyses can be shared"));
|
||||
}
|
||||
(None, None, Some(req.target_id), "analysis")
|
||||
}
|
||||
};
|
||||
let title = req.title.map(|t| t.trim().chars().take(120).collect::<String>()).filter(|t| !t.is_empty());
|
||||
let row: ShareRow = sqlx::query_as(&format!(
|
||||
"INSERT INTO shares (id, owner_id, slug, kind, chart_id, synastry_id, analysis_id, title, show_birth_data) \
|
||||
VALUES ($1, $2, $3, $4, $5, $6, $7, $8, $9) RETURNING {SHARE_COLUMNS}"
|
||||
))
|
||||
.bind(Uuid::now_v7())
|
||||
.bind(auth.id())
|
||||
.bind(new_slug())
|
||||
.bind(kind)
|
||||
.bind(chart_id)
|
||||
.bind(synastry_id)
|
||||
.bind(analysis_id)
|
||||
.bind(title)
|
||||
.bind(req.show_birth_data)
|
||||
.fetch_one(&state.db)
|
||||
.await?;
|
||||
Ok((StatusCode::CREATED, Json(row.view(&state.config.public_base_url))))
|
||||
}
|
||||
|
||||
pub async fn list(State(state): St, auth: AuthUser) -> ApiResult<Json<Value>> {
|
||||
let rows: Vec<ShareRow> =
|
||||
sqlx::query_as(&format!("SELECT {SHARE_COLUMNS} FROM shares WHERE owner_id = $1 ORDER BY created_at DESC"))
|
||||
.bind(auth.id())
|
||||
.fetch_all(&state.db)
|
||||
.await?;
|
||||
let base = &state.config.public_base_url;
|
||||
Ok(Json(json!({ "shares": rows.iter().map(|r| r.view(base)).collect::<Vec<_>>() })))
|
||||
}
|
||||
|
||||
pub async fn revoke(State(state): St, auth: AuthUser, WithRejection(Path(id), _): IdPath) -> ApiResult<StatusCode> {
|
||||
let result =
|
||||
sqlx::query("UPDATE shares SET revoked_at = now() WHERE id = $1 AND owner_id = $2 AND revoked_at IS NULL")
|
||||
.bind(id)
|
||||
.bind(auth.id())
|
||||
.execute(&state.db)
|
||||
.await?;
|
||||
if result.rows_affected() == 0 {
|
||||
return Err(ApiError::NotFound("share"));
|
||||
}
|
||||
Ok(StatusCode::NO_CONTENT)
|
||||
}
|
||||
|
||||
// --- public view -------------------------------------------------------------------------------
|
||||
|
||||
fn public_chart_block(chart: &ChartRow, share: &ShareRow) -> Value {
|
||||
// Birth data only of the sharer's own chart, never of a partner's.
|
||||
let show = share.show_birth_data && chart.owner_id == share.owner_id;
|
||||
json!({ "label": chart.label, "chart": public_chart(&chart.result, show) })
|
||||
}
|
||||
|
||||
fn public_synastry_block(s: &VisibleSynastry, share: &ShareRow) -> Value {
|
||||
json!({
|
||||
"chart1": public_chart_block(&s.chart1, share),
|
||||
"chart2": public_chart_block(&s.chart2, share),
|
||||
"synastry": s.synastry.result,
|
||||
})
|
||||
}
|
||||
|
||||
async fn public_body(db: &PgPool, share: &ShareRow) -> Result<Value, ApiError> {
|
||||
let mut body = json!({
|
||||
"kind": share.kind,
|
||||
"title": share.title,
|
||||
"created_at": rfc3339(share.created_at),
|
||||
});
|
||||
if let Some(chart_id) = share.chart_id {
|
||||
let chart = find_chart(db, chart_id).await?.ok_or(ApiError::NotFound("share"))?;
|
||||
body["chart"] = public_chart_block(&chart, share);
|
||||
} else if let Some(synastry_id) = share.synastry_id {
|
||||
let s = load_synastry(db, synastry_id).await?.ok_or(ApiError::NotFound("share"))?;
|
||||
body["synastry"] = public_synastry_block(&s, share);
|
||||
} else if let Some(analysis_id) = share.analysis_id {
|
||||
let analysis = find_analysis(db, analysis_id).await?.ok_or(ApiError::NotFound("share"))?;
|
||||
body["analysis"] = json!({
|
||||
"kind": analysis.kind,
|
||||
"language": analysis.language,
|
||||
"content": analysis.content,
|
||||
"completed_at": rfc3339_opt(analysis.completed_at),
|
||||
});
|
||||
if let Some(chart_id) = analysis.chart_id {
|
||||
let chart = find_chart(db, chart_id).await?.ok_or(ApiError::NotFound("share"))?;
|
||||
body["chart"] = public_chart_block(&chart, share);
|
||||
}
|
||||
if let Some(synastry_id) = analysis.synastry_id {
|
||||
let s = load_synastry(db, synastry_id).await?.ok_or(ApiError::NotFound("share"))?;
|
||||
body["synastry"] = public_synastry_block(&s, share);
|
||||
}
|
||||
}
|
||||
Ok(body)
|
||||
}
|
||||
|
||||
/// Public: the shared content for the share page and its OG image.
|
||||
pub async fn public_view(State(state): St, Path(slug): Path<String>) -> ApiResult<Json<Value>> {
|
||||
let share: ShareRow = sqlx::query_as(&format!(
|
||||
"UPDATE shares SET view_count = view_count + 1 WHERE slug = $1 AND revoked_at IS NULL RETURNING {SHARE_COLUMNS}"
|
||||
))
|
||||
.bind(slug.trim())
|
||||
.fetch_optional(&state.db)
|
||||
.await?
|
||||
.ok_or(ApiError::NotFound("share"))?;
|
||||
Ok(Json(public_body(&state.db, &share).await?))
|
||||
}
|
||||
@@ -0,0 +1,431 @@
|
||||
//! Synastries (two charts compared) and "how compatible are we?" invitations.
|
||||
//!
|
||||
//! A synastry is visible to its owner and to the owners of both charts: when
|
||||
//! an invitation is accepted, the inviter owns the synastry and the invitee
|
||||
//! sees it through their own chart. Birth data of a chart is shown only to
|
||||
//! its owner; the other side gets the positions only.
|
||||
|
||||
use axum::Json;
|
||||
use axum::extract::{Path, State};
|
||||
use axum::http::StatusCode;
|
||||
use axum_extra::extract::WithRejection;
|
||||
use db::USER_COLUMNS;
|
||||
use serde::Deserialize;
|
||||
use serde_json::{Map, Value, json};
|
||||
use sqlx::PgPool;
|
||||
use time::OffsetDateTime;
|
||||
use uuid::Uuid;
|
||||
|
||||
use super::charts::{ChartRow, find_chart, owned_chart, primary_chart};
|
||||
use super::{Body, IdPath, St};
|
||||
use crate::AppState;
|
||||
use crate::auth::AuthUser;
|
||||
use crate::error::{ApiError, ApiResult};
|
||||
use crate::views::{public_chart, rfc3339, rfc3339_opt, synastry_hash};
|
||||
|
||||
const INVITE_TTL: time::Duration = time::Duration::days(14);
|
||||
|
||||
#[derive(Debug, Clone, sqlx::FromRow)]
|
||||
pub struct SynastryRow {
|
||||
pub id: Uuid,
|
||||
pub owner_id: Uuid,
|
||||
pub chart1_id: Uuid,
|
||||
pub chart2_id: Uuid,
|
||||
pub result: Value,
|
||||
pub synastry_hash: String,
|
||||
pub created_at: OffsetDateTime,
|
||||
}
|
||||
|
||||
const SYNASTRY_COLUMNS: &str = "id, owner_id, chart1_id, chart2_id, result, synastry_hash, created_at";
|
||||
|
||||
/// A synastry with its two charts.
|
||||
pub struct VisibleSynastry {
|
||||
pub synastry: SynastryRow,
|
||||
pub chart1: ChartRow,
|
||||
pub chart2: ChartRow,
|
||||
}
|
||||
|
||||
impl VisibleSynastry {
|
||||
pub fn is_member(&self, user: Uuid) -> bool {
|
||||
self.synastry.owner_id == user || self.chart1.owner_id == user || self.chart2.owner_id == user
|
||||
}
|
||||
}
|
||||
|
||||
pub async fn load_synastry(db: &PgPool, id: Uuid) -> Result<Option<VisibleSynastry>, ApiError> {
|
||||
let row: Option<SynastryRow> = sqlx::query_as(&format!("SELECT {SYNASTRY_COLUMNS} FROM synastries WHERE id = $1"))
|
||||
.bind(id)
|
||||
.fetch_optional(db)
|
||||
.await?;
|
||||
let Some(synastry) = row else { return Ok(None) };
|
||||
let chart1 = find_chart(db, synastry.chart1_id).await?.ok_or(ApiError::NotFound("chart"))?;
|
||||
let chart2 = find_chart(db, synastry.chart2_id).await?.ok_or(ApiError::NotFound("chart"))?;
|
||||
Ok(Some(VisibleSynastry { synastry, chart1, chart2 }))
|
||||
}
|
||||
|
||||
/// 404 unless `user` may see the synastry.
|
||||
pub async fn visible_synastry(db: &PgPool, id: Uuid, user: Uuid) -> Result<VisibleSynastry, ApiError> {
|
||||
load_synastry(db, id).await?.filter(|s| s.is_member(user)).ok_or(ApiError::NotFound("synastry"))
|
||||
}
|
||||
|
||||
async fn display_name(db: &PgPool, user: Uuid) -> Result<Option<String>, ApiError> {
|
||||
let row: Option<(Option<String>,)> =
|
||||
sqlx::query_as("SELECT display_name FROM users WHERE id = $1").bind(user).fetch_optional(db).await?;
|
||||
Ok(row.and_then(|(n,)| n))
|
||||
}
|
||||
|
||||
/// A chart as seen by `viewer`: the owner gets everything, others the
|
||||
/// positions without birth data, labelled with the owner's display name.
|
||||
async fn chart_for_viewer(db: &PgPool, chart: &ChartRow, viewer: Uuid) -> Result<Value, ApiError> {
|
||||
if chart.owner_id == viewer {
|
||||
let mut v = chart.owner_view();
|
||||
v["owned"] = Value::Bool(true);
|
||||
return Ok(v);
|
||||
}
|
||||
let label = match display_name(db, chart.owner_id).await? {
|
||||
Some(name) if chart.is_primary => name,
|
||||
_ => chart.label.clone(),
|
||||
};
|
||||
Ok(json!({ "id": chart.id, "label": label, "owned": false, "chart": public_chart(&chart.result, false) }))
|
||||
}
|
||||
|
||||
async fn synastry_view(db: &PgPool, s: &VisibleSynastry, viewer: Uuid) -> Result<Value, ApiError> {
|
||||
Ok(json!({
|
||||
"id": s.synastry.id,
|
||||
"owned": s.synastry.owner_id == viewer,
|
||||
"chart1": chart_for_viewer(db, &s.chart1, viewer).await?,
|
||||
"chart2": chart_for_viewer(db, &s.chart2, viewer).await?,
|
||||
"synastry": s.synastry.result,
|
||||
"synastry_hash": s.synastry.synastry_hash,
|
||||
"created_at": rfc3339(s.synastry.created_at),
|
||||
}))
|
||||
}
|
||||
|
||||
fn without(value: &Value, keys: &[&str]) -> Value {
|
||||
let mut map: Map<String, Value> = value.as_object().cloned().unwrap_or_default();
|
||||
for k in keys {
|
||||
map.remove(*k);
|
||||
}
|
||||
Value::Object(map)
|
||||
}
|
||||
|
||||
/// Returns the synastry of the two charts, calculating and storing it when
|
||||
/// it does not exist yet (in either order). `bool` = newly created.
|
||||
pub async fn compute_synastry(
|
||||
state: &AppState,
|
||||
owner: Uuid,
|
||||
chart1: &ChartRow,
|
||||
chart2: &ChartRow,
|
||||
) -> Result<(SynastryRow, bool), ApiError> {
|
||||
let existing = |a: Uuid, b: Uuid| async move {
|
||||
sqlx::query_as::<_, SynastryRow>(&format!(
|
||||
"SELECT {SYNASTRY_COLUMNS} FROM synastries \
|
||||
WHERE (chart1_id = $1 AND chart2_id = $2) OR (chart1_id = $2 AND chart2_id = $1)"
|
||||
))
|
||||
.bind(a)
|
||||
.bind(b)
|
||||
.fetch_optional(&state.db)
|
||||
.await
|
||||
};
|
||||
if let Some(row) = existing(chart1.id, chart2.id).await? {
|
||||
return Ok((row, false));
|
||||
}
|
||||
|
||||
let request = json!({
|
||||
"person1": without(&chart1.birth_data, &["options"]),
|
||||
"person2": without(&chart2.birth_data, &["options"]),
|
||||
"options": chart1.birth_data.get("options").cloned().unwrap_or_else(|| json!({})),
|
||||
});
|
||||
let response = state.horoscope.synastry(&request).await?;
|
||||
let result = without(&response, &["person1", "person2", "meta"]);
|
||||
let hash = synastry_hash(&chart1.chart_hash, &chart2.chart_hash, &result["settings"]);
|
||||
|
||||
let inserted: Option<SynastryRow> = sqlx::query_as(&format!(
|
||||
"INSERT INTO synastries (id, owner_id, chart1_id, chart2_id, result, synastry_hash) \
|
||||
VALUES ($1, $2, $3, $4, $5, $6) ON CONFLICT (chart1_id, chart2_id) DO NOTHING RETURNING {SYNASTRY_COLUMNS}"
|
||||
))
|
||||
.bind(Uuid::now_v7())
|
||||
.bind(owner)
|
||||
.bind(chart1.id)
|
||||
.bind(chart2.id)
|
||||
.bind(result)
|
||||
.bind(hash)
|
||||
.fetch_optional(&state.db)
|
||||
.await?;
|
||||
match inserted {
|
||||
Some(row) => Ok((row, true)),
|
||||
// Created concurrently.
|
||||
None => Ok((existing(chart1.id, chart2.id).await?.ok_or(ApiError::NotFound("synastry"))?, false)),
|
||||
}
|
||||
}
|
||||
|
||||
pub async fn list(State(state): St, auth: AuthUser) -> ApiResult<Json<Value>> {
|
||||
type Row = (Uuid, bool, Uuid, String, Uuid, Uuid, String, Uuid, Value, OffsetDateTime);
|
||||
let rows: Vec<Row> = sqlx::query_as(
|
||||
"SELECT s.id, s.owner_id = $1, c1.id, c1.label, c1.owner_id, c2.id, c2.label, c2.owner_id, \
|
||||
s.result -> 'summary', s.created_at \
|
||||
FROM synastries s JOIN charts c1 ON c1.id = s.chart1_id JOIN charts c2 ON c2.id = s.chart2_id \
|
||||
WHERE s.owner_id = $1 OR c1.owner_id = $1 OR c2.owner_id = $1 ORDER BY s.created_at DESC",
|
||||
)
|
||||
.bind(auth.id())
|
||||
.fetch_all(&state.db)
|
||||
.await?;
|
||||
let me = auth.id();
|
||||
let list: Vec<Value> = rows
|
||||
.into_iter()
|
||||
.map(|(id, owned, c1, l1, o1, c2, l2, o2, summary, at)| {
|
||||
json!({
|
||||
"id": id, "owned": owned,
|
||||
"chart1": { "id": c1, "label": l1, "owned": o1 == me },
|
||||
"chart2": { "id": c2, "label": l2, "owned": o2 == me },
|
||||
"summary": summary, "created_at": rfc3339(at),
|
||||
})
|
||||
})
|
||||
.collect();
|
||||
Ok(Json(json!({ "synastries": list })))
|
||||
}
|
||||
|
||||
#[derive(Deserialize)]
|
||||
#[serde(deny_unknown_fields)]
|
||||
pub struct CreateSynastry {
|
||||
chart1_id: Uuid,
|
||||
chart2_id: Uuid,
|
||||
}
|
||||
|
||||
/// Compares two of the user's own charts.
|
||||
pub async fn create(
|
||||
State(state): St,
|
||||
auth: AuthUser,
|
||||
WithRejection(Json(req), _): Body<CreateSynastry>,
|
||||
) -> ApiResult<(StatusCode, Json<Value>)> {
|
||||
if req.chart1_id == req.chart2_id {
|
||||
return Err(ApiError::BadRequest("a chart cannot be compared with itself".into()));
|
||||
}
|
||||
let chart1 = owned_chart(&state.db, req.chart1_id, auth.id()).await?;
|
||||
let chart2 = owned_chart(&state.db, req.chart2_id, auth.id()).await?;
|
||||
let (row, created) = compute_synastry(&state, auth.id(), &chart1, &chart2).await?;
|
||||
let s = visible_synastry(&state.db, row.id, auth.id()).await?;
|
||||
let status = if created { StatusCode::CREATED } else { StatusCode::OK };
|
||||
Ok((status, Json(synastry_view(&state.db, &s, auth.id()).await?)))
|
||||
}
|
||||
|
||||
pub async fn get_one(State(state): St, auth: AuthUser, WithRejection(Path(id), _): IdPath) -> ApiResult<Json<Value>> {
|
||||
let s = visible_synastry(&state.db, id, auth.id()).await?;
|
||||
Ok(Json(synastry_view(&state.db, &s, auth.id()).await?))
|
||||
}
|
||||
|
||||
/// Either side may remove the synastry (and with it the link between them).
|
||||
pub async fn remove(State(state): St, auth: AuthUser, WithRejection(Path(id), _): IdPath) -> ApiResult<StatusCode> {
|
||||
visible_synastry(&state.db, id, auth.id()).await?;
|
||||
sqlx::query("DELETE FROM synastries WHERE id = $1").bind(id).execute(&state.db).await?;
|
||||
Ok(StatusCode::NO_CONTENT)
|
||||
}
|
||||
|
||||
// --- invitations -----------------------------------------------------------------------------
|
||||
|
||||
#[derive(Deserialize)]
|
||||
#[serde(deny_unknown_fields)]
|
||||
pub struct CreateInvite {
|
||||
/// Defaults to the user's primary chart.
|
||||
chart_id: Option<Uuid>,
|
||||
message: Option<String>,
|
||||
}
|
||||
|
||||
async fn chart_or_primary(db: &PgPool, chart_id: Option<Uuid>, user: Uuid) -> Result<ChartRow, ApiError> {
|
||||
match chart_id {
|
||||
Some(id) => owned_chart(db, id, user).await,
|
||||
None => primary_chart(db, user).await?.ok_or_else(|| {
|
||||
ApiError::conflict("primary_chart_required", "create your own chart first (is_primary: true)")
|
||||
}),
|
||||
}
|
||||
}
|
||||
|
||||
pub async fn create_invite(
|
||||
State(state): St,
|
||||
auth: AuthUser,
|
||||
WithRejection(Json(req), _): Body<CreateInvite>,
|
||||
) -> ApiResult<(StatusCode, Json<Value>)> {
|
||||
let chart = chart_or_primary(&state.db, req.chart_id, auth.id()).await?;
|
||||
let message = req.message.map(|m| m.trim().chars().take(500).collect::<String>()).filter(|m| !m.is_empty());
|
||||
let token = db::new_token();
|
||||
let id = Uuid::now_v7();
|
||||
let expires_at = OffsetDateTime::now_utc() + INVITE_TTL;
|
||||
sqlx::query(
|
||||
"INSERT INTO synastry_invites (id, inviter_id, inviter_chart_id, token_hash, message, expires_at) \
|
||||
VALUES ($1, $2, $3, $4, $5, $6)",
|
||||
)
|
||||
.bind(id)
|
||||
.bind(auth.id())
|
||||
.bind(chart.id)
|
||||
.bind(db::token_hash(&token))
|
||||
.bind(&message)
|
||||
.bind(expires_at)
|
||||
.execute(&state.db)
|
||||
.await?;
|
||||
Ok((
|
||||
StatusCode::CREATED,
|
||||
Json(json!({
|
||||
"id": id,
|
||||
"token": token,
|
||||
"url": format!("{}/invite/{token}", state.config.public_base_url),
|
||||
"chart_id": chart.id,
|
||||
"message": message,
|
||||
"expires_at": rfc3339(expires_at),
|
||||
})),
|
||||
))
|
||||
}
|
||||
|
||||
fn invite_status(accepted_at: Option<OffsetDateTime>, expires_at: OffsetDateTime) -> &'static str {
|
||||
if accepted_at.is_some() {
|
||||
"accepted"
|
||||
} else if expires_at <= OffsetDateTime::now_utc() {
|
||||
"expired"
|
||||
} else {
|
||||
"pending"
|
||||
}
|
||||
}
|
||||
|
||||
pub async fn list_invites(State(state): St, auth: AuthUser) -> ApiResult<Json<Value>> {
|
||||
type Row = (
|
||||
Uuid,
|
||||
Uuid,
|
||||
Option<String>,
|
||||
OffsetDateTime,
|
||||
OffsetDateTime,
|
||||
Option<OffsetDateTime>,
|
||||
Option<Uuid>,
|
||||
Option<String>,
|
||||
);
|
||||
let rows: Vec<Row> = sqlx::query_as(
|
||||
"SELECT i.id, i.inviter_chart_id, i.message, i.created_at, i.expires_at, i.accepted_at, i.synastry_id, \
|
||||
u.display_name \
|
||||
FROM synastry_invites i LEFT JOIN users u ON u.id = i.accepted_by \
|
||||
WHERE i.inviter_id = $1 ORDER BY i.created_at DESC",
|
||||
)
|
||||
.bind(auth.id())
|
||||
.fetch_all(&state.db)
|
||||
.await?;
|
||||
let list: Vec<Value> = rows
|
||||
.into_iter()
|
||||
.map(|(id, chart_id, message, created, expires, accepted, synastry_id, accepted_by)| {
|
||||
json!({
|
||||
"id": id, "chart_id": chart_id, "message": message,
|
||||
"status": invite_status(accepted, expires),
|
||||
"created_at": rfc3339(created), "expires_at": rfc3339(expires),
|
||||
"accepted_at": rfc3339_opt(accepted), "accepted_by": accepted_by, "synastry_id": synastry_id,
|
||||
})
|
||||
})
|
||||
.collect();
|
||||
Ok(Json(json!({ "invites": list })))
|
||||
}
|
||||
|
||||
pub async fn revoke_invite(
|
||||
State(state): St,
|
||||
auth: AuthUser,
|
||||
WithRejection(Path(id), _): IdPath,
|
||||
) -> ApiResult<StatusCode> {
|
||||
let result = sqlx::query(
|
||||
"UPDATE synastry_invites SET expires_at = now() \
|
||||
WHERE id = $1 AND inviter_id = $2 AND accepted_at IS NULL AND expires_at > now()",
|
||||
)
|
||||
.bind(id)
|
||||
.bind(auth.id())
|
||||
.execute(&state.db)
|
||||
.await?;
|
||||
if result.rows_affected() == 0 {
|
||||
return Err(ApiError::NotFound("pending invitation"));
|
||||
}
|
||||
Ok(StatusCode::NO_CONTENT)
|
||||
}
|
||||
|
||||
#[derive(sqlx::FromRow)]
|
||||
struct InviteRow {
|
||||
id: Uuid,
|
||||
inviter_id: Uuid,
|
||||
inviter_chart_id: Uuid,
|
||||
message: Option<String>,
|
||||
expires_at: OffsetDateTime,
|
||||
accepted_at: Option<OffsetDateTime>,
|
||||
inviter_name: Option<String>,
|
||||
}
|
||||
|
||||
async fn invite_by_token(db: &PgPool, token: &str) -> Result<InviteRow, ApiError> {
|
||||
sqlx::query_as(
|
||||
"SELECT i.id, i.inviter_id, i.inviter_chart_id, i.message, i.expires_at, i.accepted_at, \
|
||||
u.display_name AS inviter_name \
|
||||
FROM synastry_invites i JOIN users u ON u.id = i.inviter_id WHERE i.token_hash = $1",
|
||||
)
|
||||
.bind(db::token_hash(token.trim()))
|
||||
.fetch_optional(db)
|
||||
.await?
|
||||
.ok_or(ApiError::NotFound("invitation"))
|
||||
}
|
||||
|
||||
/// Public landing data of an invitation link (no login, no birth data).
|
||||
pub async fn public_invite(State(state): St, Path(token): Path<String>) -> ApiResult<Json<Value>> {
|
||||
let invite = invite_by_token(&state.db, &token).await?;
|
||||
Ok(Json(json!({
|
||||
"inviter_name": invite.inviter_name,
|
||||
"message": invite.message,
|
||||
"status": invite_status(invite.accepted_at, invite.expires_at),
|
||||
"expires_at": rfc3339(invite.expires_at),
|
||||
})))
|
||||
}
|
||||
|
||||
#[derive(Deserialize)]
|
||||
#[serde(deny_unknown_fields)]
|
||||
pub struct AcceptInvite {
|
||||
token: String,
|
||||
/// Defaults to the invitee's primary chart.
|
||||
chart_id: Option<Uuid>,
|
||||
}
|
||||
|
||||
/// The invitee accepts: their chart is compared with the inviter's, and the
|
||||
/// synastry becomes visible to both.
|
||||
pub async fn accept_invite(
|
||||
State(state): St,
|
||||
auth: AuthUser,
|
||||
WithRejection(Json(req), _): Body<AcceptInvite>,
|
||||
) -> ApiResult<(StatusCode, Json<Value>)> {
|
||||
let invite = invite_by_token(&state.db, &req.token).await?;
|
||||
match invite_status(invite.accepted_at, invite.expires_at) {
|
||||
"accepted" => return Err(ApiError::Gone("this invitation has already been accepted".into())),
|
||||
"expired" => return Err(ApiError::Gone("this invitation has expired".into())),
|
||||
_ => {}
|
||||
}
|
||||
if invite.inviter_id == auth.id() {
|
||||
return Err(ApiError::conflict("own_invitation", "you cannot accept your own invitation"));
|
||||
}
|
||||
let my_chart = chart_or_primary(&state.db, req.chart_id, auth.id()).await?;
|
||||
let inviter_chart =
|
||||
find_chart(&state.db, invite.inviter_chart_id).await?.ok_or(ApiError::NotFound("invitation"))?;
|
||||
let (row, _) = compute_synastry(&state, invite.inviter_id, &inviter_chart, &my_chart).await?;
|
||||
|
||||
let mut tx = state.db.begin().await?;
|
||||
sqlx::query(
|
||||
"UPDATE synastry_invites SET accepted_at = now(), accepted_by = $1, synastry_id = $2 \
|
||||
WHERE id = $3 AND accepted_at IS NULL",
|
||||
)
|
||||
.bind(auth.id())
|
||||
.bind(row.id)
|
||||
.bind(invite.id)
|
||||
.execute(&mut *tx)
|
||||
.await?;
|
||||
let inviter: Option<db::User> = sqlx::query_as(&format!("SELECT {USER_COLUMNS} FROM users WHERE id = $1"))
|
||||
.bind(invite.inviter_id)
|
||||
.fetch_optional(&mut *tx)
|
||||
.await?;
|
||||
if let Some(inviter) = inviter {
|
||||
let url = format!("{}/synastry/{}", state.config.public_base_url, row.id);
|
||||
super::auth::queue_email(
|
||||
&mut tx,
|
||||
&inviter,
|
||||
"invite_accepted",
|
||||
json!({ "url": url, "invitee_name": auth.user.display_name }),
|
||||
)
|
||||
.await?;
|
||||
}
|
||||
tx.commit().await?;
|
||||
|
||||
let s = visible_synastry(&state.db, row.id, auth.id()).await?;
|
||||
Ok((StatusCode::CREATED, Json(synastry_view(&state.db, &s, auth.id()).await?)))
|
||||
}
|
||||
@@ -0,0 +1,560 @@
|
||||
//! End-to-end tests against a real PostgreSQL database.
|
||||
//!
|
||||
//! `DATABASE_URL` must point to a server where the user may create databases
|
||||
//! (e.g. the `postgres` service of docker-compose); every test gets a fresh,
|
||||
//! migrated database. The horoscope service and Google's key endpoint are
|
||||
//! replaced by a small fake HTTP server.
|
||||
|
||||
use std::sync::Arc;
|
||||
|
||||
use axum::body::Body;
|
||||
use axum::http::{HeaderMap, Request, StatusCode};
|
||||
use axum::routing::{get, post};
|
||||
use axum::{Json, Router};
|
||||
use http_body_util::BodyExt;
|
||||
use serde_json::{Value, json};
|
||||
use sqlx::PgPool;
|
||||
use tower::ServiceExt;
|
||||
|
||||
use crate::config::Config;
|
||||
use crate::{AppState, routes};
|
||||
|
||||
const GOOGLE_CLIENT: &str = "test-client.apps.googleusercontent.com";
|
||||
const GOOGLE_KEY_PEM: &[u8] = include_bytes!("../testdata/google-test-key.pem");
|
||||
const GOOGLE_KEY_N: &str = include_str!("../testdata/google-test-key.n");
|
||||
|
||||
// --- fake horoscope service and Google key endpoint --------------------------------------
|
||||
|
||||
async fn fake_natal(Json(body): Json<Value>) -> (StatusCode, Json<Value>) {
|
||||
if body["place"] == "Nincsilyenhely" {
|
||||
return (
|
||||
StatusCode::NOT_FOUND,
|
||||
Json(json!({"error": {"code": "place_not_found", "message": "place not found", "suggestions": []}})),
|
||||
);
|
||||
}
|
||||
let date = body["date"].as_str().unwrap_or("2000-01-01");
|
||||
let time = body["time"].as_str();
|
||||
(
|
||||
StatusCode::OK,
|
||||
Json(json!({
|
||||
"input": body,
|
||||
"location": {"country": {"name": "Hungary"}, "place": {"name": body["place"]}, "latitude": 47.0, "longitude": 19.0},
|
||||
"time": {"local": format!("{date}T{}:00", time.unwrap_or("12:00")), "utc": format!("{date}T11:00:00Z"), "time_known": time.is_some()},
|
||||
"astronomy": {"julian_day_ut": 2451545.0},
|
||||
"settings": body.get("options").cloned().unwrap_or(json!({"house_system": "placidus"})),
|
||||
"points": [{"id": "sun", "sign": "cancer", "longitude": 90.4}, {"id": "moon", "sign": "pisces", "longitude": 338.2}],
|
||||
"angles": {"ascendant": {"sign": "aries", "longitude": 18.0}},
|
||||
"warnings": [],
|
||||
"meta": {"data_sources": {"ephemeris": {"version": "test"}}}
|
||||
})),
|
||||
)
|
||||
}
|
||||
|
||||
async fn fake_synastry(Json(body): Json<Value>) -> (StatusCode, Json<Value>) {
|
||||
// Like the real service: options only at the top level.
|
||||
if body["person1"].get("options").is_some() || body["person2"].get("options").is_some() {
|
||||
return (
|
||||
StatusCode::BAD_REQUEST,
|
||||
Json(json!({"error": {"code": "bad_request", "message": "per-person options"}})),
|
||||
);
|
||||
}
|
||||
(
|
||||
StatusCode::OK,
|
||||
Json(json!({
|
||||
"person1": {"input": body["person1"]}, "person2": {"input": body["person2"]},
|
||||
"settings": {"aspect_set": "major"},
|
||||
"aspects": [{"person1": "sun", "person2": "moon", "aspect": "trine"}],
|
||||
"house_overlays": {"person1_in_person2": [], "person2_in_person1": []},
|
||||
"summary": {"aspect_count": 1},
|
||||
"composite": {"method": "midpoint", "points": []},
|
||||
"meta": {}
|
||||
})),
|
||||
)
|
||||
}
|
||||
|
||||
async fn fake_jwks() -> Json<Value> {
|
||||
Json(
|
||||
json!({"keys": [{"kid": "test-key", "kty": "RSA", "alg": "RS256", "use": "sig", "n": GOOGLE_KEY_N.trim(), "e": "AQAB"}]}),
|
||||
)
|
||||
}
|
||||
|
||||
async fn fake_services() -> String {
|
||||
let app = Router::new()
|
||||
.route("/v1/natal", post(fake_natal))
|
||||
.route("/v1/synastry", post(fake_synastry))
|
||||
.route("/jwks", get(fake_jwks));
|
||||
let listener = tokio::net::TcpListener::bind("127.0.0.1:0").await.unwrap();
|
||||
let addr = listener.local_addr().unwrap();
|
||||
tokio::spawn(async move { axum::serve(listener, app).await.unwrap() });
|
||||
format!("http://{addr}")
|
||||
}
|
||||
|
||||
fn google_token(sub: &str, email: &str, audience: &str) -> String {
|
||||
let now = time::OffsetDateTime::now_utc().unix_timestamp();
|
||||
let claims = json!({
|
||||
"iss": "https://accounts.google.com", "aud": audience, "sub": sub, "email": email,
|
||||
"email_verified": true, "name": "Google Gábor", "iat": now, "exp": now + 3600
|
||||
});
|
||||
let mut header = jsonwebtoken::Header::new(jsonwebtoken::Algorithm::RS256);
|
||||
header.kid = Some("test-key".into());
|
||||
jsonwebtoken::encode(&header, &claims, &jsonwebtoken::EncodingKey::from_rsa_pem(GOOGLE_KEY_PEM).unwrap()).unwrap()
|
||||
}
|
||||
|
||||
// --- test client -------------------------------------------------------------------------------
|
||||
|
||||
struct TestApp {
|
||||
router: Router,
|
||||
pool: PgPool,
|
||||
}
|
||||
|
||||
struct Response {
|
||||
status: StatusCode,
|
||||
body: Value,
|
||||
headers: HeaderMap,
|
||||
}
|
||||
|
||||
impl TestApp {
|
||||
async fn new(pool: PgPool) -> Self {
|
||||
let fake = fake_services().await;
|
||||
let config = Config::for_tests(String::new(), fake.clone(), format!("{fake}/jwks"));
|
||||
Self { router: routes::router(Arc::new(AppState::new(pool.clone(), config))), pool }
|
||||
}
|
||||
|
||||
async fn call(&self, method: &str, uri: &str, token: Option<&str>, body: Option<Value>) -> Response {
|
||||
let mut req = Request::builder().method(method).uri(uri);
|
||||
if let Some(t) = token {
|
||||
req = req.header("authorization", format!("Bearer {t}"));
|
||||
}
|
||||
let body = match body {
|
||||
Some(v) => {
|
||||
req = req.header("content-type", "application/json");
|
||||
Body::from(v.to_string())
|
||||
}
|
||||
None => Body::empty(),
|
||||
};
|
||||
let resp = self.router.clone().oneshot(req.body(body).unwrap()).await.unwrap();
|
||||
let status = resp.status();
|
||||
let headers = resp.headers().clone();
|
||||
let bytes = resp.into_body().collect().await.unwrap().to_bytes();
|
||||
Response { status, body: serde_json::from_slice(&bytes).unwrap_or(Value::Null), headers }
|
||||
}
|
||||
|
||||
async fn get(&self, uri: &str, token: Option<&str>) -> Response {
|
||||
self.call("GET", uri, token, None).await
|
||||
}
|
||||
|
||||
async fn post(&self, uri: &str, token: Option<&str>, body: Value) -> Response {
|
||||
self.call("POST", uri, token, Some(body)).await
|
||||
}
|
||||
|
||||
/// Registers a user; returns the session token.
|
||||
async fn register(&self, email: &str, name: &str) -> String {
|
||||
let r = self
|
||||
.post(
|
||||
"/v1/auth/register",
|
||||
None,
|
||||
json!({"email": email, "password": "titkos-jelszo-123", "display_name": name}),
|
||||
)
|
||||
.await;
|
||||
assert_eq!(r.status, StatusCode::CREATED, "{}", r.body);
|
||||
r.body["session"]["token"].as_str().unwrap().to_string()
|
||||
}
|
||||
|
||||
async fn chart(&self, token: &str, label: &str, primary: bool, date: &str) -> Value {
|
||||
let r = self
|
||||
.post(
|
||||
"/v1/charts",
|
||||
Some(token),
|
||||
json!({"label": label, "is_primary": primary,
|
||||
"birth": {"name": "Secret Name", "date": date, "time": "14:30", "country": "HU", "place": "Szeged"}}),
|
||||
)
|
||||
.await;
|
||||
assert_eq!(r.status, StatusCode::CREATED, "{}", r.body);
|
||||
r.body
|
||||
}
|
||||
|
||||
async fn outbox_url(&self, email: &str, template: &str) -> String {
|
||||
let (payload,): (Value,) = sqlx::query_as(
|
||||
"SELECT payload FROM email_outbox WHERE to_email = $1 AND template = $2 ORDER BY created_at DESC LIMIT 1",
|
||||
)
|
||||
.bind(email)
|
||||
.bind(template)
|
||||
.fetch_one(&self.pool)
|
||||
.await
|
||||
.unwrap();
|
||||
payload["url"].as_str().unwrap().to_string()
|
||||
}
|
||||
}
|
||||
|
||||
fn token_param(url: &str) -> &str {
|
||||
url.split("token=").nth(1).unwrap()
|
||||
}
|
||||
|
||||
// --- tests ------------------------------------------------------------------------------------
|
||||
|
||||
#[sqlx::test(migrator = "db::MIGRATOR")]
|
||||
async fn register_login_verify_logout(pool: PgPool) {
|
||||
let app = TestApp::new(pool).await;
|
||||
let r = app
|
||||
.post("/v1/auth/register", None, json!({"email": "Anna@Example.com", "password": "titkos-jelszo-123"}))
|
||||
.await;
|
||||
assert_eq!(r.status, StatusCode::CREATED, "{}", r.body);
|
||||
let cookie = r.headers.get("set-cookie").unwrap().to_str().unwrap();
|
||||
assert!(cookie.starts_with("sf_session=") && cookie.contains("HttpOnly") && cookie.contains("Secure"));
|
||||
assert_eq!(r.body["user"]["email"], "anna@example.com");
|
||||
assert_eq!(r.body["user"]["roles"], json!(["user"]));
|
||||
assert_eq!(r.body["user"]["email_verified"], false);
|
||||
let token = r.body["session"]["token"].as_str().unwrap().to_string();
|
||||
|
||||
// duplicate, short password
|
||||
let r = app
|
||||
.post("/v1/auth/register", None, json!({"email": "anna@example.com", "password": "titkos-jelszo-123"}))
|
||||
.await;
|
||||
assert_eq!((r.status, r.body["error"]["code"].as_str()), (StatusCode::CONFLICT, Some("email_taken")));
|
||||
let r = app.post("/v1/auth/register", None, json!({"email": "b@example.com", "password": "rovid"})).await;
|
||||
assert_eq!(r.status, StatusCode::BAD_REQUEST);
|
||||
|
||||
let r = app.get("/v1/me", Some(&token)).await;
|
||||
assert_eq!(r.status, StatusCode::OK);
|
||||
assert_eq!(r.body["providers"], json!(["password"]));
|
||||
assert_eq!(r.body["credits"], 2);
|
||||
|
||||
// e-mail verification through the queued e-mail's link
|
||||
let url = app.outbox_url("anna@example.com", "verify_email").await;
|
||||
assert!(url.starts_with("https://sorsfonalak.test/verify-email?token="));
|
||||
let r = app.post("/v1/auth/verify-email", None, json!({"token": token_param(&url)})).await;
|
||||
assert_eq!(r.status, StatusCode::OK, "{}", r.body);
|
||||
let r = app.post("/v1/auth/verify-email", None, json!({"token": token_param(&url)})).await;
|
||||
assert_eq!(r.body["error"]["code"], "invalid_token");
|
||||
assert_eq!(app.get("/v1/me", Some(&token)).await.body["user"]["email_verified"], true);
|
||||
|
||||
// login
|
||||
let r =
|
||||
app.post("/v1/auth/login", None, json!({"email": "anna@example.com", "password": "rossz-jelszo-123"})).await;
|
||||
assert_eq!((r.status, r.body["error"]["code"].as_str()), (StatusCode::UNAUTHORIZED, Some("invalid_credentials")));
|
||||
let r =
|
||||
app.post("/v1/auth/login", None, json!({"email": "nincs@example.com", "password": "titkos-jelszo-123"})).await;
|
||||
assert_eq!(r.status, StatusCode::UNAUTHORIZED);
|
||||
let r =
|
||||
app.post("/v1/auth/login", None, json!({"email": "ANNA@example.com", "password": "titkos-jelszo-123"})).await;
|
||||
assert_eq!(r.status, StatusCode::OK, "{}", r.body);
|
||||
let second = r.body["session"]["token"].as_str().unwrap().to_string();
|
||||
|
||||
// logout ends only that session; guards answer 401 without a session
|
||||
assert_eq!(app.post("/v1/auth/logout", Some(&token), json!({})).await.status, StatusCode::NO_CONTENT);
|
||||
assert_eq!(app.get("/v1/me", Some(&token)).await.status, StatusCode::UNAUTHORIZED);
|
||||
assert_eq!(app.get("/v1/me", Some(&second)).await.status, StatusCode::OK);
|
||||
assert_eq!(app.get("/v1/me", None).await.status, StatusCode::UNAUTHORIZED);
|
||||
assert_eq!(app.get("/v1/charts", Some("garbage")).await.status, StatusCode::UNAUTHORIZED);
|
||||
}
|
||||
|
||||
#[sqlx::test(migrator = "db::MIGRATOR")]
|
||||
async fn password_reset_ends_sessions(pool: PgPool) {
|
||||
let app = TestApp::new(pool).await;
|
||||
let token = app.register("anna@example.com", "Anna").await;
|
||||
// unknown address: same answer
|
||||
assert_eq!(
|
||||
app.post("/v1/auth/password-reset", None, json!({"email": "x@example.com"})).await.status,
|
||||
StatusCode::ACCEPTED
|
||||
);
|
||||
assert_eq!(
|
||||
app.post("/v1/auth/password-reset", None, json!({"email": "anna@example.com"})).await.status,
|
||||
StatusCode::ACCEPTED
|
||||
);
|
||||
let url = app.outbox_url("anna@example.com", "reset_password").await;
|
||||
let r = app
|
||||
.post(
|
||||
"/v1/auth/password-reset/confirm",
|
||||
None,
|
||||
json!({"token": token_param(&url), "password": "uj-titkos-jelszo-456"}),
|
||||
)
|
||||
.await;
|
||||
assert_eq!(r.status, StatusCode::NO_CONTENT, "{}", r.body);
|
||||
assert_eq!(app.get("/v1/me", Some(&token)).await.status, StatusCode::UNAUTHORIZED);
|
||||
let r = app
|
||||
.post("/v1/auth/login", None, json!({"email": "anna@example.com", "password": "uj-titkos-jelszo-456"}))
|
||||
.await;
|
||||
assert_eq!(r.status, StatusCode::OK);
|
||||
}
|
||||
|
||||
#[sqlx::test(migrator = "db::MIGRATOR")]
|
||||
async fn google_login_creates_links_and_rejects(pool: PgPool) {
|
||||
let app = TestApp::new(pool).await;
|
||||
let r = app
|
||||
.post("/v1/auth/google", None, json!({"id_token": google_token("g-1", "gabor@gmail.com", GOOGLE_CLIENT)}))
|
||||
.await;
|
||||
assert_eq!(r.status, StatusCode::CREATED, "{}", r.body);
|
||||
assert_eq!(r.body["created"], true);
|
||||
assert_eq!(r.body["user"]["email_verified"], true);
|
||||
assert_eq!(r.body["user"]["display_name"], "Google Gábor");
|
||||
let r = app
|
||||
.post("/v1/auth/google", None, json!({"id_token": google_token("g-1", "gabor@gmail.com", GOOGLE_CLIENT)}))
|
||||
.await;
|
||||
assert_eq!((r.status, &r.body["created"]), (StatusCode::OK, &json!(false)));
|
||||
|
||||
// an existing password account with the same address gets Google linked
|
||||
let token = app.register("anna@example.com", "Anna").await;
|
||||
let r = app
|
||||
.post("/v1/auth/google", None, json!({"id_token": google_token("g-2", "anna@example.com", GOOGLE_CLIENT)}))
|
||||
.await;
|
||||
assert_eq!((r.status, &r.body["created"]), (StatusCode::OK, &json!(false)));
|
||||
assert_eq!(app.get("/v1/me", Some(&token)).await.body["providers"], json!(["password", "google"]));
|
||||
|
||||
let r = app
|
||||
.post("/v1/auth/google", None, json!({"id_token": google_token("g-3", "x@gmail.com", "other-client")}))
|
||||
.await;
|
||||
assert_eq!(r.status, StatusCode::UNAUTHORIZED);
|
||||
let r = app.post("/v1/auth/google", None, json!({"id_token": "not-a-jwt"})).await;
|
||||
assert_eq!(r.status, StatusCode::UNAUTHORIZED);
|
||||
}
|
||||
|
||||
#[sqlx::test(migrator = "db::MIGRATOR")]
|
||||
async fn roles_and_admin_guard(pool: PgPool) {
|
||||
let app = TestApp::new(pool).await;
|
||||
let user = app.register("anna@example.com", "Anna").await;
|
||||
let admin = app.register("admin@example.com", "Admin").await; // BOOTSTRAP_ADMIN_EMAILS
|
||||
assert_eq!(app.get("/v1/me", Some(&admin)).await.body["user"]["roles"], json!(["user", "admin"]));
|
||||
|
||||
assert_eq!(app.get("/v1/admin/users", None).await.status, StatusCode::UNAUTHORIZED);
|
||||
let r = app.get("/v1/admin/users", Some(&user)).await;
|
||||
assert_eq!((r.status, r.body["error"]["code"].as_str()), (StatusCode::FORBIDDEN, Some("forbidden")));
|
||||
|
||||
let r = app.get("/v1/admin/users?q=anna", Some(&admin)).await;
|
||||
assert_eq!(r.status, StatusCode::OK, "{}", r.body);
|
||||
let users = r.body["users"].as_array().unwrap();
|
||||
assert_eq!(users.len(), 1);
|
||||
let anna = users[0]["id"].as_str().unwrap().to_string();
|
||||
|
||||
let r = app
|
||||
.call("PATCH", &format!("/v1/admin/users/{anna}"), Some(&admin), Some(json!({"roles": ["user", "creator"]})))
|
||||
.await;
|
||||
assert_eq!(r.body["roles"], json!(["creator", "user"]));
|
||||
let r = app.call("PATCH", &format!("/v1/admin/users/{anna}"), Some(&admin), Some(json!({"roles": ["root"]}))).await;
|
||||
assert_eq!(r.status, StatusCode::BAD_REQUEST);
|
||||
let admin_id = app.get("/v1/me", Some(&admin)).await.body["user"]["id"].as_str().unwrap().to_string();
|
||||
let r =
|
||||
app.call("PATCH", &format!("/v1/admin/users/{admin_id}"), Some(&admin), Some(json!({"roles": ["user"]}))).await;
|
||||
assert_eq!(r.status, StatusCode::CONFLICT);
|
||||
|
||||
let r =
|
||||
app.post(&format!("/v1/admin/users/{anna}/credits"), Some(&admin), json!({"delta": 5, "note": "bonus"})).await;
|
||||
assert_eq!(r.status, StatusCode::CREATED);
|
||||
assert_eq!(app.get("/v1/credits", Some(&user)).await.body["balance"], 7); // 2 monthly + 5
|
||||
}
|
||||
|
||||
#[sqlx::test(migrator = "db::MIGRATOR")]
|
||||
async fn charts_are_private(pool: PgPool) {
|
||||
let app = TestApp::new(pool).await;
|
||||
let anna = app.register("anna@example.com", "Anna").await;
|
||||
let bela = app.register("bela@example.com", "Béla").await;
|
||||
let own = app.chart(&anna, "Saját", true, "1990-03-15").await;
|
||||
assert_eq!(own["highlights"]["sun"], "cancer");
|
||||
assert!(own["birth_data"].get("name").is_none(), "names must not be stored or sent");
|
||||
let id = own["id"].as_str().unwrap();
|
||||
|
||||
let other = app.chart(&anna, "Anya", true, "1950-03-01").await;
|
||||
let list = app.get("/v1/charts", Some(&anna)).await.body;
|
||||
assert_eq!(list["charts"].as_array().unwrap().len(), 2);
|
||||
assert_eq!(list["charts"][0]["id"], other["id"]); // the new primary first
|
||||
assert_eq!(list["charts"][1]["is_primary"], false);
|
||||
|
||||
assert_eq!(app.get(&format!("/v1/charts/{id}"), Some(&bela)).await.status, StatusCode::NOT_FOUND);
|
||||
assert_eq!(app.call("DELETE", &format!("/v1/charts/{id}"), Some(&bela), None).await.status, StatusCode::NOT_FOUND);
|
||||
assert_eq!(app.get("/v1/charts/not-a-uuid", Some(&anna)).await.status, StatusCode::BAD_REQUEST);
|
||||
|
||||
// birth data errors of the horoscope service are passed through
|
||||
let r = app
|
||||
.post(
|
||||
"/v1/charts",
|
||||
Some(&anna),
|
||||
json!({"label": "X", "birth": {"date": "1990-01-01", "country": "HU", "place": "Nincsilyenhely"}}),
|
||||
)
|
||||
.await;
|
||||
assert_eq!((r.status, r.body["error"]["code"].as_str()), (StatusCode::NOT_FOUND, Some("place_not_found")));
|
||||
|
||||
let r = app
|
||||
.call("PATCH", &format!("/v1/charts/{id}"), Some(&anna), Some(json!({"label": "Én", "is_primary": true})))
|
||||
.await;
|
||||
assert_eq!((r.body["label"].as_str(), &r.body["is_primary"]), (Some("Én"), &json!(true)));
|
||||
assert_eq!(app.call("DELETE", &format!("/v1/charts/{id}"), Some(&anna), None).await.status, StatusCode::NO_CONTENT);
|
||||
}
|
||||
|
||||
#[sqlx::test(migrator = "db::MIGRATOR")]
|
||||
async fn invitation_links_two_users(pool: PgPool) {
|
||||
let app = TestApp::new(pool).await;
|
||||
let anna = app.register("anna@example.com", "Anna").await;
|
||||
let bela = app.register("bela@example.com", "Béla").await;
|
||||
|
||||
let r = app.post("/v1/invites", Some(&anna), json!({"message": "Nézzük meg!"})).await;
|
||||
assert_eq!((r.status, r.body["error"]["code"].as_str()), (StatusCode::CONFLICT, Some("primary_chart_required")));
|
||||
app.chart(&anna, "Saját", true, "1990-03-15").await;
|
||||
let r = app.post("/v1/invites", Some(&anna), json!({"message": "Nézzük meg!"})).await;
|
||||
assert_eq!(r.status, StatusCode::CREATED, "{}", r.body);
|
||||
let token = r.body["token"].as_str().unwrap().to_string();
|
||||
assert!(r.body["url"].as_str().unwrap().ends_with(&token));
|
||||
|
||||
// public landing page data, no login
|
||||
let r = app.get(&format!("/v1/public/invites/{token}"), None).await;
|
||||
assert_eq!(
|
||||
r.body,
|
||||
json!({"inviter_name": "Anna", "message": "Nézzük meg!", "status": "pending", "expires_at": r.body["expires_at"]})
|
||||
);
|
||||
|
||||
let r = app.post("/v1/invites/accept", Some(&anna), json!({"token": token})).await;
|
||||
assert_eq!(r.status, StatusCode::CONFLICT); // own invitation
|
||||
let r = app.post("/v1/invites/accept", Some(&bela), json!({"token": token})).await;
|
||||
assert_eq!(r.status, StatusCode::CONFLICT); // Béla has no chart yet
|
||||
app.chart(&bela, "Saját", true, "1976-09-03").await;
|
||||
let r = app.post("/v1/invites/accept", Some(&bela), json!({"token": token})).await;
|
||||
assert_eq!(r.status, StatusCode::CREATED, "{}", r.body);
|
||||
let synastry_id = r.body["id"].as_str().unwrap().to_string();
|
||||
assert_eq!(r.body["synastry"]["summary"]["aspect_count"], 1);
|
||||
assert!(r.body["synastry"].get("person1").is_none());
|
||||
assert_eq!(r.body["chart2"]["owned"], true);
|
||||
assert_eq!(r.body["chart1"]["owned"], false);
|
||||
assert_eq!(r.body["chart1"]["label"], "Anna"); // the inviter's name, not her label
|
||||
assert!(r.body["chart1"].get("birth_data").is_none());
|
||||
assert!(r.body["chart1"]["chart"].get("time").is_none());
|
||||
|
||||
// both see it; Anna does not see Béla's birth data
|
||||
let r = app.get(&format!("/v1/synastries/{synastry_id}"), Some(&anna)).await;
|
||||
assert_eq!(r.status, StatusCode::OK);
|
||||
assert_eq!(r.body["owned"], true);
|
||||
assert!(r.body["chart2"].get("birth_data").is_none());
|
||||
assert!(r.body["chart1"]["birth_data"].is_object());
|
||||
assert_eq!(app.get("/v1/synastries", Some(&bela)).await.body["synastries"].as_array().unwrap().len(), 1);
|
||||
let outsider = app.register("c@example.com", "C").await;
|
||||
assert_eq!(app.get(&format!("/v1/synastries/{synastry_id}"), Some(&outsider)).await.status, StatusCode::NOT_FOUND);
|
||||
|
||||
let r = app.post("/v1/invites/accept", Some(&outsider), json!({"token": token})).await;
|
||||
assert_eq!(r.status, StatusCode::GONE);
|
||||
assert_eq!(app.get("/v1/invites", Some(&anna)).await.body["invites"][0]["status"], "accepted");
|
||||
assert!(app.outbox_url("anna@example.com", "invite_accepted").await.ends_with(&synastry_id));
|
||||
}
|
||||
|
||||
#[sqlx::test(migrator = "db::MIGRATOR")]
|
||||
async fn analyses_spend_credits_and_reuse_results(pool: PgPool) {
|
||||
let app = TestApp::new(pool.clone()).await;
|
||||
let anna = app.register("anna@example.com", "Anna").await;
|
||||
let chart = app.chart(&anna, "Saját", true, "1990-03-15").await;
|
||||
let uri = format!("/v1/charts/{}/analyses", chart["id"].as_str().unwrap());
|
||||
|
||||
let r = app.call("POST", &uri, Some(&anna), None).await;
|
||||
assert_eq!(r.status, StatusCode::ACCEPTED, "{}", r.body);
|
||||
assert_eq!((r.body["status"].as_str(), r.body["language"].as_str()), (Some("pending"), Some("hu")));
|
||||
let first = r.body["id"].as_str().unwrap().to_string();
|
||||
assert_eq!(app.get("/v1/credits", Some(&anna)).await.body["balance"], 1);
|
||||
|
||||
// same request again: the same analysis, no charge
|
||||
let r = app.call("POST", &uri, Some(&anna), None).await;
|
||||
assert_eq!((r.status, r.body["id"].as_str()), (StatusCode::OK, Some(first.as_str())));
|
||||
let r = app.post(&uri, Some(&anna), json!({"language": "en"})).await;
|
||||
assert_eq!(r.status, StatusCode::ACCEPTED);
|
||||
let r = app.post(&uri, Some(&anna), json!({"model": "anthropic/claude-test"})).await;
|
||||
assert_eq!(
|
||||
(r.status, r.body["error"]["code"].as_str()),
|
||||
(StatusCode::PAYMENT_REQUIRED, Some("insufficient_credits"))
|
||||
);
|
||||
let r = app.post(&uri, Some(&anna), json!({"model": "unknown/model"})).await;
|
||||
assert_eq!(r.status, StatusCode::BAD_REQUEST);
|
||||
|
||||
// the worker finishes the first one; another user with the same birth data gets it for free
|
||||
sqlx::query("UPDATE analyses SET status = 'done', content = $1, completed_at = now() WHERE id = $2::uuid")
|
||||
.bind(json!({"summary": "Érzékeny mag, harcos külső."}))
|
||||
.bind(&first)
|
||||
.execute(&pool)
|
||||
.await
|
||||
.unwrap();
|
||||
let bela = app.register("bela@example.com", "Béla").await;
|
||||
let same = app.chart(&bela, "Saját", true, "1990-03-15").await;
|
||||
assert_eq!(same["chart_hash"], chart["chart_hash"]);
|
||||
let r = app.call("POST", &format!("/v1/charts/{}/analyses", same["id"].as_str().unwrap()), Some(&bela), None).await;
|
||||
assert_eq!(r.status, StatusCode::CREATED, "{}", r.body);
|
||||
assert_eq!((r.body["status"].as_str(), &r.body["credits_charged"]), (Some("done"), &json!(0)));
|
||||
assert_eq!(app.get("/v1/credits", Some(&bela)).await.body["balance"], 2);
|
||||
|
||||
assert_eq!(app.get(&format!("/v1/analyses/{first}"), Some(&bela)).await.status, StatusCode::NOT_FOUND);
|
||||
assert_eq!(app.get(&uri, Some(&anna)).await.body["analyses"].as_array().unwrap().len(), 2);
|
||||
}
|
||||
|
||||
#[sqlx::test(migrator = "db::MIGRATOR")]
|
||||
async fn public_shares(pool: PgPool) {
|
||||
let app = TestApp::new(pool).await;
|
||||
let anna = app.register("anna@example.com", "Anna").await;
|
||||
let chart = app.chart(&anna, "Saját", true, "1990-03-15").await;
|
||||
let chart_id = chart["id"].as_str().unwrap();
|
||||
|
||||
let r = app
|
||||
.post("/v1/shares", Some(&anna), json!({"kind": "chart", "target_id": chart_id, "title": "A radixom"}))
|
||||
.await;
|
||||
assert_eq!(r.status, StatusCode::CREATED, "{}", r.body);
|
||||
let (share_id, slug) = (r.body["id"].as_str().unwrap().to_string(), r.body["slug"].as_str().unwrap().to_string());
|
||||
assert_eq!(slug.len(), 16);
|
||||
|
||||
let r = app.get(&format!("/v1/public/shares/{slug}"), None).await;
|
||||
assert_eq!(r.status, StatusCode::OK, "{}", r.body);
|
||||
assert_eq!(r.body["title"], "A radixom");
|
||||
let shown = &r.body["chart"]["chart"];
|
||||
assert_eq!(shown["points"][0]["sign"], "cancer");
|
||||
for hidden in ["input", "location", "time", "astronomy", "birth"] {
|
||||
assert!(shown.get(hidden).is_none(), "{hidden} must not be public");
|
||||
}
|
||||
|
||||
let r = app
|
||||
.post("/v1/shares", Some(&anna), json!({"kind": "chart", "target_id": chart_id, "show_birth_data": true}))
|
||||
.await;
|
||||
let r = app.get(&format!("/v1/public/shares/{}", r.body["slug"].as_str().unwrap()), None).await;
|
||||
assert_eq!(r.body["chart"]["chart"]["birth"]["date"], "1990-03-15");
|
||||
|
||||
// others cannot share it; revoked links disappear
|
||||
let bela = app.register("bela@example.com", "Béla").await;
|
||||
let r = app.post("/v1/shares", Some(&bela), json!({"kind": "chart", "target_id": chart_id})).await;
|
||||
assert_eq!(r.status, StatusCode::NOT_FOUND);
|
||||
assert_eq!(
|
||||
app.call("DELETE", &format!("/v1/shares/{share_id}"), Some(&anna), None).await.status,
|
||||
StatusCode::NO_CONTENT
|
||||
);
|
||||
assert_eq!(app.get(&format!("/v1/public/shares/{slug}"), None).await.status, StatusCode::NOT_FOUND);
|
||||
assert_eq!(app.get("/v1/public/shares/nincs-ilyen", None).await.status, StatusCode::NOT_FOUND);
|
||||
}
|
||||
|
||||
#[sqlx::test(migrator = "db::MIGRATOR")]
|
||||
async fn export_and_delete_account(pool: PgPool) {
|
||||
let app = TestApp::new(pool).await;
|
||||
let anna = app.register("anna@example.com", "Anna").await;
|
||||
let bela = app.register("bela@example.com", "Béla").await;
|
||||
let a = app.chart(&anna, "Saját", true, "1990-03-15").await;
|
||||
let b = app.chart(&anna, "Béla", false, "1976-09-03").await;
|
||||
let r = app.post("/v1/synastries", Some(&anna), json!({"chart1_id": a["id"], "chart2_id": b["id"]})).await;
|
||||
assert_eq!(r.status, StatusCode::CREATED, "{}", r.body);
|
||||
let r = app.post("/v1/synastries", Some(&anna), json!({"chart1_id": b["id"], "chart2_id": a["id"]})).await;
|
||||
assert_eq!(r.status, StatusCode::OK); // already exists
|
||||
|
||||
let r = app.get("/v1/me/export", Some(&anna)).await;
|
||||
assert_eq!(r.status, StatusCode::OK);
|
||||
assert_eq!(r.body["charts"].as_array().unwrap().len(), 2);
|
||||
assert_eq!(r.body["synastries"].as_array().unwrap().len(), 1);
|
||||
assert!(r.body["login_methods"][0].get("password_hash").is_none());
|
||||
|
||||
let r = app.call("DELETE", "/v1/me", Some(&anna), Some(json!({"confirm": "yes"}))).await;
|
||||
assert_eq!(r.status, StatusCode::BAD_REQUEST);
|
||||
let r = app.call("DELETE", "/v1/me", Some(&anna), Some(json!({"confirm": "DELETE"}))).await;
|
||||
assert_eq!(r.status, StatusCode::NO_CONTENT);
|
||||
assert_eq!(app.get("/v1/me", Some(&anna)).await.status, StatusCode::UNAUTHORIZED);
|
||||
let r =
|
||||
app.post("/v1/auth/login", None, json!({"email": "anna@example.com", "password": "titkos-jelszo-123"})).await;
|
||||
assert_eq!(r.status, StatusCode::UNAUTHORIZED);
|
||||
let (left,): (i64,) = sqlx::query_as("SELECT count(*) FROM charts").fetch_one(&app.pool).await.unwrap();
|
||||
assert_eq!(left, 0);
|
||||
assert_eq!(app.get("/v1/me", Some(&bela)).await.status, StatusCode::OK);
|
||||
}
|
||||
|
||||
#[sqlx::test(migrator = "db::MIGRATOR")]
|
||||
async fn public_config_and_health(pool: PgPool) {
|
||||
let app = TestApp::new(pool).await;
|
||||
let r = app.get("/v1/config", None).await;
|
||||
assert_eq!(r.body["google_login"]["enabled"], true);
|
||||
assert_eq!(r.body["google_login"]["client_id"], GOOGLE_CLIENT);
|
||||
assert_eq!(r.body["locales"], json!(["hu", "en"]));
|
||||
assert_eq!(app.get("/healthz", None).await.status, StatusCode::OK);
|
||||
}
|
||||
@@ -0,0 +1,129 @@
|
||||
//! JSON shapes returned by the API and helpers to build them.
|
||||
|
||||
use db::User;
|
||||
use serde::Serialize;
|
||||
use serde_json::{Map, Value, json};
|
||||
use sha2::{Digest, Sha256};
|
||||
use time::OffsetDateTime;
|
||||
use uuid::Uuid;
|
||||
|
||||
pub fn sha256_hex(text: &str) -> String {
|
||||
Sha256::digest(text.as_bytes()).iter().map(|b| format!("{b:02x}")).collect()
|
||||
}
|
||||
|
||||
/// Identifies a calculated chart independently of how the place was entered:
|
||||
/// the resolved UTC moment, coordinates, options and ephemeris version.
|
||||
pub fn chart_hash(result: &Value) -> String {
|
||||
let settings = serde_json::to_string(&result["settings"]).unwrap_or_default();
|
||||
sha256_hex(&format!(
|
||||
"natal|{}|{}|{:.5}|{:.5}|{settings}|{}",
|
||||
result["time"]["utc"].as_str().unwrap_or_default(),
|
||||
result["time"]["time_known"].as_bool().unwrap_or(true),
|
||||
result["location"]["latitude"].as_f64().unwrap_or_default(),
|
||||
result["location"]["longitude"].as_f64().unwrap_or_default(),
|
||||
result["meta"]["data_sources"]["ephemeris"]["version"].as_str().unwrap_or_default(),
|
||||
))
|
||||
}
|
||||
|
||||
pub fn synastry_hash(hash1: &str, hash2: &str, settings: &Value) -> String {
|
||||
sha256_hex(&format!("synastry|{hash1}|{hash2}|{}", serde_json::to_string(settings).unwrap_or_default()))
|
||||
}
|
||||
|
||||
/// The chart without anything that identifies the birth (date, time, place,
|
||||
/// Julian day, request echo); positions, houses, aspects and summary stay.
|
||||
/// With `show_birth_data` a short `birth` block is added instead.
|
||||
pub fn public_chart(result: &Value, show_birth_data: bool) -> Value {
|
||||
let mut out = Map::new();
|
||||
if let Some(obj) = result.as_object() {
|
||||
for (k, v) in obj {
|
||||
if !matches!(k.as_str(), "input" | "location" | "time" | "astronomy" | "meta" | "warnings") {
|
||||
out.insert(k.clone(), v.clone());
|
||||
}
|
||||
}
|
||||
}
|
||||
out.insert("time_known".into(), result["time"]["time_known"].clone());
|
||||
if show_birth_data {
|
||||
let known = result["time"]["time_known"].as_bool().unwrap_or(false);
|
||||
let local = result["time"]["local"].as_str().unwrap_or_default();
|
||||
let (date, time) = local.split_once('T').unwrap_or((local, ""));
|
||||
out.insert(
|
||||
"birth".into(),
|
||||
json!({
|
||||
"date": date,
|
||||
"time": if known { Value::from(time.get(..5).unwrap_or(time)) } else { Value::Null },
|
||||
"place": result["location"]["place"]["name"],
|
||||
"region": result["location"]["place"]["region"],
|
||||
"country": result["location"]["country"]["name"],
|
||||
}),
|
||||
);
|
||||
}
|
||||
Value::Object(out)
|
||||
}
|
||||
|
||||
/// Sign of a point or angle, for compact listings.
|
||||
pub fn chart_highlights(result: &Value) -> Value {
|
||||
let sign_of = |id: &str| {
|
||||
result["points"].as_array().and_then(|ps| ps.iter().find(|p| p["id"] == id)).map(|p| p["sign"].clone())
|
||||
};
|
||||
json!({
|
||||
"sun": sign_of("sun"),
|
||||
"moon": sign_of("moon"),
|
||||
"ascendant": result["angles"]["ascendant"]["sign"],
|
||||
"time_known": result["time"]["time_known"],
|
||||
})
|
||||
}
|
||||
|
||||
#[derive(Debug, Serialize)]
|
||||
pub struct UserView {
|
||||
pub id: Uuid,
|
||||
pub email: String,
|
||||
pub email_verified: bool,
|
||||
pub display_name: Option<String>,
|
||||
pub locale: String,
|
||||
pub roles: Vec<String>,
|
||||
#[serde(with = "time::serde::rfc3339")]
|
||||
pub created_at: OffsetDateTime,
|
||||
}
|
||||
|
||||
impl From<&User> for UserView {
|
||||
fn from(u: &User) -> Self {
|
||||
Self {
|
||||
id: u.id,
|
||||
email: u.email.clone(),
|
||||
email_verified: u.email_verified_at.is_some(),
|
||||
display_name: u.display_name.clone(),
|
||||
locale: u.locale.clone(),
|
||||
roles: u.roles.clone(),
|
||||
created_at: u.created_at,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
pub fn rfc3339(t: OffsetDateTime) -> String {
|
||||
t.format(&time::format_description::well_known::Rfc3339).unwrap_or_default()
|
||||
}
|
||||
|
||||
pub fn rfc3339_opt(t: Option<OffsetDateTime>) -> Value {
|
||||
t.map(|t| Value::from(rfc3339(t))).unwrap_or(Value::Null)
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
#[test]
|
||||
fn public_chart_hides_birth_data() {
|
||||
let result = json!({
|
||||
"input": {"date": "1990-03-15"}, "location": {"place": {"name": "Szeged"}, "country": {"name": "Hungary"}},
|
||||
"time": {"local": "1990-03-15T14:30:00", "time_known": true}, "astronomy": {"julian_day_ut": 1.0},
|
||||
"meta": {}, "warnings": [], "points": [{"id": "sun", "sign": "cancer"}]
|
||||
});
|
||||
let hidden = public_chart(&result, false);
|
||||
assert!(hidden.get("input").is_none() && hidden.get("location").is_none() && hidden.get("birth").is_none());
|
||||
assert_eq!(hidden["points"][0]["sign"], "cancer");
|
||||
let shown = public_chart(&result, true);
|
||||
assert_eq!(shown["birth"]["date"], "1990-03-15");
|
||||
assert_eq!(shown["birth"]["time"], "14:30");
|
||||
assert_eq!(shown["birth"]["place"], "Szeged");
|
||||
}
|
||||
}
|
||||
Vendored
+2
@@ -0,0 +1,2 @@
|
||||
Throwaway RSA key used only by the backend tests to sign fake Google ID tokens.
|
||||
It is not used anywhere else; do not reuse it.
|
||||
+1
@@ -0,0 +1 @@
|
||||
8gBbbqG6MkLkqmNSeumuj5eq_E5QUlf9MqR__Pp_A9UHHUS1Iv0_5EfHTs5EXqSoFNcS6RtSOcH-33eqgGrvxtXkZVjMEofzDBthwApWzFTGa6e5I1tfg5wrYVP8HQLcP6BT1dJYb2UrM7g-AAiMSAGSl-e_hAiLuct8T3-80Z3uWcovfv6iMGgo485_CuFbWmo1WhTjIrAevD8IIU8JlCnEBVLn94LFI1VYXL3nmH37jS2RYcIGkfbxnZM2EpFIWlH4YCEdPEqdQ2utiAJolqEK2hRlQ_cOUJWU-B9f8iehatjZZK9DYXntOqi7BP34M-CHc2kGPgLL_474fP_t0w
|
||||
+28
@@ -0,0 +1,28 @@
|
||||
-----BEGIN PRIVATE KEY-----
|
||||
MIIEvQIBADANBgkqhkiG9w0BAQEFAASCBKcwggSjAgEAAoIBAQDyAFtuoboyQuSq
|
||||
Y1J66a6Pl6r8TlBSV/0ypH/8+n8D1QcdRLUi/T/kR8dOzkRepKgU1xLpG1I5wf7f
|
||||
d6qAau/G1eRlWMwSh/MMG2HAClbMVMZrp7kjW1+DnCthU/wdAtw/oFPV0lhvZSsz
|
||||
uD4ACIxIAZKX57+ECIu5y3xPf7zRne5Zyi9+/qIwaCjjzn8K4VtaajVaFOMisB68
|
||||
PwghTwmUKcQFUuf3gsUjVVhcveeYffuNLZFhwgaR9vGdkzYSkUhaUfhgIR08Sp1D
|
||||
a62IAmiWoQraFGVD9w5QlZT4H1/yJ6Fq2Nlkr0Nhee06qLsE/fgz4IdzaQY+Asv/
|
||||
jvh8/+3TAgMBAAECggEAah0v+m3eGGXuoKwWoaDQE1S8/A9W9xRwCQHKwWIRydti
|
||||
WDoldyc3GeFDitG1dw6aSTEZsK9zObJQESsGz3KUm0p08N+j9Eg6kcd78FpYPxa5
|
||||
PsF31AIf+rTC7NWHyizT6O5jdHHcp1PkQrR6M0eMQ5K09fj/qGSa6ChK5Q0s/Xh5
|
||||
mZe+/PXoBamyOtwTgsd/EOfcaTalJOKSPopFKE+PiQk3Qtl5ak9r6Sccqf3GUkSe
|
||||
4sPc29+W9vpAn//JC3MmuBvoFduf+T8y8rujRYkID0qT/e+xmnzi0dOVd1tmBcPo
|
||||
e2oKhhsOcynRVMRieNcrIWlg4VprF+9OZks6im3u4QKBgQD8pPwyoTXCpxXT5oxW
|
||||
hxSckCA1bnOJ5SPD8h3EyPh7GkhR+/olHQh5m2ag7Zh4w+2JAMftgNaquyXf4rC8
|
||||
ND/SbIZ/wc5CGHR+JkHYsqF/c7/u4I9wu7GKW+FbreJIqPoeh/KKZqRLRpxzOImr
|
||||
BUolODPNfIi67T+9w/gHY0k/gwKBgQD1Ny8+hhCYPNPw3zwGp8fY1/bNMgqkdUE/
|
||||
Od88pAtDqsoza0CLuvYaB+s+cI8J+CUSzDpQKz8yaP4GQ0AckaRekZ1AtipAzbMl
|
||||
QJ0PqbK2BGFaCy217nkVU0fXhWZ+Y9LG+qUL3c6i/gtOR+BfQ3i+etHGFQdBZbX7
|
||||
6WwMqDd3cQKBgERBpsle+JFQZvtK7FtsP0tVPP5yitCUkaccwKIr0cYgga10sE5a
|
||||
m7GPJJkR2AG4nXJIPbuS9WxHB6KHMkyGqT+Ghof5qmn9BWwXle6fxDYU5aP6E4bX
|
||||
js3cqPQF9H7A+GJLRGHT/UtBFn+ipL8JvNB1cLlxjddCxdfVHCuSzXVVAoGBAKlN
|
||||
MJE6frqdRLdJaWgu7wwID54crrxdOG8uxbJYkG5nvLNDmYzfyIqwbPrvO9LmQLJ5
|
||||
zskLEtb7JmeshtcytwmT/75uBz42xzkxIz9tKrYA0DYbAbRasb7HgRKMR/d7dEtt
|
||||
QgavXburKqMhfQhIzVS195+LZTcBwmPrBW63tZQBAoGAPUccCBKBfuef7cAfF9Tl
|
||||
IiTqLHzCEo7TBwd8VFcafgSZrAR9tGi+U53cbvAoLcHgZgRPV0i8ZxPvPbt/1a6A
|
||||
nW/9FqSqQu19CoOSAm8kbMZ2nuPymGusbGVHGnX7bpzHrPXL5QaNHVmSmozt6BR2
|
||||
k3xaPb/x6krGxUEVfOWkc5o=
|
||||
-----END PRIVATE KEY-----
|
||||
Reference in New Issue
Block a user