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:
feco
2026-11-15 10:25:35 +00:00
co-authored by Claude Opus 5.5
parent 0b5416df45
commit 3a84110565
148 changed files with 95803 additions and 0 deletions
+182
View File
@@ -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))))
}
+129
View File
@@ -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 }))))
}
+265
View File
@@ -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()))
}
+466
View File
@@ -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());
}
}
+222
View File
@@ -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)
}
+123
View File
@@ -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,
}))
}
+211
View File
@@ -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?))
}
+431
View File
@@ -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?)))
}