A new Kártyajóslás page: choose a spread (1, 3 or 5 cards), ask a question, pick the cards from the fanned deck and watch them turn over; the reading is written by the detailed-analysis model from the cards, their positions and base meanings, the question and the reader's Sun, Moon and Ascendant. The server shuffles and draws, so nobody can draw again for free. A reading is a 'tarot' analysis (worker, retries, fallback, refunds and admin regeneration as for analyses), uses one 'tarot' unit, and survives recalculations; deleting the account deletes it. Packages carry 2/5/10 readings, the new +5 kártyajóslás addon costs 1 000 Ft. The card artwork comes from the tarot design studio (celestial astrolabe style); the deck JSON is shared by the frontend and the prompt. A public example is at /kartyajoslas/pelda. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> Claude-Session: https://claude.ai/code/session_012vLHzh5qUhFtmJhzkcTbXL
209 lines
10 KiB
Rust
209 lines
10 KiB
Rust
//! 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 mut conn = state.db.acquire().await?;
|
|
let balance = credits::balance(&mut conn, auth.id()).await?;
|
|
let birth_change = crate::birth_changes::view(&mut conn, &auth).await?;
|
|
let persons = crate::persons::slots(&mut conn, &auth, state.config.free_person_slots).await?;
|
|
let package = crate::packages::current(&mut conn, auth.id()).await?;
|
|
let share_reward = super::shares::reward_granted(&state.db, auth.id()).await?;
|
|
let referrals = super::shares::referral_rewards(&mut conn, auth.id()).await?;
|
|
let (invoices,): (i64,) = sqlx::query_as("SELECT count(*) FROM invoices WHERE user_id = $1")
|
|
.bind(auth.id())
|
|
.fetch_one(&mut *conn)
|
|
.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),
|
|
"analyses_left": balance.view(),
|
|
"birth_change": birth_change,
|
|
"persons": persons.view(),
|
|
"package": package.map(|(p, since)| json!({ "id": p.id, "name": p.name, "since": rfc3339(since) })),
|
|
// The free question for a shared link is used up (once per user).
|
|
"share_reward_granted": share_reward,
|
|
// Natal analyses earned by bringing new users, and how many can be.
|
|
"referral_rewards": { "earned": referrals, "limit": super::shares::REFERRAL_LIMIT },
|
|
// The "Számláim" menu shows up with the first invoice.
|
|
"invoice_count": invoices,
|
|
})))
|
|
}
|
|
|
|
#[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> {
|
|
super::auth::password_login_enabled(&state)?;
|
|
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(&mut *state.db.acquire().await?, auth.id()).await?;
|
|
type Row = (Uuid, String, i32, String, Option<Uuid>, Option<String>, OffsetDateTime);
|
|
let ledger: Vec<Row> = sqlx::query_as(
|
|
"SELECT id, unit, delta, reason, 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.view(),
|
|
"ledger": ledger.into_iter().map(|(id, unit, delta, reason, analysis_id, note, at)| json!({
|
|
"id": id, "unit": unit, "delta": delta, "reason": reason,
|
|
"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?,
|
|
"forecasts": rows("SELECT json_build_object('id', f.id, 'chart_id', f.chart_id, 'year', f.year, 'location', f.location, 'result', f.result, 'created_at', f.created_at) FROM forecasts f JOIN charts c ON c.id = f.chart_id WHERE c.owner_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, 'forecast_id', a.forecast_id, 'language', a.language, '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?,
|
|
"questions": rows("SELECT json_build_object('id', q.id, 'analysis_id', q.analysis_id, 'question', q.question, 'status', q.status, 'answer', q.answer, 'created_at', q.created_at) FROM questions q WHERE q.asked_by = $1").await?,
|
|
"credit_ledger": rows("SELECT json_build_object('unit', unit, 'delta', delta, 'reason', reason, '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, tarot readings, 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()));
|
|
}
|
|
let mut tx = state.db.begin().await?;
|
|
// Tarot readings belong to no chart: they go with the account.
|
|
sqlx::query("DELETE FROM analyses WHERE kind = 'tarot' AND requested_by = $1")
|
|
.bind(auth.id())
|
|
.execute(&mut *tx)
|
|
.await?;
|
|
sqlx::query("DELETE FROM users WHERE id = $1").bind(auth.id()).execute(&mut *tx).await?;
|
|
tx.commit().await?;
|
|
tracing::info!(user = %auth.id(), "account deleted");
|
|
Ok((StatusCode::NO_CONTENT, jar.add(removal_cookie(&state.config))))
|
|
}
|