Files
sorsfonalak/services/backend/src/routes/account.rs
T

183 lines
8.5 KiB
Rust
Raw Normal View History

//! 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,
"llm_models": state.config.llm_models,
"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))))
}