Invitation-only sign-up, invitation e-mails and waitlist

- SIGNUP_MODE=invite (default): a new account needs an open invitation for
  its address, or the invitation link (then any Google account will do)
- admin page "Meghívók": invite many addresses at once, personal message,
  resend (max 3, 24 h apart), revoke, copy link, mail preview and test copy,
  waitlist
- invitation e-mail in HTML and plain text; Message-ID on the sender's
  domain, List-Unsubscribe with one-click POST, opt-out list (hashes only)
- e-mail texts moved to a shared crate (crates/email-templates)
- login page shows the invitation; waitlist for uninvited visitors;
  unsubscribe page; privacy policy updated
- docs/levelkuldes.md: Brevo, DNS (SPF, DKIM, DMARC) and the SMTP setup

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-17 18:37:15 +00:00
co-authored by Claude Opus 5.5
parent b53cadcd8c
commit 7272d0f1f3
37 changed files with 2333 additions and 231 deletions
+27
View File
@@ -2,6 +2,24 @@
use anyhow::{Context, bail};
/// Who may create an account.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum SignupMode {
/// Anyone.
Open,
/// Only invited addresses (or the holder of an invitation link).
Invite,
}
impl SignupMode {
pub fn as_str(self) -> &'static str {
match self {
SignupMode::Open => "open",
SignupMode::Invite => "invite",
}
}
}
#[derive(Debug, Clone)]
pub struct Config {
/// `DATABASE_URL` (required).
@@ -51,6 +69,9 @@ pub struct Config {
pub free_person_slots: i64,
/// `UNLIMITED_DAILY_LIMIT` (default 5): new detailed analyses a day with the unlimited package.
pub unlimited_daily_limit: i64,
/// `SIGNUP_MODE` (`invite` or `open`, default `invite`): whether new
/// accounts need an invitation.
pub signup_mode: SignupMode,
}
fn var(name: &str) -> Option<String> {
@@ -106,6 +127,11 @@ impl Config {
max_charts_per_user: parsed("MAX_CHARTS_PER_USER", 1000)?,
free_person_slots: parsed("FREE_PERSON_SLOTS", 0)?,
unlimited_daily_limit: parsed("UNLIMITED_DAILY_LIMIT", 5)?,
signup_mode: match var("SIGNUP_MODE").as_deref() {
None | Some("invite") => SignupMode::Invite,
Some("open") => SignupMode::Open,
Some(other) => bail!("invalid SIGNUP_MODE '{other}': use 'invite' or 'open'"),
},
};
if config.session_ttl_days < 1 {
bail!("SESSION_TTL_DAYS must be at least 1");
@@ -136,6 +162,7 @@ impl Config {
max_charts_per_user: 50,
free_person_slots: 5,
unlimited_daily_limit: 3,
signup_mode: SignupMode::Open,
}
}
}
+4
View File
@@ -16,6 +16,9 @@ pub enum ApiError {
InvalidCredentials(String),
#[error("{0}")]
Forbidden(String),
/// Refused, with a code the frontend acts on (e.g. `not_invited`).
#[error("{message}")]
Refused { code: &'static str, message: String },
#[error("{0} not found")]
NotFound(&'static str),
#[error("{message}")]
@@ -51,6 +54,7 @@ impl ApiError {
ApiError::Unauthorized => (StatusCode::UNAUTHORIZED, "unauthorized"),
ApiError::InvalidCredentials(_) => (StatusCode::UNAUTHORIZED, "invalid_credentials"),
ApiError::Forbidden(_) => (StatusCode::FORBIDDEN, "forbidden"),
ApiError::Refused { code, .. } => (StatusCode::FORBIDDEN, code),
ApiError::NotFound(_) => (StatusCode::NOT_FOUND, "not_found"),
ApiError::Conflict { code, .. } => (StatusCode::CONFLICT, code),
ApiError::Gone(_) => (StatusCode::GONE, "gone"),
+24 -4
View File
@@ -113,16 +113,28 @@ async fn consume_token(conn: &mut PgConnection, token: &str, purpose: &str) -> R
row.map(|(id,)| id).ok_or(ApiError::InvalidToken)
}
/// Queues an e-mail for the worker.
/// Queues an e-mail to a user for the worker.
pub async fn queue_email(conn: &mut PgConnection, user: &User, template: &str, payload: Value) -> Result<(), ApiError> {
queue_email_to(conn, Some(user.id), &user.email, template, &user.locale, payload).await
}
/// Queues an e-mail to any address (e.g. an invitation) for the worker.
pub async fn queue_email_to(
conn: &mut PgConnection,
user_id: Option<Uuid>,
to: &str,
template: &str,
locale: &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(user_id)
.bind(to)
.bind(template)
.bind(&user.locale)
.bind(locale)
.bind(payload)
.execute(conn)
.await?;
@@ -156,6 +168,8 @@ pub struct RegisterRequest {
password: String,
display_name: Option<String>,
locale: Option<String>,
/// The invitation link's token, while sign-up needs an invitation.
invite_token: Option<String>,
}
/// Password endpoints answer 403 while `PASSWORD_LOGIN` is off.
@@ -185,6 +199,7 @@ pub async fn register(
if exists.is_some() {
return Err(ApiError::conflict("email_taken", "an account with this e-mail address already exists"));
}
super::invitations::admit(&state, &mut tx, &email, req.invite_token.as_deref()).await?;
let user_id = Uuid::now_v7();
sqlx::query("INSERT INTO users (id, email, display_name, locale) VALUES ($1, $2, $3, $4)")
.bind(user_id)
@@ -201,6 +216,7 @@ pub async fn register(
.bind(&email)
.execute(&mut *tx)
.await?;
super::invitations::mark_accepted(&mut tx, user_id, &email, req.invite_token.as_deref()).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?;
@@ -266,6 +282,8 @@ pub async fn login(
pub struct GoogleRequest {
/// ID token (JWT) from Google Identity Services.
id_token: String,
/// The invitation link's token, while sign-up needs an invitation.
invite_token: Option<String>,
}
/// Logs in with Google. An unknown Google account is linked to the existing
@@ -311,6 +329,7 @@ pub async fn google(
(id, false)
}
None => {
super::invitations::admit(&state, &mut tx, &email, req.invite_token.as_deref()).await?;
let id = Uuid::now_v7();
let locale = claims
.locale
@@ -328,6 +347,7 @@ pub async fn google(
.bind(locale)
.execute(&mut *tx)
.await?;
super::invitations::mark_accepted(&mut tx, id, &email, req.invite_token.as_deref()).await?;
(id, true)
}
};
+547
View File
@@ -0,0 +1,547 @@
//! 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.
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::views::{rfc3339, rfc3339_opt};
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, and it leaves the waitlist.
pub async fn mark_accepted(
conn: &mut PgConnection,
user_id: Uuid,
email: &str,
token: Option<&str>,
) -> 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?;
Ok(())
}
// --- sending ---------------------------------------------------------------------------------
fn clean_message(message: Option<String>) -> Result<Option<String>, 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))
}
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,
) -> Value {
let (url, unsubscribe_url, unsubscribe_post_url) = links(state, token);
json!({
"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,
) -> Result<String, ApiError> {
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);
let url = payload["url"].as_str().unwrap_or_default().to_owned();
queue_email_to(conn, None, email, "invitation", locale, payload).await?;
Ok(url)
}
async fn opted_out(conn: &mut PgConnection, email: &str) -> Result<bool, ApiError> {
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<String>,
message: Option<String>,
locale: Option<String>,
}
/// 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<CreateInvitations>,
) -> ApiResult<(StatusCode, Json<Value>)> {
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 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 url = send(&state, &mut tx, id, &email, &locale, inviter.as_deref(), message.as_deref(), expires).await?;
results.push(json!({ "email": email, "status": "invited", "id": id, "url": url }));
}
tx.commit().await?;
Ok((StatusCode::CREATED, Json(json!({ "results": results }))))
}
#[derive(sqlx::FromRow)]
struct Row {
id: Uuid,
email: String,
message: Option<String>,
locale: String,
created_at: OffsetDateTime,
expires_at: OffsetDateTime,
sent_count: i32,
last_sent_at: OffsetDateTime,
accepted_at: Option<OffsetDateTime>,
revoked_at: Option<OffsetDateTime>,
invited_by_name: Option<String>,
accepted_by_name: Option<String>,
mail_created_at: Option<OffsetDateTime>,
mail_sent_at: Option<OffsetDateTime>,
mail_failed_at: Option<OffsetDateTime>,
mail_error: Option<String>,
}
fn status(accepted: Option<OffsetDateTime>, revoked: Option<OffsetDateTime>, 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<Json<Value>> {
let rows: Vec<Row> = 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 \
FROM invitations i \
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<Value> = 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,
})
})
.collect();
let waitlist: Vec<(String, String, OffsetDateTime, Option<String>)> = 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<Value> = 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<Json<Value>> {
let mut tx = state.db.begin().await?;
#[derive(sqlx::FromRow)]
struct Open {
email: String,
message: Option<String>,
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 url = send(&state, &mut tx, id, &email, &locale, inviter.as_deref(), message.as_deref(), expires).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<StatusCode> {
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(&state.db)
.await?
.rows_affected();
if done == 0 {
return Err(ApiError::NotFound("open invitation"));
}
Ok(StatusCode::NO_CONTENT)
}
pub async fn remove_from_waitlist(
State(state): St,
_admin: AdminUser,
WithRejection(Path(email), _): WithRejection<Path<String>, ApiError>,
) -> ApiResult<StatusCode> {
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<String>,
locale: Option<String>,
/// Also send it to the admin's own address.
#[serde(default)]
send_to_me: bool,
}
/// 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<PreviewRequest>,
) -> ApiResult<Json<Value>> {
let message = clean_message(req.message)?;
let locale = validate_locale(&state, req.locale.as_deref())?;
let payload = payload(
&state,
"minta",
admin.user.display_name.as_deref(),
message.as_deref(),
OffsetDateTime::now_utc() + INVITATION_TTL,
);
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<String>) -> ApiResult<Json<Value>> {
#[derive(sqlx::FromRow)]
struct Landing {
inviter: Option<String>,
message: Option<String>,
expires_at: OffsetDateTime,
accepted_at: Option<OffsetDateTime>,
revoked_at: Option<OffsetDateTime>,
}
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<Query<TokenQuery>, ApiError>,
) -> ApiResult<Json<Value>> {
let mut tx = state.db.begin().await?;
let email: Option<String> = sqlx::query_scalar(
"SELECT i.email FROM invitation_tokens t JOIN invitations i ON i.id = t.invitation_id WHERE t.token_hash = $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?;
tx.commit().await?;
Ok(Json(json!({ "unsubscribed": true })))
}
#[derive(Deserialize)]
#[serde(deny_unknown_fields)]
pub struct WaitlistRequest {
email: String,
locale: Option<String>,
}
/// Joins the waitlist. Always answers the same, so it does not reveal who has an account.
pub async fn join_waitlist(
State(state): St,
WithRejection(Json(req), _): Body<WaitlistRequest>,
) -> ApiResult<(StatusCode, Json<Value>)> {
let email = normalize_email(&req.email)?;
let locale = validate_locale(&state, req.locale.as_deref())?;
sqlx::query(
"INSERT INTO waitlist (email, locale) SELECT $1, $2 \
WHERE NOT EXISTS (SELECT 1 FROM users WHERE email = $1) \
AND (SELECT count(*) FROM waitlist) < 10000 \
ON CONFLICT DO NOTHING",
)
.bind(&email)
.bind(&locale)
.execute(&state.db)
.await?;
Ok((StatusCode::ACCEPTED, Json(json!({ "ok": true }))))
}
+10
View File
@@ -10,6 +10,7 @@ mod admin;
mod analyses;
mod auth;
mod charts;
mod invitations;
mod payments;
mod prompts;
mod shares;
@@ -87,11 +88,19 @@ pub fn router(state: Arc<AppState>) -> Router {
// public, no login
.route("/v1/public/shares/{slug}", get(shares::public_view))
.route("/v1/public/invites/{token}", get(synastries::public_invite))
.route("/v1/public/invitations/unsubscribe", post(invitations::unsubscribe))
.route("/v1/public/invitations/{token}", get(invitations::public_view))
.route("/v1/public/waitlist", post(invitations::join_waitlist))
// 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))
.route("/v1/admin/users/{id}/packages", post(admin::grant_package))
.route("/v1/admin/invitations", get(invitations::list).post(invitations::create))
.route("/v1/admin/invitations/preview", post(invitations::preview))
.route("/v1/admin/invitations/{id}", delete(invitations::revoke))
.route("/v1/admin/invitations/{id}/resend", post(invitations::resend))
.route("/v1/admin/waitlist/{email}", delete(invitations::remove_from_waitlist))
.route("/v1/admin/prompts", get(prompts::list))
.route("/v1/admin/prompts/{kind}/{language}", axum::routing::put(prompts::save))
.route("/v1/admin/prompts/{kind}/{language}/preview", post(prompts::start_preview))
@@ -130,6 +139,7 @@ async fn public_config(State(state): St) -> Json<Value> {
"password_login": c.password_login,
"mock_payments": c.mock_payments,
"unlimited_daily_limit": c.unlimited_daily_limit,
"signup_mode": c.signup_mode.as_str(),
"password_min_length": crate::auth::MIN_PASSWORD_LEN,
}))
}
+134
View File
@@ -1112,3 +1112,137 @@ async fn renaming_a_person_keeps_chart_and_analyses(pool: PgPool) {
let r = app.call("PATCH", &format!("/v1/charts/{id}"), Some(&anna), Some(same)).await;
assert_eq!(r.status, StatusCode::OK, "{}", r.body);
}
async fn google_signup(app: &TestApp, sub: &str, email: &str, invite: Option<&str>) -> Response {
app.post(
"/v1/auth/google",
None,
json!({"id_token": google_token(sub, email, GOOGLE_CLIENT), "invite_token": invite}),
)
.await
}
fn invite_token(url: &str) -> String {
url.rsplit('/').next().unwrap().to_string()
}
#[sqlx::test(migrator = "db::MIGRATOR")]
async fn invitation_only_signup(pool: PgPool) {
let app = TestApp::with_config(pool.clone(), |c| c.signup_mode = crate::config::SignupMode::Invite).await;
assert_eq!(app.get("/v1/config", None).await.body["signup_mode"], "invite");
// nobody gets in uninvited, except the bootstrap admin
let r = google_signup(&app, "g-x", "stranger@gmail.com", None).await;
assert_eq!((r.status, r.body["error"]["code"].as_str()), (StatusCode::FORBIDDEN, Some("not_invited")));
let admin = app.register("admin@example.com", "Admin").await;
// an existing user (from before the invitation-only times) is not an admin
let user = {
let open = TestApp::new(pool.clone()).await;
open.register("anna@example.com", "Anna").await
};
// inviting: duplicates, invalid addresses and existing users are sorted out
let r = app
.post(
"/v1/admin/invitations",
Some(&admin),
json!({"emails": ["Guest@Example.com", "guest@example.com", "nope", "anna@example.com", "kata@example.com"],
"message": "Gyere, nézd meg!"}),
)
.await;
assert_eq!(r.status, StatusCode::CREATED, "{}", r.body);
let statuses: Vec<&str> =
r.body["results"].as_array().unwrap().iter().map(|x| x["status"].as_str().unwrap()).collect();
assert_eq!(statuses, ["invited", "invalid", "already_user", "invited"]);
let guest_url = r.body["results"][0]["url"].as_str().unwrap().to_string();
let guest_id = r.body["results"][0]["id"].as_str().unwrap().to_string();
let guest_token = invite_token(&guest_url);
let r = app.post("/v1/admin/invitations", Some(&admin), json!({"emails": ["guest@example.com"]})).await;
assert_eq!(r.body["results"][0]["status"], "already_invited");
let r = app
.post(
"/v1/admin/invitations",
Some(&admin),
json!({"emails": ["x@example.com"], "message": "nézd: www.spam.hu"}),
)
.await;
assert_eq!(r.status, StatusCode::BAD_REQUEST);
assert_eq!(app.get("/v1/admin/invitations", Some(&user)).await.status, StatusCode::FORBIDDEN);
// the e-mail and the landing page
let (payload,): (Value,) = sqlx::query_as(
"SELECT payload FROM email_outbox WHERE to_email = 'guest@example.com' AND template = 'invitation'",
)
.fetch_one(&pool)
.await
.unwrap();
assert_eq!(payload["url"], guest_url.as_str());
assert_eq!(payload["inviter_name"], "Admin");
assert!(
payload["unsubscribe_post_url"].as_str().unwrap().contains("/api/v1/public/invitations/unsubscribe?token=")
);
let r = app.get(&format!("/v1/public/invitations/{guest_token}"), None).await;
assert_eq!((r.body["inviter_name"].as_str(), r.body["status"].as_str()), (Some("Admin"), Some("pending")));
// a resend: not too soon, then with a new link; the old one keeps working
let r = app.post(&format!("/v1/admin/invitations/{guest_id}/resend"), Some(&admin), json!({})).await;
assert_eq!(r.body["error"]["code"], "resend_too_soon");
sqlx::query("UPDATE invitations SET last_sent_at = now() - interval '25 hours'").execute(&pool).await.unwrap();
let r = app.post(&format!("/v1/admin/invitations/{guest_id}/resend"), Some(&admin), json!({})).await;
assert_eq!(r.status, StatusCode::OK, "{}", r.body);
assert_ne!(r.body["url"], guest_url.as_str());
// the link lets in any Google account, once
let r = google_signup(&app, "g-1", "guests.other.account@gmail.com", Some(&guest_token)).await;
assert_eq!(r.status, StatusCode::CREATED, "{}", r.body);
let r = google_signup(&app, "g-2", "third@gmail.com", Some(&guest_token)).await;
assert_eq!(r.body["error"]["code"], "not_invited");
// the invited address itself gets in without the link
assert_eq!(google_signup(&app, "g-3", "kata@example.com", None).await.status, StatusCode::CREATED);
// revoked: no entry
let r = app
.post("/v1/admin/invitations", Some(&admin), json!({"emails": ["zoli@example.com", "mari@example.com"]}))
.await;
let zoli_id = r.body["results"][0]["id"].as_str().unwrap().to_string();
let mari_token = invite_token(r.body["results"][1]["url"].as_str().unwrap());
assert_eq!(
app.call("DELETE", &format!("/v1/admin/invitations/{zoli_id}"), Some(&admin), None).await.status,
StatusCode::NO_CONTENT
);
assert_eq!(google_signup(&app, "g-4", "zoli@example.com", None).await.status, StatusCode::FORBIDDEN);
// unsubscribing (one-click POST): the invitation closes and no new one can be sent
let r = app.call("POST", &format!("/v1/public/invitations/unsubscribe?token={mari_token}"), None, None).await;
assert_eq!(r.status, StatusCode::OK);
assert_eq!(google_signup(&app, "g-5", "mari@example.com", None).await.status, StatusCode::FORBIDDEN);
let r = app.post("/v1/admin/invitations", Some(&admin), json!({"emails": ["MARI@example.com"]})).await;
assert_eq!(r.body["results"][0]["status"], "opted_out");
// the waitlist: joining reveals nothing, an invited and accepted address leaves it
for email in ["wait@example.com", "anna@example.com"] {
let r = app.post("/v1/public/waitlist", None, json!({"email": email})).await;
assert_eq!(r.status, StatusCode::ACCEPTED);
}
let list = app.get("/v1/admin/invitations", Some(&admin)).await.body;
assert_eq!(list["waitlist"].as_array().unwrap().len(), 1);
let statuses: Vec<(&str, &str)> = list["invitations"]
.as_array()
.unwrap()
.iter()
.map(|i| (i["email"].as_str().unwrap(), i["status"].as_str().unwrap()))
.collect();
assert!(
statuses.contains(&("guest@example.com", "accepted")) && statuses.contains(&("zoli@example.com", "revoked"))
);
app.post("/v1/admin/invitations", Some(&admin), json!({"emails": ["wait@example.com"]})).await;
assert_eq!(google_signup(&app, "g-6", "wait@example.com", None).await.status, StatusCode::CREATED);
assert!(app.get("/v1/admin/invitations", Some(&admin)).await.body["waitlist"].as_array().unwrap().is_empty());
// preview and a test copy to the admin
let r =
app.post("/v1/admin/invitations/preview", Some(&admin), json!({"message": "Szia!", "send_to_me": true})).await;
assert_eq!(r.body["subject"], "Admin meghívott a Sorsfonalakra");
assert!(r.body["html"].as_str().unwrap().contains("Szia!") && r.body["text"].as_str().unwrap().contains("> Szia!"));
assert_eq!(app.outbox_url("admin@example.com", "invitation").await, "https://sorsfonalak.test/meghivo/minta");
}