Cloudflare Turnstile on e-mail sign-up and password reset, and a limit per address
- The sign-up and "forgot password" forms carry a token from Cloudflare Turnstile's widget (managed, shown only when Cloudflare asks for a click); the backend checks it before an e-mail goes out. Off without TURNSTILE_SITE_KEY and TURNSTILE_SECRET_KEY (development); the site key comes to the page through /v1/config. - At most ten such e-mail requests an hour per visitor address, so a script cannot make the site mail thousands of strangers. - The privacy notice (HU, EN) mentions Turnstile with Cloudflare. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> Claude-Session: https://claude.ai/code/session_012vLHzh5qUhFtmJhzkcTbXL
This commit is contained in:
@@ -110,6 +110,9 @@ services:
|
|||||||
S3_ENDPOINT: ${S3_ENDPOINT:-}
|
S3_ENDPOINT: ${S3_ENDPOINT:-}
|
||||||
S3_BUCKET: ${S3_BUCKET:-}
|
S3_BUCKET: ${S3_BUCKET:-}
|
||||||
S3_REGION: ${S3_REGION:-us-east-1}
|
S3_REGION: ${S3_REGION:-us-east-1}
|
||||||
|
# Cloudflare Turnstile on the e-mail sign-up and reset forms (the
|
||||||
|
# TURNSTILE_SECRET_KEY is in .env.secrets). Without both: no check.
|
||||||
|
TURNSTILE_SITE_KEY: ${TURNSTILE_SITE_KEY:-}
|
||||||
# The log also goes to the logs volume, one file a day, kept 30 days
|
# The log also goes to the logs volume, one file a day, kept 30 days
|
||||||
# (deploy/README.md: Logs).
|
# (deploy/README.md: Logs).
|
||||||
LOG_DIR: /logs
|
LOG_DIR: /logs
|
||||||
|
|||||||
@@ -54,6 +54,10 @@ services:
|
|||||||
SUMMARY_MODEL: ${SUMMARY_MODEL:-}
|
SUMMARY_MODEL: ${SUMMARY_MODEL:-}
|
||||||
# E-mail + password login; off by default (Google, Apple and Facebook only).
|
# E-mail + password login; off by default (Google, Apple and Facebook only).
|
||||||
PASSWORD_LOGIN: ${PASSWORD_LOGIN:-false}
|
PASSWORD_LOGIN: ${PASSWORD_LOGIN:-false}
|
||||||
|
# Cloudflare Turnstile (off without both keys; Cloudflare's test keys
|
||||||
|
# 1x00000000000000000000AA / 1x0000000000000000000000000000000AA always pass).
|
||||||
|
TURNSTILE_SITE_KEY: ${TURNSTILE_SITE_KEY:-}
|
||||||
|
TURNSTILE_SECRET_KEY: ${TURNSTILE_SECRET_KEY:-}
|
||||||
# Stand-in payment (adds an analysis unit at once) until Stripe is connected.
|
# Stand-in payment (adds an analysis unit at once) until Stripe is connected.
|
||||||
MOCK_PAYMENTS: ${MOCK_PAYMENTS:-true}
|
MOCK_PAYMENTS: ${MOCK_PAYMENTS:-true}
|
||||||
# Stripe purchases for everyone (false: admins only, until the opening;
|
# Stripe purchases for everyone (false: admins only, until the opening;
|
||||||
|
|||||||
@@ -110,6 +110,10 @@ pub struct Config {
|
|||||||
/// Object storage of the uploaded photos (see [`crate::storage`]); `None`
|
/// Object storage of the uploaded photos (see [`crate::storage`]); `None`
|
||||||
/// when `S3_ENDPOINT` is not set (photo uploads are then refused).
|
/// when `S3_ENDPOINT` is not set (photo uploads are then refused).
|
||||||
pub storage: Option<crate::storage::StorageConfig>,
|
pub storage: Option<crate::storage::StorageConfig>,
|
||||||
|
/// `TURNSTILE_SITE_KEY` and `TURNSTILE_SECRET_KEY`: Cloudflare Turnstile
|
||||||
|
/// on the e-mail sign-up and password reset forms (see [`crate::turnstile`]);
|
||||||
|
/// `None` without both (development): no check.
|
||||||
|
pub turnstile: Option<crate::turnstile::TurnstileConfig>,
|
||||||
/// `S3_CREATE_BUCKET` (default false): create the bucket at startup if it
|
/// `S3_CREATE_BUCKET` (default false): create the bucket at startup if it
|
||||||
/// is missing (development; in production it is made in the console).
|
/// is missing (development; in production it is made in the console).
|
||||||
pub storage_create_bucket: bool,
|
pub storage_create_bucket: bool,
|
||||||
@@ -226,6 +230,14 @@ impl Config {
|
|||||||
Some("open") => SignupMode::Open,
|
Some("open") => SignupMode::Open,
|
||||||
Some(other) => bail!("invalid SIGNUP_MODE '{other}': use 'invite' or 'open'"),
|
Some(other) => bail!("invalid SIGNUP_MODE '{other}': use 'invite' or 'open'"),
|
||||||
},
|
},
|
||||||
|
turnstile: match (var("TURNSTILE_SITE_KEY"), var("TURNSTILE_SECRET_KEY")) {
|
||||||
|
(Some(site_key), Some(secret)) => Some(crate::turnstile::TurnstileConfig {
|
||||||
|
site_key,
|
||||||
|
secret,
|
||||||
|
verify_url: var("TURNSTILE_VERIFY_URL").unwrap_or_else(|| crate::turnstile::VERIFY_URL.to_string()),
|
||||||
|
}),
|
||||||
|
_ => None,
|
||||||
|
},
|
||||||
storage: match var("S3_ENDPOINT") {
|
storage: match var("S3_ENDPOINT") {
|
||||||
None => None,
|
None => None,
|
||||||
Some(endpoint) => Some(crate::storage::StorageConfig {
|
Some(endpoint) => Some(crate::storage::StorageConfig {
|
||||||
@@ -279,6 +291,7 @@ impl Config {
|
|||||||
max_charts_per_user: 50,
|
max_charts_per_user: 50,
|
||||||
free_person_slots: 5,
|
free_person_slots: 5,
|
||||||
signup_mode: SignupMode::Open,
|
signup_mode: SignupMode::Open,
|
||||||
|
turnstile: None,
|
||||||
storage: Some(crate::storage::StorageConfig {
|
storage: Some(crate::storage::StorageConfig {
|
||||||
endpoint: format!("{horoscope_api_url}/s3"),
|
endpoint: format!("{horoscope_api_url}/s3"),
|
||||||
bucket: "photos".into(),
|
bucket: "photos".into(),
|
||||||
|
|||||||
@@ -23,6 +23,7 @@ mod storage;
|
|||||||
mod stripe;
|
mod stripe;
|
||||||
#[cfg(test)]
|
#[cfg(test)]
|
||||||
mod tests;
|
mod tests;
|
||||||
|
mod turnstile;
|
||||||
mod views;
|
mod views;
|
||||||
|
|
||||||
use std::sync::Arc;
|
use std::sync::Arc;
|
||||||
@@ -49,6 +50,9 @@ pub struct AppState {
|
|||||||
pub calculator_limiter: LoginLimiter,
|
pub calculator_limiter: LoginLimiter,
|
||||||
/// The public place search (typing makes several calls), per visitor address.
|
/// The public place search (typing makes several calls), per visitor address.
|
||||||
pub places_limiter: LoginLimiter,
|
pub places_limiter: LoginLimiter,
|
||||||
|
/// E-mail sign-ups and password reset requests, per visitor address (each
|
||||||
|
/// sends an e-mail, so a script must not send thousands).
|
||||||
|
pub signup_limiter: LoginLimiter,
|
||||||
/// Share visits already counted (link and visitor address, for half an hour):
|
/// Share visits already counted (link and visitor address, for half an hour):
|
||||||
/// a reload is not a new visit, without storing anything in the browser.
|
/// a reload is not a new visit, without storing anything in the browser.
|
||||||
pub share_visits: LoginLimiter,
|
pub share_visits: LoginLimiter,
|
||||||
@@ -70,6 +74,7 @@ impl AppState {
|
|||||||
calculator_limiter: LoginLimiter::new(30, Duration::from_secs(60 * 60)),
|
calculator_limiter: LoginLimiter::new(30, Duration::from_secs(60 * 60)),
|
||||||
places_limiter: LoginLimiter::new(300, Duration::from_secs(60 * 60)),
|
places_limiter: LoginLimiter::new(300, Duration::from_secs(60 * 60)),
|
||||||
share_visits: LoginLimiter::new(1, Duration::from_secs(30 * 60)),
|
share_visits: LoginLimiter::new(1, Duration::from_secs(30 * 60)),
|
||||||
|
signup_limiter: LoginLimiter::new(10, Duration::from_secs(60 * 60)),
|
||||||
models: models::Catalog::new(&config.openrouter_models_url),
|
models: models::Catalog::new(&config.openrouter_models_url),
|
||||||
stripe: stripe::Client::default(),
|
stripe: stripe::Client::default(),
|
||||||
storage: config.storage.clone().map(storage::Storage::new),
|
storage: config.storage.clone().map(storage::Storage::new),
|
||||||
|
|||||||
@@ -227,6 +227,19 @@ pub struct RegisterRequest {
|
|||||||
invite_token: Option<String>,
|
invite_token: Option<String>,
|
||||||
/// The slug of the shared link the visitor came from.
|
/// The slug of the shared link the visitor came from.
|
||||||
referral: Option<String>,
|
referral: Option<String>,
|
||||||
|
/// Cloudflare Turnstile's token (see [`crate::turnstile`]).
|
||||||
|
#[serde(default)]
|
||||||
|
turnstile_token: Option<String>,
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Before a sign-up or reset e-mail goes out: at most a few per visitor
|
||||||
|
/// address an hour, and Cloudflare Turnstile's check when it is set up.
|
||||||
|
async fn not_a_robot(state: &AppState, headers: &axum::http::HeaderMap, token: Option<&str>) -> Result<(), ApiError> {
|
||||||
|
let ip = super::client_ip(headers);
|
||||||
|
if let Some(ip) = &ip {
|
||||||
|
state.signup_limiter.hit(ip)?;
|
||||||
|
}
|
||||||
|
crate::turnstile::verify(state.config.turnstile.as_ref(), token, ip.as_deref()).await
|
||||||
}
|
}
|
||||||
|
|
||||||
/// Password endpoints answer 403 while `PASSWORD_LOGIN` is off.
|
/// Password endpoints answer 403 while `PASSWORD_LOGIN` is off.
|
||||||
@@ -244,10 +257,12 @@ pub fn password_login_enabled(state: &crate::AppState) -> Result<(), ApiError> {
|
|||||||
/// password instead), so the form does not reveal who is registered.
|
/// password instead), so the form does not reveal who is registered.
|
||||||
pub async fn register(
|
pub async fn register(
|
||||||
State(state): St,
|
State(state): St,
|
||||||
|
headers: axum::http::HeaderMap,
|
||||||
WithRejection(Json(req), _): Body<RegisterRequest>,
|
WithRejection(Json(req), _): Body<RegisterRequest>,
|
||||||
) -> ApiResult<impl IntoResponse> {
|
) -> ApiResult<impl IntoResponse> {
|
||||||
password_login_enabled(&state)?;
|
password_login_enabled(&state)?;
|
||||||
let email = normalize_email(&req.email)?;
|
let email = normalize_email(&req.email)?;
|
||||||
|
not_a_robot(&state, &headers, req.turnstile_token.as_deref()).await?;
|
||||||
let locale = validate_locale(&state, req.locale.as_deref())?;
|
let locale = validate_locale(&state, req.locale.as_deref())?;
|
||||||
|
|
||||||
let mut tx = state.db.begin().await?;
|
let mut tx = state.db.begin().await?;
|
||||||
@@ -553,6 +568,9 @@ pub async fn logout_all(State(state): St, auth: AuthUser, jar: CookieJar) -> Api
|
|||||||
#[serde(deny_unknown_fields)]
|
#[serde(deny_unknown_fields)]
|
||||||
pub struct ResetRequest {
|
pub struct ResetRequest {
|
||||||
email: String,
|
email: String,
|
||||||
|
/// Cloudflare Turnstile's token (see [`crate::turnstile`]).
|
||||||
|
#[serde(default)]
|
||||||
|
turnstile_token: Option<String>,
|
||||||
}
|
}
|
||||||
|
|
||||||
/// Forgotten password: a link to set a new one (also adds a password to a
|
/// Forgotten password: a link to set a new one (also adds a password to a
|
||||||
@@ -560,9 +578,11 @@ pub struct ResetRequest {
|
|||||||
/// whether the address is registered.
|
/// whether the address is registered.
|
||||||
pub async fn request_password_reset(
|
pub async fn request_password_reset(
|
||||||
State(state): St,
|
State(state): St,
|
||||||
|
headers: axum::http::HeaderMap,
|
||||||
WithRejection(Json(req), _): Body<ResetRequest>,
|
WithRejection(Json(req), _): Body<ResetRequest>,
|
||||||
) -> ApiResult<StatusCode> {
|
) -> ApiResult<StatusCode> {
|
||||||
password_login_enabled(&state)?;
|
password_login_enabled(&state)?;
|
||||||
|
not_a_robot(&state, &headers, req.turnstile_token.as_deref()).await?;
|
||||||
let Ok(email) = normalize_email(&req.email) else { return Ok(StatusCode::ACCEPTED) };
|
let Ok(email) = normalize_email(&req.email) else { return Ok(StatusCode::ACCEPTED) };
|
||||||
let mut tx = state.db.begin().await?;
|
let mut tx = state.db.begin().await?;
|
||||||
let user: Option<User> = sqlx::query_as(&format!("SELECT {USER_COLUMNS} FROM users WHERE email = $1 FOR UPDATE"))
|
let user: Option<User> = sqlx::query_as(&format!("SELECT {USER_COLUMNS} FROM users WHERE email = $1 FOR UPDATE"))
|
||||||
|
|||||||
@@ -233,5 +233,7 @@ async fn public_config(State(state): St) -> Json<Value> {
|
|||||||
"referral_rewards": c.referral_rewards,
|
"referral_rewards": c.referral_rewards,
|
||||||
"signup_mode": c.signup_mode.as_str(),
|
"signup_mode": c.signup_mode.as_str(),
|
||||||
"password_min_length": crate::auth::MIN_PASSWORD_LEN,
|
"password_min_length": crate::auth::MIN_PASSWORD_LEN,
|
||||||
|
// Cloudflare Turnstile on the e-mail sign-up and reset forms (null: none).
|
||||||
|
"turnstile_site_key": c.turnstile.as_ref().map(|t| t.site_key.clone()),
|
||||||
}))
|
}))
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -226,12 +226,20 @@ async fn fake_s3(
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/// Cloudflare Turnstile: the token "ok" with the test secret passes.
|
||||||
|
async fn fake_turnstile(axum::Form(form): axum::Form<std::collections::HashMap<String, String>>) -> Json<Value> {
|
||||||
|
let ok = form.get("secret").map(String::as_str) == Some("test-secret")
|
||||||
|
&& form.get("response").map(String::as_str) == Some("ok");
|
||||||
|
Json(json!({ "success": ok, "error-codes": if ok { json!([]) } else { json!(["invalid-input-response"]) } }))
|
||||||
|
}
|
||||||
|
|
||||||
async fn fake_services_with(s3: FakeS3) -> String {
|
async fn fake_services_with(s3: FakeS3) -> String {
|
||||||
let objects = Router::new().route("/s3/photos/{*key}", get(fake_s3).put(fake_s3).delete(fake_s3)).with_state(s3);
|
let objects = Router::new().route("/s3/photos/{*key}", get(fake_s3).put(fake_s3).delete(fake_s3)).with_state(s3);
|
||||||
let app = Router::new()
|
let app = Router::new()
|
||||||
.merge(objects)
|
.merge(objects)
|
||||||
.route("/billingo/documents/{id}/download", get(fake_billingo_pdf))
|
.route("/billingo/documents/{id}/download", get(fake_billingo_pdf))
|
||||||
.route("/openrouter/models", get(fake_openrouter_models))
|
.route("/openrouter/models", get(fake_openrouter_models))
|
||||||
|
.route("/turnstile/siteverify", post(fake_turnstile))
|
||||||
.route("/v1/checkout/sessions", post(fake_stripe_create))
|
.route("/v1/checkout/sessions", post(fake_stripe_create))
|
||||||
.route("/v1/checkout/sessions/{id}", get(fake_stripe_get))
|
.route("/v1/checkout/sessions/{id}", get(fake_stripe_get))
|
||||||
.route("/v1/refunds", post(fake_stripe_refund))
|
.route("/v1/refunds", post(fake_stripe_refund))
|
||||||
@@ -4031,3 +4039,42 @@ async fn a_gift_can_be_e_mailed_at_a_chosen_time(pool: PgPool) {
|
|||||||
assert_eq!(r.status, StatusCode::OK, "{}", r.body);
|
assert_eq!(r.status, StatusCode::OK, "{}", r.body);
|
||||||
assert_eq!(app.outbox_count("cili@example.com", "gift_package").await, 0);
|
assert_eq!(app.outbox_count("cili@example.com", "gift_package").await, 0);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
#[sqlx::test(migrator = "db::MIGRATOR")]
|
||||||
|
async fn email_sign_up_checks_turnstile_and_limits_each_address(pool: PgPool) {
|
||||||
|
let app = TestApp::with_config(pool, |c| {
|
||||||
|
c.turnstile = Some(crate::turnstile::TurnstileConfig {
|
||||||
|
site_key: "site-key".into(),
|
||||||
|
secret: "test-secret".into(),
|
||||||
|
verify_url: format!("{}/turnstile/siteverify", c.horoscope_api_url),
|
||||||
|
});
|
||||||
|
})
|
||||||
|
.await;
|
||||||
|
assert_eq!(app.get("/v1/config", None).await.body["turnstile_site_key"], "site-key");
|
||||||
|
let ip = [("x-real-ip", "203.0.113.50")];
|
||||||
|
let sign_up = |token: Option<&str>| json!({ "email": "anna@example.com", "turnstile_token": token });
|
||||||
|
|
||||||
|
// No token or a wrong one: no account, no e-mail.
|
||||||
|
for token in [None, Some("rossz")] {
|
||||||
|
let r = app.call_with("POST", "/v1/auth/register", None, Some(sign_up(token)), &ip).await;
|
||||||
|
assert_eq!(r.status, StatusCode::BAD_REQUEST, "{}", r.body);
|
||||||
|
}
|
||||||
|
let users: i64 = sqlx::query_scalar("SELECT count(*) FROM users").fetch_one(&app.pool).await.unwrap();
|
||||||
|
assert_eq!(users, 0);
|
||||||
|
let r = app.call_with("POST", "/v1/auth/register", None, Some(sign_up(Some("ok"))), &ip).await;
|
||||||
|
assert_eq!(r.status, StatusCode::ACCEPTED, "{}", r.body);
|
||||||
|
let reset = |token: Option<&str>| json!({ "email": "anna@example.com", "turnstile_token": token });
|
||||||
|
let r = app.call_with("POST", "/v1/auth/password-reset", None, Some(reset(None)), &ip).await;
|
||||||
|
assert_eq!(r.status, StatusCode::BAD_REQUEST);
|
||||||
|
|
||||||
|
// Ten e-mail requests an hour from one address (the four above count too).
|
||||||
|
for _ in 0..6 {
|
||||||
|
let r = app.call_with("POST", "/v1/auth/password-reset", None, Some(reset(Some("ok"))), &ip).await;
|
||||||
|
assert_eq!(r.status, StatusCode::ACCEPTED);
|
||||||
|
}
|
||||||
|
let r = app.call_with("POST", "/v1/auth/password-reset", None, Some(reset(Some("ok"))), &ip).await;
|
||||||
|
assert_eq!(r.status, StatusCode::TOO_MANY_REQUESTS);
|
||||||
|
let elsewhere = [("x-real-ip", "198.51.100.60")];
|
||||||
|
let r = app.call_with("POST", "/v1/auth/password-reset", None, Some(reset(Some("ok"))), &elsewhere).await;
|
||||||
|
assert_eq!(r.status, StatusCode::ACCEPTED);
|
||||||
|
}
|
||||||
|
|||||||
@@ -0,0 +1,63 @@
|
|||||||
|
//! Cloudflare Turnstile: the e-mail sign-up and the password reset forms
|
||||||
|
//! carry a token from Cloudflare's widget (usually invisible), checked here
|
||||||
|
//! before an e-mail goes out. Without the keys (development) there is no
|
||||||
|
//! check. Cloudflare not answering counts as a failed check.
|
||||||
|
|
||||||
|
use std::sync::OnceLock;
|
||||||
|
use std::time::Duration;
|
||||||
|
|
||||||
|
use serde::Deserialize;
|
||||||
|
|
||||||
|
use crate::error::ApiError;
|
||||||
|
|
||||||
|
pub const VERIFY_URL: &str = "https://challenges.cloudflare.com/turnstile/v0/siteverify";
|
||||||
|
|
||||||
|
#[derive(Clone, Debug)]
|
||||||
|
pub struct TurnstileConfig {
|
||||||
|
/// Public: the page's widget uses it (`/v1/config`).
|
||||||
|
pub site_key: String,
|
||||||
|
pub secret: String,
|
||||||
|
pub verify_url: String,
|
||||||
|
}
|
||||||
|
|
||||||
|
#[derive(Deserialize)]
|
||||||
|
struct Answer {
|
||||||
|
success: bool,
|
||||||
|
#[serde(default, rename = "error-codes")]
|
||||||
|
error_codes: Vec<String>,
|
||||||
|
}
|
||||||
|
|
||||||
|
fn client() -> &'static reqwest::Client {
|
||||||
|
static CLIENT: OnceLock<reqwest::Client> = OnceLock::new();
|
||||||
|
CLIENT.get_or_init(|| reqwest::Client::builder().timeout(Duration::from_secs(8)).build().expect("an HTTP client"))
|
||||||
|
}
|
||||||
|
|
||||||
|
fn refused() -> ApiError {
|
||||||
|
ApiError::BadRequest("Kérjük, igazold, hogy nem robot vagy (az ellenőrzés nem sikerült), és próbáld újra.".into())
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Checks the widget's token (with the visitor's address, when known).
|
||||||
|
pub async fn verify(config: Option<&TurnstileConfig>, token: Option<&str>, ip: Option<&str>) -> Result<(), ApiError> {
|
||||||
|
let Some(config) = config else { return Ok(()) };
|
||||||
|
let token = token.map(str::trim).filter(|t| !t.is_empty() && t.len() <= 2048).ok_or_else(refused)?;
|
||||||
|
let mut form = vec![("secret", config.secret.as_str()), ("response", token)];
|
||||||
|
if let Some(ip) = ip {
|
||||||
|
form.push(("remoteip", ip));
|
||||||
|
}
|
||||||
|
let answer: Answer = match client().post(&config.verify_url).form(&form).send().await {
|
||||||
|
Ok(res) => res.json().await.map_err(|e| {
|
||||||
|
tracing::warn!(error = %e, "turnstile answer not understood");
|
||||||
|
refused()
|
||||||
|
})?,
|
||||||
|
Err(e) => {
|
||||||
|
tracing::warn!(error = %e, "turnstile not reachable");
|
||||||
|
return Err(refused());
|
||||||
|
}
|
||||||
|
};
|
||||||
|
if answer.success {
|
||||||
|
Ok(())
|
||||||
|
} else {
|
||||||
|
tracing::info!(codes = ?answer.error_codes, "turnstile check failed");
|
||||||
|
Err(refused())
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -254,7 +254,9 @@ export default async function PrivacyPage() {
|
|||||||
</li>
|
</li>
|
||||||
<li>
|
<li>
|
||||||
<strong>Cloudflare, Inc.</strong> – a forgalom továbbítása és a támadások elleni védelem; az oldal
|
<strong>Cloudflare, Inc.</strong> – a forgalom továbbítása és a támadások elleni védelem; az oldal
|
||||||
letöltésekor kezeli az IP-címedet és a kérés adatait.
|
letöltésekor kezeli az IP-címedet és a kérés adatait. Az e-mailes regisztrációnál és a jelszókérésnél a
|
||||||
|
Turnstile szolgáltatásával ellenőrzi, hogy nem gép küldi az űrlapot (ehhez a böngésző jellemzőit is
|
||||||
|
vizsgálja).
|
||||||
</li>
|
</li>
|
||||||
<li>
|
<li>
|
||||||
<strong>Google LLC</strong> – bejelentkezés Google-fiókkal.
|
<strong>Google LLC</strong> – bejelentkezés Google-fiókkal.
|
||||||
|
|||||||
@@ -3,6 +3,7 @@
|
|||||||
import { useRouter } from "next/navigation";
|
import { useRouter } from "next/navigation";
|
||||||
import { useState } from "react";
|
import { useState } from "react";
|
||||||
|
|
||||||
|
import { Turnstile } from "@/components/Turnstile";
|
||||||
import { ApiError, api, errorText } from "@/lib/api";
|
import { ApiError, api, errorText } from "@/lib/api";
|
||||||
|
|
||||||
type Mode = "login" | "register" | "forgot";
|
type Mode = "login" | "register" | "forgot";
|
||||||
@@ -25,9 +26,12 @@ export function PasswordLogin({
|
|||||||
inviteToken = null,
|
inviteToken = null,
|
||||||
referral = null,
|
referral = null,
|
||||||
initialMode = "login",
|
initialMode = "login",
|
||||||
|
turnstileKey = null,
|
||||||
}: {
|
}: {
|
||||||
target: string;
|
target: string;
|
||||||
inviteToken?: string | null;
|
inviteToken?: string | null;
|
||||||
|
/** Cloudflare Turnstile on the sign-up and reset forms (null: none). */
|
||||||
|
turnstileKey?: string | null;
|
||||||
/** The shared link the visitor came from (in the login link: `?ref=`), for the sharer's reward. */
|
/** The shared link the visitor came from (in the login link: `?ref=`), for the sharer's reward. */
|
||||||
referral?: string | null;
|
referral?: string | null;
|
||||||
initialMode?: Mode;
|
initialMode?: Mode;
|
||||||
@@ -41,6 +45,10 @@ export function PasswordLogin({
|
|||||||
const [error, setError] = useState<string | null>(null);
|
const [error, setError] = useState<string | null>(null);
|
||||||
const [sent, setSent] = useState<Mode | null>(null);
|
const [sent, setSent] = useState<Mode | null>(null);
|
||||||
const [uninvited, setUninvited] = useState(false);
|
const [uninvited, setUninvited] = useState(false);
|
||||||
|
// Turnstile's token (sign-up and reset only); a new round after each try.
|
||||||
|
const [token, setToken] = useState<string | null>(null);
|
||||||
|
const [round, setRound] = useState(0);
|
||||||
|
const checked = mode === "login" || !turnstileKey;
|
||||||
|
|
||||||
function switchTo(next: Mode) {
|
function switchTo(next: Mode) {
|
||||||
setMode(next);
|
setMode(next);
|
||||||
@@ -63,10 +71,17 @@ export function PasswordLogin({
|
|||||||
}
|
}
|
||||||
if (mode === "register") {
|
if (mode === "register") {
|
||||||
await api("/auth/register", {
|
await api("/auth/register", {
|
||||||
body: { email, display_name: name.trim() || null, locale: "hu", invite_token: inviteToken, referral },
|
body: {
|
||||||
|
email,
|
||||||
|
display_name: name.trim() || null,
|
||||||
|
locale: "hu",
|
||||||
|
invite_token: inviteToken,
|
||||||
|
referral,
|
||||||
|
turnstile_token: token,
|
||||||
|
},
|
||||||
});
|
});
|
||||||
} else {
|
} else {
|
||||||
await api("/auth/password-reset", { body: { email } });
|
await api("/auth/password-reset", { body: { email, turnstile_token: token } });
|
||||||
}
|
}
|
||||||
setSent(mode);
|
setSent(mode);
|
||||||
} catch (err) {
|
} catch (err) {
|
||||||
@@ -74,6 +89,8 @@ export function PasswordLogin({
|
|||||||
else setError(mode === "login" ? loginError(err) : errorText(err));
|
else setError(mode === "login" ? loginError(err) : errorText(err));
|
||||||
} finally {
|
} finally {
|
||||||
setBusy(false);
|
setBusy(false);
|
||||||
|
// A token works once.
|
||||||
|
if (mode !== "login" && turnstileKey) setRound((r) => r + 1);
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -156,9 +173,12 @@ export function PasswordLogin({
|
|||||||
jelszót is beállíthatsz.
|
jelszót is beállíthatsz.
|
||||||
</p>
|
</p>
|
||||||
)}
|
)}
|
||||||
<button type="submit" className="btn btn-primary" disabled={busy}>
|
{mode !== "login" && turnstileKey && <Turnstile siteKey={turnstileKey} onToken={setToken} round={round} />}
|
||||||
|
<button type="submit" className="btn btn-primary" disabled={busy || (!checked && !token)}>
|
||||||
{busy
|
{busy
|
||||||
? "Küldés…"
|
? "Küldés…"
|
||||||
|
: !checked && !token
|
||||||
|
? "Egy pillanat…"
|
||||||
: mode === "login"
|
: mode === "login"
|
||||||
? "Belépés"
|
? "Belépés"
|
||||||
: mode === "register"
|
: mode === "register"
|
||||||
|
|||||||
@@ -169,7 +169,13 @@ export default async function LoginPage({ searchParams }: { searchParams: Promis
|
|||||||
</div>
|
</div>
|
||||||
)}
|
)}
|
||||||
{password && (
|
{password && (
|
||||||
<PasswordLogin target={target} inviteToken={pendingInvite} referral={referral} initialMode={initialMode} />
|
<PasswordLogin
|
||||||
|
target={target}
|
||||||
|
inviteToken={pendingInvite}
|
||||||
|
referral={referral}
|
||||||
|
initialMode={initialMode}
|
||||||
|
turnstileKey={config?.turnstile_site_key ?? null}
|
||||||
|
/>
|
||||||
)}
|
)}
|
||||||
</>
|
</>
|
||||||
) : (
|
) : (
|
||||||
|
|||||||
@@ -242,7 +242,8 @@ export default async function PrivacyPolicyPage() {
|
|||||||
</li>
|
</li>
|
||||||
<li>
|
<li>
|
||||||
<strong>Cloudflare, Inc.</strong>: delivering traffic and protecting against attacks; processes your IP
|
<strong>Cloudflare, Inc.</strong>: delivering traffic and protecting against attacks; processes your IP
|
||||||
address and request data when the site loads.
|
address and request data when the site loads. On the e-mail sign-up and password request forms its
|
||||||
|
Turnstile service checks that a person, not a script, sends the form (looking at browser features too).
|
||||||
</li>
|
</li>
|
||||||
<li>
|
<li>
|
||||||
<strong>Google LLC</strong>: signing in with a Google account.
|
<strong>Google LLC</strong>: signing in with a Google account.
|
||||||
|
|||||||
@@ -0,0 +1,86 @@
|
|||||||
|
"use client";
|
||||||
|
|
||||||
|
import { useEffect, useRef } from "react";
|
||||||
|
|
||||||
|
type TurnstileApi = {
|
||||||
|
render: (el: HTMLElement, options: Record<string, unknown>) => string;
|
||||||
|
reset: (id: string) => void;
|
||||||
|
remove: (id: string) => void;
|
||||||
|
};
|
||||||
|
|
||||||
|
declare global {
|
||||||
|
interface Window {
|
||||||
|
turnstile?: TurnstileApi;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
const SCRIPT = "https://challenges.cloudflare.com/turnstile/v0/api.js?render=explicit";
|
||||||
|
let loading: Promise<TurnstileApi> | null = null;
|
||||||
|
|
||||||
|
function load(): Promise<TurnstileApi> {
|
||||||
|
if (window.turnstile) return Promise.resolve(window.turnstile);
|
||||||
|
loading ??= new Promise((resolve, reject) => {
|
||||||
|
const script = document.createElement("script");
|
||||||
|
script.src = SCRIPT;
|
||||||
|
script.async = true;
|
||||||
|
script.onload = () => (window.turnstile ? resolve(window.turnstile) : reject(new Error("turnstile")));
|
||||||
|
script.onerror = () => {
|
||||||
|
loading = null;
|
||||||
|
reject(new Error("turnstile"));
|
||||||
|
};
|
||||||
|
document.head.appendChild(script);
|
||||||
|
});
|
||||||
|
return loading;
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Cloudflare Turnstile ("nem robot vagy?"): usually invisible, it shows a box
|
||||||
|
* only when Cloudflare wants a click. `onToken` gets the token (null when it
|
||||||
|
* expires); a new `round` asks for a fresh one (a token works once).
|
||||||
|
*/
|
||||||
|
export function Turnstile({
|
||||||
|
siteKey,
|
||||||
|
onToken,
|
||||||
|
round = 0,
|
||||||
|
}: {
|
||||||
|
siteKey: string;
|
||||||
|
onToken: (token: string | null) => void;
|
||||||
|
round?: number;
|
||||||
|
}) {
|
||||||
|
const box = useRef<HTMLDivElement>(null);
|
||||||
|
const widget = useRef<string | null>(null);
|
||||||
|
const callback = useRef(onToken);
|
||||||
|
callback.current = onToken;
|
||||||
|
|
||||||
|
useEffect(() => {
|
||||||
|
let gone = false;
|
||||||
|
load()
|
||||||
|
.then((api) => {
|
||||||
|
if (gone || !box.current || widget.current) return;
|
||||||
|
widget.current = api.render(box.current, {
|
||||||
|
sitekey: siteKey,
|
||||||
|
appearance: "interaction-only",
|
||||||
|
language: "hu",
|
||||||
|
theme: "auto",
|
||||||
|
callback: (token: string) => callback.current(token),
|
||||||
|
"expired-callback": () => callback.current(null),
|
||||||
|
"error-callback": () => callback.current(null),
|
||||||
|
});
|
||||||
|
})
|
||||||
|
.catch(() => callback.current(null));
|
||||||
|
return () => {
|
||||||
|
gone = true;
|
||||||
|
if (widget.current && window.turnstile) window.turnstile.remove(widget.current);
|
||||||
|
widget.current = null;
|
||||||
|
};
|
||||||
|
}, [siteKey]);
|
||||||
|
|
||||||
|
useEffect(() => {
|
||||||
|
if (round > 0 && widget.current && window.turnstile) {
|
||||||
|
callback.current(null);
|
||||||
|
window.turnstile.reset(widget.current);
|
||||||
|
}
|
||||||
|
}, [round]);
|
||||||
|
|
||||||
|
return <div ref={box} className="turnstile" />;
|
||||||
|
}
|
||||||
@@ -98,6 +98,8 @@ export interface Question {
|
|||||||
|
|
||||||
export interface PublicConfig {
|
export interface PublicConfig {
|
||||||
google_login: { enabled: boolean; client_id: string | null };
|
google_login: { enabled: boolean; client_id: string | null };
|
||||||
|
/** Cloudflare Turnstile on the e-mail sign-up and reset forms (null: none). */
|
||||||
|
turnstile_site_key?: string | null;
|
||||||
/** Sign in with Apple; `client_id` is the Services ID. */
|
/** Sign in with Apple; `client_id` is the Services ID. */
|
||||||
apple_login?: { enabled: boolean; client_id: string | null };
|
apple_login?: { enabled: boolean; client_id: string | null };
|
||||||
locales: string[];
|
locales: string[];
|
||||||
|
|||||||
Reference in New Issue
Block a user