Inviting shown but off until launch; waitlist confirmation; waitlist invites with a package
USER_INVITES (default false) keeps users from inviting others until the launch: the 'Meghívom' option and a 'Hívd meg, akit szeretsz' card on the persons page are shown, disabled, with 'Hamarosan'; the backend refuses with invites_disabled (admins may always). Joining the waitlist sends one confirmation e-mail (waitlist_joined) with a link that takes the address off the list and opts it out; at most 10 per address in 15 minutes. Admins can pick a package for waitlist invitations, like on the invitation form. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> Claude-Session: https://claude.ai/code/session_012vLHzh5qUhFtmJhzkcTbXL
This commit is contained in:
@@ -45,6 +45,10 @@ pub struct Config {
|
||||
/// `MOCK_PAYMENTS` (default `false`): a stand-in payment that adds an
|
||||
/// analysis unit at once, until Stripe is connected.
|
||||
pub mock_payments: bool,
|
||||
/// `USER_INVITES` (default `false`): users may invite others ("how
|
||||
/// compatible are we?" links, which also let the invitee sign up). Off
|
||||
/// until the launch; admins may always.
|
||||
pub user_invites: bool,
|
||||
/// `GOOGLE_CLIENT_IDS`: comma-separated OAuth client ids accepted as the
|
||||
/// ID token audience; empty disables Google login.
|
||||
pub google_client_ids: Vec<String>,
|
||||
@@ -119,6 +123,7 @@ impl Config {
|
||||
session_ttl_days: parsed("SESSION_TTL_DAYS", 30)?,
|
||||
password_login: parsed("PASSWORD_LOGIN", false)?,
|
||||
mock_payments: parsed("MOCK_PAYMENTS", false)?,
|
||||
user_invites: parsed("USER_INVITES", false)?,
|
||||
google_client_ids: list("GOOGLE_CLIENT_IDS"),
|
||||
google_jwks_url: var("GOOGLE_JWKS_URL")
|
||||
.unwrap_or_else(|| "https://www.googleapis.com/oauth2/v3/certs".into()),
|
||||
@@ -156,6 +161,7 @@ impl Config {
|
||||
session_ttl_days: 30,
|
||||
password_login: true,
|
||||
mock_payments: true,
|
||||
user_invites: true,
|
||||
google_client_ids: vec!["test-client.apps.googleusercontent.com".into()],
|
||||
google_jwks_url,
|
||||
bootstrap_admin_emails: vec!["admin@example.com".into()],
|
||||
|
||||
@@ -587,10 +587,12 @@ pub async fn unsubscribe(
|
||||
WithRejection(Query(q), _): WithRejection<Query<TokenQuery>, ApiError>,
|
||||
) -> ApiResult<Json<Value>> {
|
||||
let mut tx = state.db.begin().await?;
|
||||
// The link of a site invitation, or of a "how compatible are we?" one a user had us e-mail.
|
||||
// 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<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 \
|
||||
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()))
|
||||
@@ -607,6 +609,7 @@ pub async fn unsubscribe(
|
||||
.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 })))
|
||||
}
|
||||
@@ -621,19 +624,46 @@ pub struct WaitlistRequest {
|
||||
/// 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<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 \
|
||||
// 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)
|
||||
.execute(&state.db)
|
||||
.await?;
|
||||
.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 }))))
|
||||
}
|
||||
|
||||
@@ -162,6 +162,7 @@ async fn public_config(State(state): St) -> Json<Value> {
|
||||
"locales": c.supported_locales,
|
||||
"password_login": c.password_login,
|
||||
"mock_payments": c.mock_payments,
|
||||
"user_invites": c.user_invites,
|
||||
"signup_mode": c.signup_mode.as_str(),
|
||||
"password_min_length": crate::auth::MIN_PASSWORD_LEN,
|
||||
}))
|
||||
|
||||
@@ -260,6 +260,9 @@ pub async fn create_invite(
|
||||
auth: AuthUser,
|
||||
WithRejection(Json(req), _): Body<CreateInvite>,
|
||||
) -> ApiResult<(StatusCode, Json<Value>)> {
|
||||
if !state.config.user_invites && !auth.user.has_role(db::Role::Admin) {
|
||||
return Err(ApiError::conflict("invites_disabled", "A meghívás hamarosan indul."));
|
||||
}
|
||||
let chart = chart_or_primary(&state.db, req.chart_id, auth.id()).await?;
|
||||
// No links: the message may go out in an e-mail from our domain.
|
||||
let message = super::invitations::clean_message(req.message)?;
|
||||
|
||||
@@ -2056,3 +2056,84 @@ async fn an_invitation_brings_its_package_and_codes_fill_up(pool: PgPool) {
|
||||
(Some(2), Some(1), Some(5))
|
||||
);
|
||||
}
|
||||
|
||||
#[sqlx::test(migrator = "db::MIGRATOR")]
|
||||
async fn the_waitlist_confirms_and_can_be_left(pool: PgPool) {
|
||||
let app = TestApp::with_config(pool.clone(), |c| c.signup_mode = crate::config::SignupMode::Invite).await;
|
||||
let admin = app.register("admin@example.com", "Admin").await;
|
||||
let from = |ip: &'static str| [("x-forwarded-for", ip)];
|
||||
|
||||
// one confirmation per address, even when sent again
|
||||
for _ in 0..2 {
|
||||
let r = app
|
||||
.call_with(
|
||||
"POST",
|
||||
"/v1/public/waitlist",
|
||||
None,
|
||||
Some(json!({"email": "Wait@Example.com"})),
|
||||
&from("198.51.100.7"),
|
||||
)
|
||||
.await;
|
||||
assert_eq!(r.status, StatusCode::ACCEPTED);
|
||||
}
|
||||
let mails: Vec<(Value,)> = sqlx::query_as(
|
||||
"SELECT payload FROM email_outbox WHERE to_email = 'wait@example.com' AND template = 'waitlist_joined'",
|
||||
)
|
||||
.fetch_all(&pool)
|
||||
.await
|
||||
.unwrap();
|
||||
assert_eq!(mails.len(), 1);
|
||||
let leave = mails[0].0["unsubscribe_post_url"].as_str().unwrap().to_string();
|
||||
let token = leave.rsplit("token=").next().unwrap().to_string();
|
||||
|
||||
// leaving: off the list, and no invitation can be sent there any more
|
||||
let r = app.call("POST", &format!("/v1/public/invitations/unsubscribe?token={token}"), None, None).await;
|
||||
assert_eq!(r.status, StatusCode::OK, "{}", r.body);
|
||||
assert!(app.get("/v1/admin/invitations", Some(&admin)).await.body["waitlist"].as_array().unwrap().is_empty());
|
||||
let r = app.post("/v1/admin/invitations", Some(&admin), json!({"emails": ["wait@example.com"]})).await;
|
||||
assert_eq!(r.body["results"][0]["status"], "opted_out");
|
||||
// and signing up again sends nothing
|
||||
app.call_with(
|
||||
"POST",
|
||||
"/v1/public/waitlist",
|
||||
None,
|
||||
Some(json!({"email": "wait@example.com"})),
|
||||
&from("198.51.100.8"),
|
||||
)
|
||||
.await;
|
||||
let count: i64 = sqlx::query_scalar("SELECT count(*) FROM email_outbox WHERE to_email = 'wait@example.com'")
|
||||
.fetch_one(&pool)
|
||||
.await
|
||||
.unwrap();
|
||||
assert_eq!(count, 1);
|
||||
|
||||
// one address cannot flood the form
|
||||
let mut last = StatusCode::OK;
|
||||
for i in 0..12 {
|
||||
let r = app
|
||||
.call_with(
|
||||
"POST",
|
||||
"/v1/public/waitlist",
|
||||
None,
|
||||
Some(json!({"email": format!("w{i}@example.com")})),
|
||||
&from("203.0.113.9"),
|
||||
)
|
||||
.await;
|
||||
last = r.status;
|
||||
}
|
||||
assert_eq!(last, StatusCode::TOO_MANY_REQUESTS);
|
||||
}
|
||||
|
||||
#[sqlx::test(migrator = "db::MIGRATOR")]
|
||||
async fn user_invitations_wait_for_the_launch(pool: PgPool) {
|
||||
let app = TestApp::with_config(pool, |c| c.user_invites = false).await;
|
||||
assert_eq!(app.get("/v1/config", None).await.body["user_invites"], false);
|
||||
let anna = app.register("anna@example.com", "Anna").await;
|
||||
app.chart(&anna, "Saját", true, "1990-03-15").await;
|
||||
let r = app.post("/v1/invites", Some(&anna), json!({"label": "Béla"})).await;
|
||||
assert_eq!((r.status, r.body["error"]["code"].as_str()), (StatusCode::CONFLICT, Some("invites_disabled")));
|
||||
// admins may, to try it
|
||||
let admin = app.register("admin@example.com", "Admin").await;
|
||||
app.chart(&admin, "Saját", true, "1980-01-01").await;
|
||||
assert_eq!(app.post("/v1/invites", Some(&admin), json!({})).await.status, StatusCode::CREATED);
|
||||
}
|
||||
|
||||
@@ -403,13 +403,15 @@ function InvitationRow({ invitation: i, onChange }: { invitation: AdminInvitatio
|
||||
function WaitlistTable({ waitlist, onChange }: { waitlist: WaitlistEntry[]; onChange: () => Promise<void> }) {
|
||||
const [busy, setBusy] = useState<string | null>(null);
|
||||
const [note, setNote] = useState<string | null>(null);
|
||||
const [pkg, setPkg] = useState("");
|
||||
const packages = usePackages();
|
||||
|
||||
async function invite(w: WaitlistEntry) {
|
||||
setBusy(w.email);
|
||||
setNote(null);
|
||||
try {
|
||||
const res = await api<{ results: InvitationResult[] }>("/admin/invitations", {
|
||||
body: { emails: [w.email], locale: w.locale },
|
||||
body: { emails: [w.email], locale: w.locale, package: pkg || null },
|
||||
});
|
||||
const r = res.results[0];
|
||||
if (r && r.status !== "invited") setNote(`${r.email}: ${RESULT[r.status]}`);
|
||||
@@ -440,6 +442,20 @@ function WaitlistTable({ waitlist, onChange }: { waitlist: WaitlistEntry[]; onCh
|
||||
Várólista
|
||||
</h2>
|
||||
<p className="hint">Akik meghívó nélkül próbáltak belépni, és kérték, hogy szóljunk nekik.</p>
|
||||
{waitlist.some((w) => w.invitation === null) && (
|
||||
<div className="field" style={{ maxWidth: 320 }}>
|
||||
<label htmlFor="waitlist-package">Ajándék csomag a meghívottaknak</label>
|
||||
<select id="waitlist-package" className="inp" value={pkg} onChange={(e) => setPkg(e.target.value)}>
|
||||
<option value="">nincs</option>
|
||||
{(packages ?? []).map((p) => (
|
||||
<option key={p.id} value={p.id}>
|
||||
{p.name}
|
||||
</option>
|
||||
))}
|
||||
</select>
|
||||
<span className="hint">A „Meghívás” gomb ezzel a csomaggal küldi a meghívót; a regisztrációkor magától jóváíródik.</span>
|
||||
</div>
|
||||
)}
|
||||
{note && (
|
||||
<p className="msg msg-error" role="alert">
|
||||
{note}
|
||||
|
||||
@@ -909,3 +909,8 @@ a.pair-row:hover strong { color: var(--gold); }
|
||||
.lp-wheel .w-aspect { stroke-dashoffset: 0; }
|
||||
.lp-wheel .w-aspect.w-asp-sextile { opacity: 1; }
|
||||
}
|
||||
|
||||
.mode-option:disabled { cursor: not-allowed; opacity: 0.75; }
|
||||
.mode-option:disabled:hover { border-color: var(--line-2); }
|
||||
.mode-soon { margin-left: 8px; vertical-align: middle; font-family: var(--font-body); font-size: 11px; }
|
||||
.invite-soon .btn:disabled { cursor: not-allowed; }
|
||||
|
||||
@@ -20,7 +20,7 @@ export function Unsubscribe({ token }: { token: string | null }) {
|
||||
if (state === "done") {
|
||||
return (
|
||||
<p className="msg msg-ok" role="status">
|
||||
Leiratkoztál: erre a címre nem küldünk több meghívót.
|
||||
Leiratkoztál: erre a címre nem küldünk több meghívót, és levettük a várólistáról.
|
||||
</p>
|
||||
);
|
||||
}
|
||||
@@ -40,7 +40,8 @@ export function Unsubscribe({ token }: { token: string | null }) {
|
||||
return (
|
||||
<div className="card field" style={{ gap: 12 }}>
|
||||
<p style={{ margin: 0 }}>
|
||||
Ha leiratkozol, erre az e-mail-címre többé nem küldünk meghívót, és a mostani meghívód is érvényét veszti.
|
||||
Ha leiratkozol, erre az e-mail-címre többé nem küldünk meghívót, levesszük a várólistáról, és a mostani meghívód
|
||||
is érvényét veszti.
|
||||
</p>
|
||||
<div>
|
||||
<button type="button" className="btn btn-primary" onClick={confirm} disabled={state === "busy"}>
|
||||
|
||||
@@ -12,7 +12,7 @@ export default async function UnsubscribePage({ searchParams }: { searchParams:
|
||||
<main className="page" style={{ maxWidth: 560 }}>
|
||||
<div className="page-head">
|
||||
<h1>Leiratkozás</h1>
|
||||
<p className="muted">Nem kérsz több meghívót a Sorsfonalakra.</p>
|
||||
<p className="muted">Nem kérsz több levelet és meghívót a Sorsfonalakról.</p>
|
||||
</div>
|
||||
<Unsubscribe token={token ?? null} />
|
||||
</main>
|
||||
|
||||
@@ -23,6 +23,7 @@ export default async function PersonsPage() {
|
||||
const isAdmin = me.user.roles.includes("admin");
|
||||
const slots = me.persons;
|
||||
const full = slots.left === 0;
|
||||
const invitesOpen = (config?.user_invites ?? false) || isAdmin;
|
||||
const now = Date.now();
|
||||
|
||||
return (
|
||||
@@ -47,22 +48,46 @@ export default async function PersonsPage() {
|
||||
</ChartCard>
|
||||
))}
|
||||
|
||||
<Link href="/szemelyek/uj" className="chart-card chart-card-new">
|
||||
<span className="chart-card-plus" aria-hidden="true">
|
||||
+
|
||||
</span>
|
||||
<strong className="chart-card-name">Új személy</strong>
|
||||
<span className="muted">
|
||||
{full
|
||||
? "Meghívással bármikor"
|
||||
: slots.unlimited
|
||||
? "Adatokkal vagy meghívással"
|
||||
: `Még ${slots.left} személyt vehetsz fel, vagy hívd meg`}
|
||||
</span>
|
||||
</Link>
|
||||
{(!full || invitesOpen) && (
|
||||
<Link href="/szemelyek/uj" className="chart-card chart-card-new">
|
||||
<span className="chart-card-plus" aria-hidden="true">
|
||||
+
|
||||
</span>
|
||||
<strong className="chart-card-name">Új személy</strong>
|
||||
<span className="muted">
|
||||
{!invitesOpen
|
||||
? slots.unlimited
|
||||
? "Korlátlan számú személy"
|
||||
: `Még ${slots.left} személyt vehetsz fel`
|
||||
: full
|
||||
? "Meghívással bármikor"
|
||||
: slots.unlimited
|
||||
? "Adatokkal vagy meghívással"
|
||||
: `Még ${slots.left} személyt vehetsz fel, vagy hívd meg`}
|
||||
</span>
|
||||
</Link>
|
||||
)}
|
||||
</div>
|
||||
|
||||
<PendingInvites />
|
||||
{invitesOpen ? (
|
||||
<PendingInvites />
|
||||
) : (
|
||||
<section className="card invite-soon" aria-labelledby="invite-soon-title">
|
||||
<div className="card-head">
|
||||
<h2 id="invite-soon-title">Hívd meg, akit szeretsz</h2>
|
||||
<span className="badge">Hamarosan</span>
|
||||
</div>
|
||||
<p className="muted">
|
||||
Hamarosan te is meghívhatod a barátaidat, a családodat vagy a párodat: ők megadják a saját születési adataikat,
|
||||
ingyen megkapják a képletüket, és együtt megnézitek, mennyire illetek össze.
|
||||
</p>
|
||||
<div>
|
||||
<button type="button" className="btn" disabled>
|
||||
Meghívó küldése
|
||||
</button>
|
||||
</div>
|
||||
</section>
|
||||
)}
|
||||
|
||||
{!slots.unlimited && (
|
||||
<section className="card" aria-labelledby="slots-title">
|
||||
|
||||
@@ -14,16 +14,19 @@ import { NewPerson } from "./NewPerson";
|
||||
export function NewPersonChooser({
|
||||
canAdd,
|
||||
hasOwnChart,
|
||||
invitesOpen,
|
||||
full,
|
||||
}: {
|
||||
/** A slot is free for typed-in data. */
|
||||
canAdd: boolean;
|
||||
/** Inviting is on (until the launch it is shown, but off). */
|
||||
invitesOpen: boolean;
|
||||
/** Inviting compares with the user's own chart. */
|
||||
hasOwnChart: boolean;
|
||||
/** Shown instead of the form when no slot is left. */
|
||||
full: React.ReactNode;
|
||||
}) {
|
||||
const [mode, setMode] = useState<"data" | "invite">(canAdd ? "data" : "invite");
|
||||
const [mode, setMode] = useState<"data" | "invite">(canAdd || !invitesOpen ? "data" : "invite");
|
||||
return (
|
||||
<div className="field" style={{ gap: 18 }}>
|
||||
<div className="mode-switch" role="tablist" aria-label="Hogyan veszed fel?">
|
||||
@@ -41,11 +44,19 @@ export function NewPersonChooser({
|
||||
type="button"
|
||||
role="tab"
|
||||
aria-selected={mode === "invite"}
|
||||
aria-disabled={!invitesOpen}
|
||||
disabled={!invitesOpen}
|
||||
className="mode-option"
|
||||
onClick={() => setMode("invite")}
|
||||
>
|
||||
<strong>Meghívom</strong>
|
||||
<span>Ő adja meg a saját adatait, és megnézitek, mennyire illetek össze. Ingyenes, nem kell hozzá hely.</span>
|
||||
<strong>
|
||||
Meghívom {!invitesOpen && <span className="badge mode-soon">Hamarosan</span>}
|
||||
</strong>
|
||||
<span>
|
||||
{invitesOpen
|
||||
? "Ő adja meg a saját adatait, és megnézitek, mennyire illetek össze. Ingyenes, nem kell hozzá hely."
|
||||
: "Hamarosan meghívhatod azokat, akiket szeretsz: ők adják meg a saját adataikat, és együtt nézitek meg, mennyire illetek össze."}
|
||||
</span>
|
||||
</button>
|
||||
</div>
|
||||
{mode === "data" ? (
|
||||
|
||||
@@ -27,6 +27,7 @@ export default async function NewPersonPage() {
|
||||
<NewPersonChooser
|
||||
canAdd={slots.left !== 0}
|
||||
hasOwnChart={me.primary_chart_id !== null}
|
||||
invitesOpen={(config?.user_invites ?? false) || me.user.roles.includes("admin")}
|
||||
full={
|
||||
<>
|
||||
<p className="muted">Elfogytak a helyeid. Újabb személyhez válassz csomagot, vagy hívd meg.</p>
|
||||
|
||||
@@ -92,6 +92,8 @@ export interface PublicConfig {
|
||||
mock_payments: boolean;
|
||||
/** "invite": new accounts need an invitation. */
|
||||
signup_mode: "invite" | "open";
|
||||
/** Users may invite others (off until the launch; admins always may). */
|
||||
user_invites: boolean;
|
||||
}
|
||||
|
||||
export interface Position {
|
||||
|
||||
Reference in New Issue
Block a user