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);
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user