//! Invitations to the closed site. //! //! While `SIGNUP_MODE=invite`, a new account needs an open invitation for its //! e-mail address, or an invitation link (then any address will do, because //! people often sign in with another Google account than the one their friend //! knows). Only administrators invite; the worker sends the e-mails. //! //! People who asked for no more invitations are kept as the hash of their //! address. People without an invitation can join the waitlist. //! //! An invitation can come with a package: a promo code is made with it, the //! e-mail shows it with its redeem link, and it is redeemed by itself when //! the invitee signs up (revoking the invitation withdraws it). use axum::Json; use axum::extract::{Path, Query, State}; use axum::http::StatusCode; use axum_extra::extract::WithRejection; use serde::Deserialize; use serde_json::{Value, json}; use sqlx::PgConnection; use time::OffsetDateTime; use uuid::Uuid; use super::auth::{normalize_email, queue_email_to, validate_locale}; use super::{Body, IdPath, St}; use crate::AppState; use crate::auth::AdminUser; use crate::config::SignupMode; use crate::error::{ApiError, ApiResult}; use crate::packages; use crate::views::{rfc3339, rfc3339_opt}; /// The package of an invitation, as shown in its e-mail: (code as shown, package name). type Gift = (String, &'static str); pub const INVITATION_TTL: time::Duration = time::Duration::days(30); /// A resend is possible this often, and at most this many sendings in all. const RESEND_GAP: time::Duration = time::Duration::hours(24); const MAX_SENDINGS: i32 = 3; const MAX_MESSAGE_CHARS: usize = 300; const MAX_BATCH: usize = 50; // --- the gate ------------------------------------------------------------------------------- /// Whether a new account may be created for `email` (with the invitation link /// `token`, if the visitor came through one). pub async fn admit( state: &AppState, conn: &mut PgConnection, email: &str, token: Option<&str>, ) -> Result<(), ApiError> { if state.config.signup_mode == SignupMode::Open || state.config.bootstrap_admin_emails.iter().any(|e| e == email) { return Ok(()); } let hash = token.map(|t| db::token_hash(t.trim())); let invited: bool = sqlx::query_scalar( "SELECT EXISTS (SELECT 1 FROM invitations i WHERE i.accepted_at IS NULL AND i.revoked_at IS NULL \ AND i.expires_at > now() \ AND (i.email = $1 OR i.id IN (SELECT invitation_id FROM invitation_tokens WHERE token_hash = $2))) \ -- a \"how compatible are we?\" link also lets the invitee in OR EXISTS (SELECT 1 FROM synastry_invites WHERE token_hash = $2 AND accepted_at IS NULL AND expires_at > now())", ) .bind(email) .bind(hash) .fetch_one(&mut *conn) .await?; if invited { Ok(()) } else { Err(ApiError::Refused { code: "not_invited", message: "A Sorsfonalak jelenleg meghívásos: ehhez az e-mail-címhez nem tartozik meghívó.".into(), }) } } /// After a new account is created: its invitations count as accepted, it /// leaves the waitlist, and the packages of those invitations are redeemed /// (`free_slots`: the person slots everyone gets). pub async fn mark_accepted( conn: &mut PgConnection, user_id: Uuid, email: &str, token: Option<&str>, free_slots: i64, ) -> Result<(), ApiError> { let hash = token.map(|t| db::token_hash(t.trim())); sqlx::query( "UPDATE invitations SET accepted_at = now(), accepted_by = $1 \ WHERE accepted_at IS NULL AND revoked_at IS NULL \ AND (email = $2 OR (expires_at > now() AND id IN (SELECT invitation_id FROM invitation_tokens WHERE token_hash = $3)))", ) .bind(user_id) .bind(email) .bind(hash) .execute(&mut *conn) .await?; sqlx::query("DELETE FROM waitlist WHERE email = $1").bind(email).execute(&mut *conn).await?; let codes: Vec<(Uuid, String, String)> = sqlx::query_as( "SELECT p.id, p.code, p.package FROM promo_codes p JOIN invitations i ON i.id = p.invitation_id \ WHERE i.accepted_by = $1 AND p.redeemed_at IS NULL AND p.revoked_at IS NULL FOR UPDATE OF p", ) .bind(user_id) .fetch_all(&mut *conn) .await?; for (id, code, package) in codes { let Some(package) = packages::find(&package) else { continue }; let persons_left = crate::persons::left(conn, user_id, free_slots).await?; super::promo::redeem_code(conn, id, &code, package, user_id, Some(persons_left)).await?; tracing::info!(user = %user_id, package = package.id, "invitation package redeemed"); } Ok(()) } /// The open promo code of an invitation, for its e-mail. async fn gift_of(conn: &mut PgConnection, invitation_id: Uuid) -> Result, sqlx::Error> { let row: Option<(String, String)> = sqlx::query_as( "SELECT code, package FROM promo_codes WHERE invitation_id = $1 AND redeemed_at IS NULL AND revoked_at IS NULL", ) .bind(invitation_id) .fetch_optional(conn) .await?; Ok(row.and_then(|(code, package)| packages::find(&package).map(|p| (super::promo::display(&code), p.name)))) } // --- sending --------------------------------------------------------------------------------- pub(super) fn clean_message(message: Option) -> Result, ApiError> { let Some(message) = message.map(|m| m.replace("\r\n", "\n").trim().to_owned()).filter(|m| !m.is_empty()) else { return Ok(None); }; if message.chars().count() > MAX_MESSAGE_CHARS { return Err(ApiError::BadRequest(format!("A személyes üzenet legfeljebb {MAX_MESSAGE_CHARS} karakter lehet."))); } // Links in a mail from our domain are what spammers would use this field for. let lower = message.to_lowercase(); if lower.contains("://") || lower.contains("www.") { return Err(ApiError::BadRequest("A személyes üzenetben nem lehet link.".into())); } Ok(Some(message)) } pub(super) fn links(state: &AppState, token: &str) -> (String, String, String) { let base = &state.config.public_base_url; ( format!("{base}/meghivo/{token}"), format!("{base}/leiratkozas?token={token}"), format!("{base}/api/v1/public/invitations/unsubscribe?token={token}"), ) } fn payload( state: &AppState, token: &str, inviter: Option<&str>, message: Option<&str>, expires: OffsetDateTime, gift: Option<&Gift>, ) -> Value { let (url, unsubscribe_url, unsubscribe_post_url) = links(state, token); let base = &state.config.public_base_url; json!({ "package_name": gift.map(|g| g.1), "promo_code": gift.map(|g| g.0.as_str()), "redeem_url": gift.map(|g| format!("{base}/bevaltas?kod={}", g.0)), "url": url, "unsubscribe_url": unsubscribe_url, "unsubscribe_post_url": unsubscribe_post_url, "inviter_name": inviter, "message": message, "expires_on": expires.date().to_string(), }) } /// Issues a new link token for an invitation and queues the e-mail; returns the link. #[allow(clippy::too_many_arguments)] async fn send( state: &AppState, conn: &mut PgConnection, id: Uuid, email: &str, locale: &str, inviter: Option<&str>, message: Option<&str>, expires: OffsetDateTime, gift: Option<&Gift>, ) -> Result { let token = db::new_token(); sqlx::query("INSERT INTO invitation_tokens (token_hash, invitation_id) VALUES ($1, $2)") .bind(db::token_hash(&token)) .bind(id) .execute(&mut *conn) .await?; let payload = payload(state, &token, inviter, message, expires, gift); let url = payload["url"].as_str().unwrap_or_default().to_owned(); queue_email_to(conn, None, email, "invitation", locale, payload).await?; Ok(url) } pub(super) async fn opted_out(conn: &mut PgConnection, email: &str) -> Result { Ok(sqlx::query_scalar("SELECT EXISTS (SELECT 1 FROM email_optouts WHERE email_hash = $1)") .bind(db::token_hash(email)) .fetch_one(conn) .await?) } // --- admin ------------------------------------------------------------------------------------ #[derive(Deserialize)] #[serde(deny_unknown_fields)] pub struct CreateInvitations { emails: Vec, message: Option, locale: Option, /// A package from the catalog the invitees get (as a promo code). package: Option, } /// Invites a list of addresses. Each gets a result: `invited` (with the /// link, to pass on by hand if needed), `already_user`, `already_invited`, /// `opted_out` or `invalid`. pub async fn create( State(state): St, AdminUser(admin): AdminUser, WithRejection(Json(req), _): Body, ) -> ApiResult<(StatusCode, Json)> { if req.emails.is_empty() || req.emails.len() > MAX_BATCH { return Err(ApiError::BadRequest(format!("1–{MAX_BATCH} e-mail-cím adható meg egyszerre."))); } let message = clean_message(req.message)?; let locale = validate_locale(&state, req.locale.as_deref())?; let package = match req.package.as_deref().filter(|p| !p.is_empty()) { Some(id) => Some(packages::find(id).ok_or(ApiError::NotFound("package"))?), None => None, }; let inviter = admin.user.display_name.clone(); let mut results = Vec::new(); let mut seen = std::collections::HashSet::new(); let mut tx = state.db.begin().await?; for raw in &req.emails { let raw = raw.trim(); let Ok(email) = normalize_email(raw) else { results.push(json!({ "email": raw, "status": "invalid" })); continue; }; if !seen.insert(email.clone()) { continue; } let user: bool = sqlx::query_scalar("SELECT EXISTS (SELECT 1 FROM users WHERE email = $1)") .bind(&email) .fetch_one(&mut *tx) .await?; if user { results.push(json!({ "email": email, "status": "already_user" })); continue; } if opted_out(&mut tx, &email).await? { results.push(json!({ "email": email, "status": "opted_out" })); continue; } // An expired open invitation gives way to the new one. sqlx::query( "UPDATE invitations SET revoked_at = now() \ WHERE email = $1 AND accepted_at IS NULL AND revoked_at IS NULL AND expires_at <= now()", ) .bind(&email) .execute(&mut *tx) .await?; let id = Uuid::now_v7(); let expires = OffsetDateTime::now_utc() + INVITATION_TTL; let inserted = sqlx::query( "INSERT INTO invitations (id, email, message, locale, invited_by, expires_at) \ VALUES ($1, $2, $3, $4, $5, $6) ON CONFLICT DO NOTHING", ) .bind(id) .bind(&email) .bind(&message) .bind(&locale) .bind(admin.id()) .bind(expires) .execute(&mut *tx) .await? .rows_affected(); if inserted == 0 { results.push(json!({ "email": email, "status": "already_invited" })); continue; } let gift = match package { Some(p) => { let note = format!("meghívó: {email}"); let code = super::promo::new_code(&mut tx, p.id, Some(¬e), Some(admin.id()), Some(id)).await?; Some((super::promo::display(&code), p.name)) } None => None, }; let url = send(&state, &mut tx, id, &email, &locale, inviter.as_deref(), message.as_deref(), expires, gift.as_ref()) .await?; results.push(json!({ "email": email, "status": "invited", "id": id, "url": url, "promo_code": gift.as_ref().map(|g| &g.0), })); } tx.commit().await?; Ok((StatusCode::CREATED, Json(json!({ "results": results })))) } #[derive(sqlx::FromRow)] struct Row { id: Uuid, email: String, message: Option, locale: String, created_at: OffsetDateTime, expires_at: OffsetDateTime, sent_count: i32, last_sent_at: OffsetDateTime, accepted_at: Option, revoked_at: Option, invited_by_name: Option, accepted_by_name: Option, mail_created_at: Option, mail_sent_at: Option, mail_failed_at: Option, mail_error: Option, promo_code: Option, promo_package: Option, promo_redeemed_at: Option, } fn status(accepted: Option, revoked: Option, expires: OffsetDateTime) -> &'static str { if accepted.is_some() { "accepted" } else if revoked.is_some() { "revoked" } else if expires <= OffsetDateTime::now_utc() { "expired" } else { "pending" } } /// Every invitation (newest first) with the state of its last e-mail, and the waitlist. pub async fn list(State(state): St, _admin: AdminUser) -> ApiResult> { let rows: Vec = sqlx::query_as( "SELECT i.id, i.email, i.message, i.locale, i.created_at, i.expires_at, i.sent_count, i.last_sent_at, \ i.accepted_at, i.revoked_at, inv.display_name AS invited_by_name, \ coalesce(acc.display_name, acc.email) AS accepted_by_name, \ m.created_at AS mail_created_at, m.sent_at AS mail_sent_at, m.failed_at AS mail_failed_at, m.last_error AS mail_error, \ pc.code AS promo_code, pc.package AS promo_package, pc.redeemed_at AS promo_redeemed_at \ FROM invitations i \ LEFT JOIN promo_codes pc ON pc.invitation_id = i.id \ LEFT JOIN users inv ON inv.id = i.invited_by \ LEFT JOIN users acc ON acc.id = i.accepted_by \ LEFT JOIN LATERAL (SELECT created_at, sent_at, failed_at, last_error FROM email_outbox \ WHERE to_email = i.email AND template = 'invitation' \ ORDER BY created_at DESC LIMIT 1) m ON true \ ORDER BY i.created_at DESC LIMIT 500", ) .fetch_all(&state.db) .await?; let now = OffsetDateTime::now_utc(); let invitations: Vec = rows .into_iter() .map(|r| { let status = status(r.accepted_at, r.revoked_at, r.expires_at); // Sent e-mails are removed from the outbox after a week. let mail = match (r.mail_created_at, r.mail_sent_at, r.mail_failed_at) { (None, _, _) => "archived", (_, Some(_), _) => "sent", (_, None, Some(_)) => "failed", _ => "queued", }; let can_resend = matches!(status, "pending" | "expired") && r.sent_count < MAX_SENDINGS && r.last_sent_at + RESEND_GAP <= now; json!({ "id": r.id, "email": r.email, "message": r.message, "locale": r.locale, "status": status, "created_at": rfc3339(r.created_at), "expires_at": rfc3339(r.expires_at), "sent_count": r.sent_count, "last_sent_at": rfc3339(r.last_sent_at), "accepted_at": rfc3339_opt(r.accepted_at), "accepted_by": r.accepted_by_name, "invited_by": r.invited_by_name, "mail": mail, "mail_error": r.mail_error, "can_resend": can_resend, "package": r.promo_package.as_deref().map(|p| json!({ "id": p, "name": packages::find(p).map(|p| p.name), "code": r.promo_code.as_deref().map(super::promo::display), "redeemed_at": rfc3339_opt(r.promo_redeemed_at), })), }) }) .collect(); let waitlist: Vec<(String, String, OffsetDateTime, Option)> = sqlx::query_as( "SELECT w.email, w.locale, w.created_at, \ (SELECT CASE WHEN accepted_at IS NOT NULL THEN 'accepted' WHEN expires_at > now() THEN 'pending' END \ FROM invitations WHERE email = w.email AND revoked_at IS NULL ORDER BY created_at DESC LIMIT 1) \ FROM waitlist w ORDER BY w.created_at", ) .fetch_all(&state.db) .await?; let waitlist: Vec = waitlist .into_iter() .map(|(email, locale, created, invitation)| { json!({ "email": email, "locale": locale, "created_at": rfc3339(created), "invitation": invitation }) }) .collect(); Ok(Json( json!({ "invitations": invitations, "waitlist": waitlist, "signup_mode": state.config.signup_mode.as_str() }), )) } /// Sends the invitation again with a new link (the earlier links keep /// working), and gives it another 30 days. pub async fn resend( State(state): St, AdminUser(admin): AdminUser, WithRejection(Path(id), _): IdPath, ) -> ApiResult> { let mut tx = state.db.begin().await?; #[derive(sqlx::FromRow)] struct Open { email: String, message: Option, locale: String, sent_count: i32, last_sent_at: OffsetDateTime, closed: bool, } let Open { email, message, locale, sent_count, last_sent_at: last_sent, closed } = sqlx::query_as( "SELECT email, message, locale, sent_count, last_sent_at, \ accepted_at IS NOT NULL OR revoked_at IS NOT NULL AS closed \ FROM invitations WHERE id = $1 FOR UPDATE", ) .bind(id) .fetch_optional(&mut *tx) .await? .ok_or(ApiError::NotFound("invitation"))?; if closed { return Err(ApiError::conflict("invitation_closed", "Ezt a meghívót már elfogadták vagy visszavonták.")); } if sent_count >= MAX_SENDINGS { return Err(ApiError::conflict( "resend_limit", format!("Egy meghívó legfeljebb {MAX_SENDINGS}-szor küldhető el (spamvédelem)."), )); } if last_sent + RESEND_GAP > OffsetDateTime::now_utc() { return Err(ApiError::conflict("resend_too_soon", "Újraküldés legkorábban 24 órával az előző küldés után.")); } if opted_out(&mut tx, &email).await? { return Err(ApiError::conflict("opted_out", "Ez a cím leiratkozott a meghívókról.")); } let expires = OffsetDateTime::now_utc() + INVITATION_TTL; sqlx::query( "UPDATE invitations SET sent_count = sent_count + 1, last_sent_at = now(), expires_at = $2 WHERE id = $1", ) .bind(id) .bind(expires) .execute(&mut *tx) .await?; let inviter = admin.user.display_name.clone(); let gift = gift_of(&mut tx, id).await?; let url = send(&state, &mut tx, id, &email, &locale, inviter.as_deref(), message.as_deref(), expires, gift.as_ref()) .await?; tx.commit().await?; Ok(Json(json!({ "id": id, "url": url, "expires_at": rfc3339(expires) }))) } pub async fn revoke(State(state): St, _admin: AdminUser, WithRejection(Path(id), _): IdPath) -> ApiResult { let mut tx = state.db.begin().await?; let done = sqlx::query( "UPDATE invitations SET revoked_at = now() WHERE id = $1 AND accepted_at IS NULL AND revoked_at IS NULL", ) .bind(id) .execute(&mut *tx) .await? .rows_affected(); if done == 0 { return Err(ApiError::NotFound("open invitation")); } // Its package goes with it. sqlx::query( "UPDATE promo_codes SET revoked_at = now() WHERE invitation_id = $1 AND redeemed_at IS NULL AND revoked_at IS NULL", ) .bind(id) .execute(&mut *tx) .await?; tx.commit().await?; Ok(StatusCode::NO_CONTENT) } pub async fn remove_from_waitlist( State(state): St, _admin: AdminUser, WithRejection(Path(email), _): WithRejection, ApiError>, ) -> ApiResult { sqlx::query("DELETE FROM waitlist WHERE email = $1").bind(email.trim().to_lowercase()).execute(&state.db).await?; Ok(StatusCode::NO_CONTENT) } #[derive(Deserialize)] #[serde(deny_unknown_fields)] pub struct PreviewRequest { message: Option, locale: Option, /// Also send it to the admin's own address. #[serde(default)] send_to_me: bool, /// Show it with this package (a sample code). package: Option, } /// The invitation e-mail with sample links (they lead nowhere), and /// optionally a test copy to the admin. pub async fn preview( State(state): St, AdminUser(admin): AdminUser, WithRejection(Json(req), _): Body, ) -> ApiResult> { let message = clean_message(req.message)?; let locale = validate_locale(&state, req.locale.as_deref())?; let gift = match req.package.as_deref().filter(|p| !p.is_empty()) { Some(id) => Some(("MINT-AKOD-XXXX".to_string(), packages::find(id).ok_or(ApiError::NotFound("package"))?.name)), None => None, }; let payload = payload( &state, "minta", admin.user.display_name.as_deref(), message.as_deref(), OffsetDateTime::now_utc() + INVITATION_TTL, gift.as_ref(), ); let mail = email_templates::render("invitation", &locale, &payload) .map_err(|e| ApiError::Internal(format!("invitation template: {e}")))?; if req.send_to_me { let mut conn = state.db.acquire().await?; queue_email_to(&mut conn, Some(admin.id()), &admin.user.email, "invitation", &locale, payload).await?; } Ok(Json(json!({ "subject": mail.subject, "text": mail.text, "html": mail.html, "sent_to": req.send_to_me.then_some(&admin.user.email), }))) } // --- public ------------------------------------------------------------------------------------- /// Landing data of an invitation link. pub async fn public_view(State(state): St, Path(token): Path) -> ApiResult> { #[derive(sqlx::FromRow)] struct Landing { inviter: Option, message: Option, expires_at: OffsetDateTime, accepted_at: Option, revoked_at: Option, } let l: Landing = sqlx::query_as( "SELECT u.display_name AS inviter, i.message, i.expires_at, i.accepted_at, i.revoked_at \ FROM invitation_tokens t JOIN invitations i ON i.id = t.invitation_id \ LEFT JOIN users u ON u.id = i.invited_by WHERE t.token_hash = $1", ) .bind(db::token_hash(token.trim())) .fetch_optional(&state.db) .await? .ok_or(ApiError::NotFound("invitation"))?; Ok(Json(json!({ "inviter_name": l.inviter, "message": l.message, "status": status(l.accepted_at, l.revoked_at, l.expires_at), "expires_at": rfc3339(l.expires_at), }))) } #[derive(Deserialize)] pub struct TokenQuery { token: String, } /// "No more invitations": from the page behind the footer link, or straight /// from the mail client's unsubscribe button (RFC 8058 one-click POST). pub async fn unsubscribe( State(state): St, WithRejection(Query(q), _): WithRejection, ApiError>, ) -> ApiResult> { let mut tx = state.db.begin().await?; // The link of a site invitation, of a "how compatible are we?" one a user // had us e-mail, or of the waitlist confirmation. let email: Option = sqlx::query_scalar( "SELECT i.email FROM invitation_tokens t JOIN invitations i ON i.id = t.invitation_id WHERE t.token_hash = $1 \ UNION ALL SELECT invitee_email FROM synastry_invites WHERE token_hash = $1 AND invitee_email IS NOT NULL \ UNION ALL SELECT email FROM waitlist WHERE token_hash = $1 \ LIMIT 1", ) .bind(db::token_hash(q.token.trim())) .fetch_optional(&mut *tx) .await?; let email = email.ok_or(ApiError::NotFound("invitation"))?; sqlx::query("INSERT INTO email_optouts (email_hash) VALUES ($1) ON CONFLICT DO NOTHING") .bind(db::token_hash(&email)) .execute(&mut *tx) .await?; sqlx::query( "UPDATE invitations SET revoked_at = now() WHERE email = $1 AND accepted_at IS NULL AND revoked_at IS NULL", ) .bind(&email) .execute(&mut *tx) .await?; sqlx::query("DELETE FROM waitlist WHERE email = $1").bind(&email).execute(&mut *tx).await?; tx.commit().await?; Ok(Json(json!({ "unsubscribed": true }))) } #[derive(Deserialize)] #[serde(deny_unknown_fields)] pub struct WaitlistRequest { email: String, locale: Option, } /// Joins the waitlist. Always answers the same, so it does not reveal who has an account. pub async fn join_waitlist( State(state): St, headers: axum::http::HeaderMap, WithRejection(Json(req), _): Body, ) -> ApiResult<(StatusCode, Json)> { let email = normalize_email(&req.email)?; let locale = validate_locale(&state, req.locale.as_deref())?; // Every sign-up sends an e-mail: a few per address, so the form cannot be used to flood someone. let ip = headers .get("x-forwarded-for") .and_then(|v| v.to_str().ok()) .and_then(|v| v.split(',').next()) .map(str::trim) .unwrap_or("unknown"); let key = format!("waitlist:{ip}"); state.login_limiter.check(&key)?; let token = db::new_token(); let mut tx = state.db.begin().await?; let added = sqlx::query( "INSERT INTO waitlist (email, locale, token_hash) SELECT $1, $2, $3 \ WHERE NOT EXISTS (SELECT 1 FROM users WHERE email = $1) \ AND (SELECT count(*) FROM waitlist) < 10000 \ ON CONFLICT DO NOTHING", ) .bind(&email) .bind(&locale) .bind(db::token_hash(&token)) .execute(&mut *tx) .await? .rows_affected() == 1; // A confirmation, once, unless the address asked for no more mail from us. if added && !opted_out(&mut tx, &email).await? { let (_, unsubscribe_url, unsubscribe_post_url) = links(&state, &token); let payload = json!({ "url": state.config.public_base_url, "unsubscribe_url": unsubscribe_url, "unsubscribe_post_url": unsubscribe_post_url, }); queue_email_to(&mut tx, None, &email, "waitlist_joined", &locale, payload).await?; state.login_limiter.failed(&key); } tx.commit().await?; Ok((StatusCode::ACCEPTED, Json(json!({ "ok": true })))) }