auth: e-mail + password login with e-mailed password links
Sign-up asks no password: a link goes to the address and the password is set there (also for forgotten passwords), by whoever opens the mailbox. So nobody can register a password for someone else's address, and linking Google or Apple to an account with the same address stays safe. Opening the link confirms the address, ends other sessions and logs in. Sign-up answers alike for registered addresses (the owner gets an 'account exists' link), links are limited to one per kind a minute and five an hour, and unconfirmed password accounts cannot log in. Frontend: login form with sign-up and forgotten password next to the social buttons, and the /jelszo page for the link. Still behind PASSWORD_LOGIN (off on prod). Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> Claude-Session: https://claude.ai/code/session_012vLHzh5qUhFtmJhzkcTbXL
This commit is contained in:
@@ -91,20 +91,36 @@ pub fn render(template: &str, locale: &str, payload: &Value) -> Result<Rendered,
|
||||
};
|
||||
let content = match (template, lang) {
|
||||
("verify_email", Lang::Hu) => Content::simple(
|
||||
"Erősítsd meg az e-mail-címed".into(),
|
||||
"Add meg a jelszavad".into(),
|
||||
greeting(name(payload, "display_name")),
|
||||
"Köszönjük, hogy regisztráltál a Sorsfonalakon! Az alábbi gombbal erősítsd meg az e-mail-címed.".into(),
|
||||
"E-mail-cím megerősítése",
|
||||
"Köszönjük, hogy regisztráltál a Sorsfonalakon! Az alábbi gombbal megerősíted az e-mail-címed, és megadhatod a jelszavad. Utána már be is vagy lépve.".into(),
|
||||
"Jelszó megadása",
|
||||
url,
|
||||
"A link 3 napig érvényes. Ha nem te regisztráltál, nyugodtan hagyd figyelmen kívül ezt a levelet.",
|
||||
"A link 3 napig érvényes, és csak egyszer használható. Ha nem te regisztráltál, nyugodtan hagyd figyelmen kívül ezt a levelet.",
|
||||
),
|
||||
("verify_email", Lang::En) => Content::simple(
|
||||
"Confirm your e-mail address".into(),
|
||||
"Set your password".into(),
|
||||
greeting(name(payload, "display_name")),
|
||||
"Thanks for signing up for Sorsfonalak! Please confirm your e-mail address with the button below.".into(),
|
||||
"Confirm e-mail address",
|
||||
"Thanks for signing up for Sorsfonalak! The button below confirms your e-mail address and lets you set your password. You will be logged in right after.".into(),
|
||||
"Set password",
|
||||
url,
|
||||
"The link is valid for 3 days. If you did not sign up, you can safely ignore this e-mail.",
|
||||
"The link is valid for 3 days and can be used once. If you did not sign up, you can safely ignore this e-mail.",
|
||||
),
|
||||
("account_exists", Lang::Hu) => Content::simple(
|
||||
"Már van fiókod a Sorsfonalakon".into(),
|
||||
greeting(name(payload, "display_name")),
|
||||
"Ezzel az e-mail-címmel regisztrációt kezdtek a Sorsfonalakon, de neked már van fiókod. Beléphetsz úgy, ahogy eddig (például Google-lel), vagy az alábbi gombbal jelszót adhatsz meg.".into(),
|
||||
"Jelszó megadása",
|
||||
url,
|
||||
"A link 1 óráig érvényes, és csak egyszer használható. Ha nem te voltál, hagyd figyelmen kívül ezt a levelet: a fiókod nem változik.",
|
||||
),
|
||||
("account_exists", Lang::En) => Content::simple(
|
||||
"You already have a Sorsfonalak account".into(),
|
||||
greeting(name(payload, "display_name")),
|
||||
"Someone started signing up for Sorsfonalak with this e-mail address, but you already have an account. Log in as before (e.g. with Google), or set a password with the button below.".into(),
|
||||
"Set password",
|
||||
url,
|
||||
"The link is valid for 1 hour and can be used once. If it was not you, ignore this e-mail: your account stays the same.",
|
||||
),
|
||||
("reset_password", Lang::Hu) => Content::simple(
|
||||
"Új jelszó megadása".into(),
|
||||
|
||||
@@ -32,6 +32,11 @@ Felhasználók, belépés, mentett születési képletek, szinasztriák és megh
|
||||
|
||||
- **Munkamenet:** véletlen token, HttpOnly + SameSite=Lax sütiben (`sf_session`). A belépési válasz törzsében is ott van, hogy nem böngészős kliens `Authorization: Bearer <token>` fejléccel küldhesse vissza. Az adatbázis csak a token SHA-256 hash-ét tárolja, így a munkamenet visszavonható (kijelentkezés, jelszócsere, fióktörlés).
|
||||
- **E-mail + jelszó** (csak `PASSWORD_LOGIN=true` mellett; élesben csak közösségi belépés lesz, hogy ne lehessen tömegesen ingyenes fiókokat nyitni):
|
||||
- a regisztráció nem kér jelszót: a címre megy egy link (`verify_email`, 3 napig él), és jelszót csak ezen lehet megadni. Az elfelejtett jelszó linkje (`reset_password`, 1 óra) ugyanoda visz (`/jelszo?token=…`). Így jelszót csak az állíthat be, aki a postafiókot olvassa, és mindig ő maga választja: senki nem regisztrálhat más címére jelszót, ezért a Google- vagy Apple-fiók összekötése az azonos című fiókkal biztonságos;
|
||||
- a link megnyitásakor a cím megerősítettnek számít, minden korábbi munkamenet megszűnik, és a felhasználó be is lép;
|
||||
- már regisztrált címre a regisztráció ugyanúgy 202-t ad (nem derül ki, ki van regisztrálva), a tulajdonos pedig egy „Már van fiókod” levelet kap jelszómegadó linkkel (`account_exists`);
|
||||
- jelszavas link címenként és fajtánként percenként egy, összesen óránként öt mehet ki;
|
||||
- megerősítetlen címmel (a linkes regisztráció előtti fiók) nem lehet jelszóval belépni;
|
||||
- a jelszó legalább 10 karakter, Argon2id hash-sel tárolva;
|
||||
- címenként 15 percen belül 10 hibás próbálkozás után átmenetileg tiltás jár;
|
||||
- ismeretlen címnél is ugyanannyi ideig tart a válasz.
|
||||
@@ -57,14 +62,12 @@ Felhasználók, belépés, mentett születési képletek, szinasztriák és megh
|
||||
|---|---|---|
|
||||
| `GET /v1/config` | – | Google kliens-azonosító, `password_login`, `signup_mode`, nyelvek, elemző és összefoglaló modell |
|
||||
| `GET /v1/packages` | – | a csomagkatalógus árral, tartalommal, megtakarítással, elemzésenkénti árral (lásd `docs/csomagok.md`) |
|
||||
| `POST /v1/auth/register` | – | `{email, password, display_name?, locale?, invite_token?}` → munkamenet; megerősítő e-mailt küld |
|
||||
| `POST /v1/auth/register` | – | `{email, display_name?, locale?, invite_token?, referral?}` → 202; jelszómegadó linket küld |
|
||||
| `POST /v1/auth/login` | – | `{email, password}` |
|
||||
| `POST /v1/auth/google` | – | `{id_token, invite_token?}`; `created: true`, ha most jött létre a fiók; meghívó nélkül 403 `not_invited` |
|
||||
| `POST /v1/auth/logout`, `/logout-all` | user | kijelentkezés erről, illetve minden eszközről |
|
||||
| `POST /v1/auth/verify-email` | – | `{token}` az e-mailben kapott linkből |
|
||||
| `POST /v1/auth/resend-verification` | user | |
|
||||
| `POST /v1/auth/password-reset` | – | `{email}`; mindig 202 |
|
||||
| `POST /v1/auth/password-reset/confirm` | – | `{token, password}`; minden munkamenet megszűnik |
|
||||
| `POST /v1/auth/set-password` | – | `{token, password}` a levélben kapott linkből (regisztráció vagy elfelejtett jelszó); a cím megerősítetté válik, minden más munkamenet megszűnik, és belép |
|
||||
| `GET`/`PATCH`/`DELETE /v1/me` | user | profil (`display_name`, `locale`); törlés: `{confirm: "DELETE"}` |
|
||||
| `POST /v1/me/password` | user | `{current_password?, new_password}`; Google-fiókhoz jelszót is ad |
|
||||
| `GET /v1/me/export` | user | GDPR: minden adat egy JSON-ban |
|
||||
|
||||
@@ -1,5 +1,10 @@
|
||||
//! Registration and login: e-mail + password, Google; e-mail verification,
|
||||
//! password reset, logout.
|
||||
//! Registration and login: e-mail + password, Google, Apple; password links,
|
||||
//! logout.
|
||||
//!
|
||||
//! A password can only be set through a link sent to the address (sign-up,
|
||||
//! forgotten password), by whoever opens it. So every password account has a
|
||||
//! confirmed address, and nobody can set a password for someone else's
|
||||
//! address: linking a Google or Apple account with the same address is safe.
|
||||
|
||||
use axum::Json;
|
||||
use axum::extract::State;
|
||||
@@ -100,14 +105,14 @@ async fn issue_token(
|
||||
Ok(token)
|
||||
}
|
||||
|
||||
/// Uses a one-time token; returns its user.
|
||||
async fn consume_token(conn: &mut PgConnection, token: &str, purpose: &str) -> Result<Uuid, ApiError> {
|
||||
/// Uses a one-time token of one of `purposes`; returns its user.
|
||||
async fn consume_token(conn: &mut PgConnection, token: &str, purposes: &[&str]) -> Result<Uuid, ApiError> {
|
||||
let row: Option<(Uuid,)> = sqlx::query_as(
|
||||
"UPDATE auth_tokens SET used_at = now() \
|
||||
WHERE token_hash = $1 AND purpose = $2 AND used_at IS NULL AND expires_at > now() RETURNING user_id",
|
||||
WHERE token_hash = $1 AND purpose = ANY($2) AND used_at IS NULL AND expires_at > now() RETURNING user_id",
|
||||
)
|
||||
.bind(db::token_hash(token.trim()))
|
||||
.bind(purpose)
|
||||
.bind(purposes)
|
||||
.fetch_optional(conn)
|
||||
.await?;
|
||||
row.map(|(id,)| id).ok_or(ApiError::InvalidToken)
|
||||
@@ -141,10 +146,44 @@ pub async fn queue_email_to(
|
||||
Ok(())
|
||||
}
|
||||
|
||||
async fn queue_verification(state: &AppState, conn: &mut PgConnection, user: &User) -> Result<(), ApiError> {
|
||||
let token = issue_token(conn, user.id, "verify_email", VERIFY_EMAIL_TTL).await?;
|
||||
let url = format!("{}/verify-email?token={token}", state.config.public_base_url);
|
||||
queue_email(conn, user, "verify_email", json!({ "url": url, "display_name": user.display_name })).await
|
||||
/// The e-mails that carry a password link.
|
||||
const LINK_TEMPLATES: [&str; 3] = ["verify_email", "reset_password", "account_exists"];
|
||||
|
||||
/// Whether another password link may go to `email` now: one per kind a
|
||||
/// minute and five an hour, so the forms cannot flood a mailbox.
|
||||
async fn may_send_link(conn: &mut PgConnection, email: &str, template: &str) -> Result<bool, ApiError> {
|
||||
let (same_kind, total): (i64, i64) = sqlx::query_as(
|
||||
"SELECT count(*) FILTER (WHERE template = $2 AND created_at > now() - interval '1 minute'), count(*) \
|
||||
FROM email_outbox WHERE to_email = $1 AND template = ANY($3) AND created_at > now() - interval '1 hour'",
|
||||
)
|
||||
.bind(email)
|
||||
.bind(template)
|
||||
.bind(&LINK_TEMPLATES[..])
|
||||
.fetch_one(conn)
|
||||
.await?;
|
||||
Ok(same_kind == 0 && total < 5)
|
||||
}
|
||||
|
||||
/// Sends a link that sets the password: `verify_email` (sign-up, valid for 3
|
||||
/// days), `reset_password` (forgotten password) or `account_exists` (sign-up
|
||||
/// with an address that already has an account), the latter two for 1 hour.
|
||||
async fn queue_password_link(
|
||||
state: &AppState,
|
||||
conn: &mut PgConnection,
|
||||
user: &User,
|
||||
template: &'static str,
|
||||
) -> Result<(), ApiError> {
|
||||
if !may_send_link(conn, &user.email, template).await? {
|
||||
tracing::info!(user = %user.id, template, "password link not sent: one went out a moment ago");
|
||||
return Ok(());
|
||||
}
|
||||
let (purpose, ttl) = match template {
|
||||
"verify_email" => ("verify_email", VERIFY_EMAIL_TTL),
|
||||
_ => ("reset_password", RESET_PASSWORD_TTL),
|
||||
};
|
||||
let token = issue_token(conn, user.id, purpose, ttl).await?;
|
||||
let url = format!("{}/jelszo?token={token}", state.config.public_base_url);
|
||||
queue_email(conn, user, template, json!({ "url": url, "display_name": user.display_name })).await
|
||||
}
|
||||
|
||||
fn login_response(
|
||||
@@ -165,7 +204,6 @@ fn login_response(
|
||||
#[serde(deny_unknown_fields)]
|
||||
pub struct RegisterRequest {
|
||||
email: String,
|
||||
password: String,
|
||||
display_name: Option<String>,
|
||||
locale: Option<String>,
|
||||
/// The invitation link's token, while sign-up needs an invitation.
|
||||
@@ -183,24 +221,30 @@ pub fn password_login_enabled(state: &crate::AppState) -> Result<(), ApiError> {
|
||||
}
|
||||
}
|
||||
|
||||
/// Sign-up with an e-mail address: no password yet, only a link to the
|
||||
/// address, where the password is set. Answers 202 the same way whether or
|
||||
/// not the address already has an account (that one gets a link to set a
|
||||
/// password instead), so the form does not reveal who is registered.
|
||||
pub async fn register(
|
||||
State(state): St,
|
||||
headers: HeaderMap,
|
||||
jar: CookieJar,
|
||||
WithRejection(Json(req), _): Body<RegisterRequest>,
|
||||
) -> ApiResult<impl IntoResponse> {
|
||||
password_login_enabled(&state)?;
|
||||
let email = normalize_email(&req.email)?;
|
||||
validate_password(&req.password)?;
|
||||
let locale = validate_locale(&state, req.locale.as_deref())?;
|
||||
let hash = hash_password(req.password).await?;
|
||||
|
||||
let mut tx = state.db.begin().await?;
|
||||
let exists: Option<(Uuid,)> =
|
||||
sqlx::query_as("SELECT id FROM users WHERE email = $1").bind(&email).fetch_optional(&mut *tx).await?;
|
||||
if exists.is_some() {
|
||||
return Err(ApiError::conflict("email_taken", "an account with this e-mail address already exists"));
|
||||
let existing: Option<User> =
|
||||
sqlx::query_as(&format!("SELECT {USER_COLUMNS} FROM users WHERE email = $1 FOR UPDATE"))
|
||||
.bind(&email)
|
||||
.fetch_optional(&mut *tx)
|
||||
.await?;
|
||||
match existing {
|
||||
Some(user) if user.email_verified_at.is_none() => {
|
||||
queue_password_link(&state, &mut tx, &user, "verify_email").await?;
|
||||
}
|
||||
Some(user) => queue_password_link(&state, &mut tx, &user, "account_exists").await?,
|
||||
None => {
|
||||
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)")
|
||||
@@ -210,14 +254,8 @@ pub async fn register(
|
||||
.bind(&locale)
|
||||
.execute(&mut *tx)
|
||||
.await?;
|
||||
sqlx::query("INSERT INTO auth_identities (id, user_id, provider, subject, password_hash, email) VALUES ($1, $2, 'password', $3, $4, $5)")
|
||||
.bind(Uuid::now_v7())
|
||||
.bind(user_id)
|
||||
.bind(user_id.to_string())
|
||||
.bind(hash)
|
||||
.bind(&email)
|
||||
.execute(&mut *tx)
|
||||
.await?;
|
||||
// Packages of invitations go to this account; only whoever opens
|
||||
// the link in the mailbox can ever log in to it.
|
||||
super::invitations::mark_accepted(
|
||||
&mut tx,
|
||||
user_id,
|
||||
@@ -226,14 +264,14 @@ pub async fn register(
|
||||
state.config.free_person_slots,
|
||||
)
|
||||
.await?;
|
||||
super::shares::record_referral(&mut tx, state.config.referral_rewards, user_id, req.referral.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?;
|
||||
super::shares::record_referral(&mut tx, state.config.referral_rewards, user_id, req.referral.as_deref())
|
||||
.await?;
|
||||
let user = load_user(&mut tx, user_id).await?;
|
||||
queue_password_link(&state, &mut tx, &user, "verify_email").await?;
|
||||
}
|
||||
}
|
||||
tx.commit().await?;
|
||||
|
||||
let session = create_session(&state.db, &state.config, user.id, user_agent(&headers)).await?;
|
||||
Ok(login_response(&state, jar, &user, session, true))
|
||||
Ok((StatusCode::ACCEPTED, Json(json!({ "sent": true }))))
|
||||
}
|
||||
|
||||
#[derive(Deserialize)]
|
||||
@@ -254,9 +292,12 @@ pub async fn login(
|
||||
let email = normalize_email(&req.email).map_err(|_| invalid())?;
|
||||
state.login_limiter.check(&email)?;
|
||||
|
||||
// Passwords are set through e-mailed links, so every password account has
|
||||
// a confirmed address; an unconfirmed one (made before that) cannot log in.
|
||||
let row: Option<(Uuid, String)> = sqlx::query_as(
|
||||
"SELECT u.id, i.password_hash FROM users u \
|
||||
JOIN auth_identities i ON i.user_id = u.id AND i.provider = 'password' WHERE u.email = $1",
|
||||
JOIN auth_identities i ON i.user_id = u.id AND i.provider = 'password' \
|
||||
WHERE u.email = $1 AND u.email_verified_at IS NOT NULL",
|
||||
)
|
||||
.bind(&email)
|
||||
.fetch_optional(&state.db)
|
||||
@@ -487,34 +528,7 @@ pub async fn logout_all(State(state): St, auth: AuthUser, jar: CookieJar) -> Api
|
||||
Ok((StatusCode::NO_CONTENT, jar.add(removal_cookie(&state.config))))
|
||||
}
|
||||
|
||||
// --- e-mail verification and password reset ------------------------------------------------
|
||||
|
||||
#[derive(Deserialize)]
|
||||
#[serde(deny_unknown_fields)]
|
||||
pub struct TokenRequest {
|
||||
token: String,
|
||||
}
|
||||
|
||||
pub async fn verify_email(State(state): St, WithRejection(Json(req), _): Body<TokenRequest>) -> ApiResult<Json<Value>> {
|
||||
let mut tx = state.db.begin().await?;
|
||||
let user_id = consume_token(&mut tx, &req.token, "verify_email").await?;
|
||||
sqlx::query("UPDATE users SET email_verified_at = COALESCE(email_verified_at, now()) WHERE id = $1")
|
||||
.bind(user_id)
|
||||
.execute(&mut *tx)
|
||||
.await?;
|
||||
tx.commit().await?;
|
||||
Ok(Json(json!({ "verified": true })))
|
||||
}
|
||||
|
||||
pub async fn resend_verification(State(state): St, auth: AuthUser) -> ApiResult<StatusCode> {
|
||||
if auth.user.email_verified_at.is_some() {
|
||||
return Err(ApiError::conflict("already_verified", "the e-mail address is already verified"));
|
||||
}
|
||||
let mut tx = state.db.begin().await?;
|
||||
queue_verification(&state, &mut tx, &auth.user).await?;
|
||||
tx.commit().await?;
|
||||
Ok(StatusCode::ACCEPTED)
|
||||
}
|
||||
// --- password links ---------------------------------------------------------------------
|
||||
|
||||
#[derive(Deserialize)]
|
||||
#[serde(deny_unknown_fields)]
|
||||
@@ -522,7 +536,9 @@ pub struct ResetRequest {
|
||||
email: String,
|
||||
}
|
||||
|
||||
/// Always 202, so the response does not reveal whether the address is registered.
|
||||
/// Forgotten password: a link to set a new one (also adds a password to a
|
||||
/// Google or Apple account). Always 202, so the response does not reveal
|
||||
/// whether the address is registered.
|
||||
pub async fn request_password_reset(
|
||||
State(state): St,
|
||||
WithRejection(Json(req), _): Body<ResetRequest>,
|
||||
@@ -530,14 +546,12 @@ pub async fn request_password_reset(
|
||||
password_login_enabled(&state)?;
|
||||
let Ok(email) = normalize_email(&req.email) else { return Ok(StatusCode::ACCEPTED) };
|
||||
let mut tx = state.db.begin().await?;
|
||||
let user: Option<User> = sqlx::query_as(&format!("SELECT {USER_COLUMNS} FROM users WHERE email = $1"))
|
||||
let user: Option<User> = sqlx::query_as(&format!("SELECT {USER_COLUMNS} FROM users WHERE email = $1 FOR UPDATE"))
|
||||
.bind(&email)
|
||||
.fetch_optional(&mut *tx)
|
||||
.await?;
|
||||
if let Some(user) = user {
|
||||
let token = issue_token(&mut tx, user.id, "reset_password", RESET_PASSWORD_TTL).await?;
|
||||
let url = format!("{}/reset-password?token={token}", state.config.public_base_url);
|
||||
queue_email(&mut tx, &user, "reset_password", json!({ "url": url, "display_name": user.display_name })).await?;
|
||||
queue_password_link(&state, &mut tx, &user, "reset_password").await?;
|
||||
}
|
||||
tx.commit().await?;
|
||||
Ok(StatusCode::ACCEPTED)
|
||||
@@ -545,31 +559,38 @@ pub async fn request_password_reset(
|
||||
|
||||
#[derive(Deserialize)]
|
||||
#[serde(deny_unknown_fields)]
|
||||
pub struct ResetConfirmRequest {
|
||||
pub struct SetPasswordRequest {
|
||||
token: String,
|
||||
password: String,
|
||||
}
|
||||
|
||||
/// Sets a new password (adding the password login if the user had only
|
||||
/// Google) and ends all sessions.
|
||||
pub async fn confirm_password_reset(
|
||||
/// Sets the password with an e-mailed link (sign-up or forgotten password):
|
||||
/// the address counts as confirmed, every other session ends, and this one
|
||||
/// is logged in.
|
||||
pub async fn set_password_with_link(
|
||||
State(state): St,
|
||||
WithRejection(Json(req), _): Body<ResetConfirmRequest>,
|
||||
) -> ApiResult<StatusCode> {
|
||||
headers: HeaderMap,
|
||||
jar: CookieJar,
|
||||
WithRejection(Json(req), _): Body<SetPasswordRequest>,
|
||||
) -> ApiResult<impl IntoResponse> {
|
||||
password_login_enabled(&state)?;
|
||||
validate_password(&req.password)?;
|
||||
let hash = hash_password(req.password).await?;
|
||||
let mut tx = state.db.begin().await?;
|
||||
let user_id = consume_token(&mut tx, &req.token, "reset_password").await?;
|
||||
let user_id = consume_token(&mut tx, &req.token, &["verify_email", "reset_password"]).await?;
|
||||
set_password(&mut tx, user_id, &hash).await?;
|
||||
// The link arrived in the mailbox, so the address is verified.
|
||||
sqlx::query("UPDATE users SET email_verified_at = COALESCE(email_verified_at, now()) WHERE id = $1")
|
||||
.bind(user_id)
|
||||
.execute(&mut *tx)
|
||||
.await?;
|
||||
sqlx::query("DELETE FROM sessions WHERE user_id = $1").bind(user_id).execute(&mut *tx).await?;
|
||||
let mut user = load_user(&mut tx, user_id).await?;
|
||||
apply_bootstrap_admin(&state, &mut tx, &mut user).await?;
|
||||
tx.commit().await?;
|
||||
Ok(StatusCode::NO_CONTENT)
|
||||
state.login_limiter.succeeded(&user.email);
|
||||
|
||||
let session = create_session(&state.db, &state.config, user.id, user_agent(&headers)).await?;
|
||||
Ok(login_response(&state, jar, &user, session, false))
|
||||
}
|
||||
|
||||
/// Creates or replaces the password identity.
|
||||
|
||||
@@ -78,10 +78,8 @@ pub fn router(state: Arc<AppState>) -> Router {
|
||||
.route("/v1/auth/apple", post(auth::apple))
|
||||
.route("/v1/auth/logout", post(auth::logout))
|
||||
.route("/v1/auth/logout-all", post(auth::logout_all))
|
||||
.route("/v1/auth/verify-email", post(auth::verify_email))
|
||||
.route("/v1/auth/resend-verification", post(auth::resend_verification))
|
||||
.route("/v1/auth/password-reset", post(auth::request_password_reset))
|
||||
.route("/v1/auth/password-reset/confirm", post(auth::confirm_password_reset))
|
||||
.route("/v1/auth/set-password", post(auth::set_password_with_link))
|
||||
// own account (GDPR export and deletion included)
|
||||
.route("/v1/me", get(account::me).patch(account::update_me).delete(account::delete_me))
|
||||
.route("/v1/me/password", post(account::change_password))
|
||||
|
||||
+102
-70
@@ -278,17 +278,32 @@ impl TestApp {
|
||||
|
||||
/// Registers a user; returns the session token.
|
||||
async fn register(&self, email: &str, name: &str) -> String {
|
||||
self.register_with(json!({"email": email, "display_name": name})).await
|
||||
}
|
||||
|
||||
/// Signs up with `body` and sets the password through the e-mailed link;
|
||||
/// returns the session token.
|
||||
async fn register_with(&self, body: Value) -> String {
|
||||
let r = self.post("/v1/auth/register", None, body.clone()).await;
|
||||
assert_eq!(r.status, StatusCode::ACCEPTED, "{}", r.body);
|
||||
let email = body["email"].as_str().unwrap().trim().to_lowercase();
|
||||
let url = self.outbox_url(&email, "verify_email").await;
|
||||
let r = self
|
||||
.post(
|
||||
"/v1/auth/register",
|
||||
None,
|
||||
json!({"email": email, "password": "titkos-jelszo-123", "display_name": name}),
|
||||
)
|
||||
.post("/v1/auth/set-password", None, json!({"token": token_param(&url), "password": "titkos-jelszo-123"}))
|
||||
.await;
|
||||
assert_eq!(r.status, StatusCode::CREATED, "{}", r.body);
|
||||
assert_eq!(r.status, StatusCode::OK, "{}", r.body);
|
||||
r.body["session"]["token"].as_str().unwrap().to_string()
|
||||
}
|
||||
|
||||
async fn outbox_count(&self, email: &str, template: &str) -> i64 {
|
||||
sqlx::query_scalar("SELECT count(*) FROM email_outbox WHERE to_email = $1 AND template = $2")
|
||||
.bind(email)
|
||||
.bind(template)
|
||||
.fetch_one(&self.pool)
|
||||
.await
|
||||
.unwrap()
|
||||
}
|
||||
|
||||
/// An admin adds units to their own account (admins use units too).
|
||||
async fn add_own_units(&self, admin: &str, unit: &str, delta: i32) {
|
||||
let id = self.get("/v1/me", Some(admin)).await.body["user"]["id"].as_str().unwrap().to_string();
|
||||
@@ -333,38 +348,48 @@ fn token_param(url: &str) -> &str {
|
||||
#[sqlx::test(migrator = "db::MIGRATOR")]
|
||||
async fn register_login_verify_logout(pool: PgPool) {
|
||||
let app = TestApp::new(pool).await;
|
||||
let r = app
|
||||
.post("/v1/auth/register", None, json!({"email": "Anna@Example.com", "password": "titkos-jelszo-123"}))
|
||||
.await;
|
||||
assert_eq!(r.status, StatusCode::CREATED, "{}", r.body);
|
||||
// Sign-up takes no password: it is set through the e-mailed link.
|
||||
let r =
|
||||
app.post("/v1/auth/register", None, json!({"email": "x@example.com", "password": "titkos-jelszo-123"})).await;
|
||||
assert_eq!(r.status, StatusCode::BAD_REQUEST);
|
||||
let r = app.post("/v1/auth/register", None, json!({"email": "Anna@Example.com", "display_name": "Anna"})).await;
|
||||
assert_eq!((r.status, &r.body["sent"]), (StatusCode::ACCEPTED, &json!(true)), "{}", r.body);
|
||||
assert!(r.headers.get("set-cookie").is_none(), "no session before the link");
|
||||
let url = app.outbox_url("anna@example.com", "verify_email").await;
|
||||
assert!(url.starts_with("https://sorsfonalak.test/jelszo?token="));
|
||||
|
||||
// no login before the password is set
|
||||
let r =
|
||||
app.post("/v1/auth/login", None, json!({"email": "anna@example.com", "password": "titkos-jelszo-123"})).await;
|
||||
assert_eq!(r.status, StatusCode::UNAUTHORIZED);
|
||||
|
||||
// a too short password does not use up the link
|
||||
let set = |password: &'static str| {
|
||||
app.post("/v1/auth/set-password", None, json!({"token": token_param(&url), "password": password}))
|
||||
};
|
||||
assert_eq!(set("rovid").await.status, StatusCode::BAD_REQUEST);
|
||||
let r = set("titkos-jelszo-123").await;
|
||||
assert_eq!(r.status, StatusCode::OK, "{}", r.body);
|
||||
let cookie = r.headers.get("set-cookie").unwrap().to_str().unwrap();
|
||||
assert!(cookie.starts_with("sf_session=") && cookie.contains("HttpOnly") && cookie.contains("Secure"));
|
||||
assert_eq!(r.body["user"]["email"], "anna@example.com");
|
||||
assert_eq!(r.body["user"]["roles"], json!(["user"]));
|
||||
assert_eq!(r.body["user"]["email_verified"], false);
|
||||
assert_eq!(r.body["user"]["email_verified"], true);
|
||||
let token = r.body["session"]["token"].as_str().unwrap().to_string();
|
||||
|
||||
// duplicate, short password
|
||||
let r = app
|
||||
.post("/v1/auth/register", None, json!({"email": "anna@example.com", "password": "titkos-jelszo-123"}))
|
||||
.await;
|
||||
assert_eq!((r.status, r.body["error"]["code"].as_str()), (StatusCode::CONFLICT, Some("email_taken")));
|
||||
let r = app.post("/v1/auth/register", None, json!({"email": "b@example.com", "password": "rovid"})).await;
|
||||
assert_eq!(r.status, StatusCode::BAD_REQUEST);
|
||||
assert_eq!(set("masik-jelszo-123").await.body["error"]["code"], "invalid_token");
|
||||
|
||||
let r = app.get("/v1/me", Some(&token)).await;
|
||||
assert_eq!(r.status, StatusCode::OK);
|
||||
assert_eq!(r.body["providers"], json!(["password"]));
|
||||
assert_eq!(r.body["analyses_left"], json!({"natal": 0, "synastry": 0, "forecast": 0, "question": 0, "tarot": 0}));
|
||||
|
||||
// e-mail verification through the queued e-mail's link
|
||||
let url = app.outbox_url("anna@example.com", "verify_email").await;
|
||||
assert!(url.starts_with("https://sorsfonalak.test/verify-email?token="));
|
||||
let r = app.post("/v1/auth/verify-email", None, json!({"token": token_param(&url)})).await;
|
||||
assert_eq!(r.status, StatusCode::OK, "{}", r.body);
|
||||
let r = app.post("/v1/auth/verify-email", None, json!({"token": token_param(&url)})).await;
|
||||
assert_eq!(r.body["error"]["code"], "invalid_token");
|
||||
assert_eq!(app.get("/v1/me", Some(&token)).await.body["user"]["email_verified"], true);
|
||||
// signing up again with the address: the same answer, and the owner gets
|
||||
// a link instead (once a minute at most)
|
||||
for _ in 0..2 {
|
||||
let r = app.post("/v1/auth/register", None, json!({"email": "anna@example.com"})).await;
|
||||
assert_eq!(r.status, StatusCode::ACCEPTED);
|
||||
}
|
||||
assert_eq!(app.outbox_count("anna@example.com", "account_exists").await, 1);
|
||||
|
||||
// login
|
||||
let r =
|
||||
@@ -400,15 +425,25 @@ async fn password_reset_ends_sessions(pool: PgPool) {
|
||||
StatusCode::ACCEPTED
|
||||
);
|
||||
let url = app.outbox_url("anna@example.com", "reset_password").await;
|
||||
assert!(url.starts_with("https://sorsfonalak.test/jelszo?token="));
|
||||
let r = app
|
||||
.post(
|
||||
"/v1/auth/password-reset/confirm",
|
||||
None,
|
||||
json!({"token": token_param(&url), "password": "uj-titkos-jelszo-456"}),
|
||||
)
|
||||
.post("/v1/auth/set-password", None, json!({"token": token_param(&url), "password": "uj-titkos-jelszo-456"}))
|
||||
.await;
|
||||
assert_eq!(r.status, StatusCode::NO_CONTENT, "{}", r.body);
|
||||
assert_eq!(r.status, StatusCode::OK, "{}", r.body);
|
||||
let fresh = r.body["session"]["token"].as_str().unwrap().to_string();
|
||||
assert_eq!(app.get("/v1/me", Some(&token)).await.status, StatusCode::UNAUTHORIZED);
|
||||
assert_eq!(app.get("/v1/me", Some(&fresh)).await.status, StatusCode::OK);
|
||||
// the sign-up link cannot be used for it any more either
|
||||
let signup = app.outbox_url("anna@example.com", "verify_email").await;
|
||||
let r = app
|
||||
.post("/v1/auth/set-password", None, json!({"token": token_param(&signup), "password": "harmadik-jelszo-789"}))
|
||||
.await;
|
||||
assert_eq!(r.body["error"]["code"], "invalid_token");
|
||||
// a flood of requests sends one more link a minute at most
|
||||
for _ in 0..3 {
|
||||
app.post("/v1/auth/password-reset", None, json!({"email": "anna@example.com"})).await;
|
||||
}
|
||||
assert_eq!(app.outbox_count("anna@example.com", "reset_password").await, 1);
|
||||
let r = app
|
||||
.post("/v1/auth/login", None, json!({"email": "anna@example.com", "password": "uj-titkos-jelszo-456"}))
|
||||
.await;
|
||||
@@ -430,31 +465,49 @@ async fn google_login_creates_links_and_rejects(pool: PgPool) {
|
||||
.await;
|
||||
assert_eq!((r.status, &r.body["created"]), (StatusCode::OK, &json!(false)));
|
||||
|
||||
// an existing, confirmed password account with the same address gets Google linked
|
||||
// an existing password account with the same address gets Google linked
|
||||
// (its address was confirmed when the password was set)
|
||||
let token = app.register("anna@example.com", "Anna").await;
|
||||
sqlx::query("UPDATE users SET email_verified_at = now() WHERE email = 'anna@example.com'")
|
||||
.execute(&app.pool)
|
||||
.await
|
||||
.unwrap();
|
||||
let r = app
|
||||
.post("/v1/auth/google", None, json!({"id_token": google_token("g-2", "anna@example.com", GOOGLE_CLIENT)}))
|
||||
.await;
|
||||
assert_eq!((r.status, &r.body["created"]), (StatusCode::OK, &json!(false)));
|
||||
assert_eq!(app.get("/v1/me", Some(&token)).await.body["providers"], json!(["password", "google"]));
|
||||
|
||||
// an unconfirmed one may be someone else's: its password and sessions go
|
||||
let squatter = app.register("victim@example.com", "Valaki").await;
|
||||
// Someone signs up with another person's address: no password, no session.
|
||||
// When the owner comes with Google, the account is theirs, and the link
|
||||
// in their mailbox would only let them set their own password.
|
||||
let r = app.post("/v1/auth/register", None, json!({"email": "victim@example.com", "display_name": "Valaki"})).await;
|
||||
assert_eq!(r.status, StatusCode::ACCEPTED);
|
||||
let r = app
|
||||
.post("/v1/auth/google", None, json!({"id_token": google_token("g-4", "victim@example.com", GOOGLE_CLIENT)}))
|
||||
.await;
|
||||
assert_eq!(r.status, StatusCode::OK, "{}", r.body);
|
||||
let owner = r.body["session"]["token"].as_str().unwrap().to_string();
|
||||
assert_eq!(app.get("/v1/me", Some(&squatter)).await.status, StatusCode::UNAUTHORIZED);
|
||||
assert_eq!(app.get("/v1/me", Some(&owner)).await.body["providers"], json!(["google"]));
|
||||
let me = app.get("/v1/me", Some(&owner)).await.body;
|
||||
assert_eq!((&me["providers"], &me["user"]["email_verified"]), (&json!(["google"]), &json!(true)));
|
||||
let r =
|
||||
app.post("/v1/auth/login", None, json!({"email": "victim@example.com", "password": "titkos-jelszo-123"})).await;
|
||||
assert_eq!(r.status, StatusCode::UNAUTHORIZED);
|
||||
|
||||
// An unconfirmed password account from before the links (legacy) cannot
|
||||
// log in, and Google login removes its password and sessions.
|
||||
let legacy = app.register("old@example.com", "Régi").await;
|
||||
sqlx::query("UPDATE users SET email_verified_at = NULL WHERE email = 'old@example.com'")
|
||||
.execute(&app.pool)
|
||||
.await
|
||||
.unwrap();
|
||||
let r =
|
||||
app.post("/v1/auth/login", None, json!({"email": "old@example.com", "password": "titkos-jelszo-123"})).await;
|
||||
assert_eq!(r.status, StatusCode::UNAUTHORIZED);
|
||||
let r = app
|
||||
.post("/v1/auth/google", None, json!({"id_token": google_token("g-5", "old@example.com", GOOGLE_CLIENT)}))
|
||||
.await;
|
||||
assert_eq!(r.status, StatusCode::OK, "{}", r.body);
|
||||
assert_eq!(app.get("/v1/me", Some(&legacy)).await.status, StatusCode::UNAUTHORIZED);
|
||||
let owner = r.body["session"]["token"].as_str().unwrap().to_string();
|
||||
assert_eq!(app.get("/v1/me", Some(&owner)).await.body["providers"], json!(["google"]));
|
||||
|
||||
let r = app
|
||||
.post("/v1/auth/google", None, json!({"id_token": google_token("g-3", "x@gmail.com", "other-client")}))
|
||||
.await;
|
||||
@@ -769,15 +822,15 @@ async fn analyses_spend_units_and_reuse_results(pool: PgPool) {
|
||||
async fn password_login_can_be_disabled(pool: PgPool) {
|
||||
let app = TestApp::with_config(pool, |c| c.password_login = false).await;
|
||||
assert_eq!(app.get("/v1/config", None).await.body["password_login"], false);
|
||||
let r = app
|
||||
.post("/v1/auth/register", None, json!({"email": "anna@example.com", "password": "titkos-jelszo-123"}))
|
||||
.await;
|
||||
let r = app.post("/v1/auth/register", None, json!({"email": "anna@example.com"})).await;
|
||||
assert_eq!(r.status, StatusCode::FORBIDDEN);
|
||||
let r =
|
||||
app.post("/v1/auth/login", None, json!({"email": "anna@example.com", "password": "titkos-jelszo-123"})).await;
|
||||
assert_eq!(r.status, StatusCode::FORBIDDEN);
|
||||
let r = app.post("/v1/auth/password-reset", None, json!({"email": "anna@example.com"})).await;
|
||||
assert_eq!(r.status, StatusCode::FORBIDDEN);
|
||||
let r = app.post("/v1/auth/set-password", None, json!({"token": "x", "password": "titkos-jelszo-123"})).await;
|
||||
assert_eq!(r.status, StatusCode::FORBIDDEN);
|
||||
}
|
||||
|
||||
#[sqlx::test(migrator = "db::MIGRATOR")]
|
||||
@@ -880,7 +933,7 @@ async fn export_and_delete_account(pool: PgPool) {
|
||||
/// config and catalog, shared links, invitation pages, the waitlist and
|
||||
/// unsubscribing. Every other route (charts, calculations, analyses) needs a
|
||||
/// logged-in user, so other apps cannot use them.
|
||||
const PUBLIC_ROUTES: [&str; 17] = [
|
||||
const PUBLIC_ROUTES: [&str; 16] = [
|
||||
"/healthz",
|
||||
// Stripe calls it; the signature proves it.
|
||||
"/v1/payments/stripe/webhook",
|
||||
@@ -890,9 +943,8 @@ const PUBLIC_ROUTES: [&str; 17] = [
|
||||
"/v1/auth/login",
|
||||
"/v1/auth/google",
|
||||
"/v1/auth/apple",
|
||||
"/v1/auth/verify-email",
|
||||
"/v1/auth/password-reset",
|
||||
"/v1/auth/password-reset/confirm",
|
||||
"/v1/auth/set-password",
|
||||
"/v1/public/shares/{slug}",
|
||||
"/v1/public/shares/{slug}/visit",
|
||||
"/v1/public/invites/{token}",
|
||||
@@ -2296,20 +2348,7 @@ async fn a_new_user_from_a_shared_link_earns_an_analysis(pool: PgPool) {
|
||||
let before = natal(anna.clone()).await;
|
||||
let join = |email: String| {
|
||||
let (app, slug) = (&app, slug.clone());
|
||||
async move {
|
||||
let r = app
|
||||
.post(
|
||||
"/v1/auth/register",
|
||||
None,
|
||||
json!({"email": email, "password": "titkos-jelszo-123", "referral": slug}),
|
||||
)
|
||||
.await;
|
||||
assert_eq!(r.status, StatusCode::CREATED, "{}", r.body);
|
||||
r.body["token"].as_str().map(str::to_string).unwrap_or_else(|| {
|
||||
let cookie = r.headers.get("set-cookie").unwrap().to_str().unwrap();
|
||||
cookie.split(';').next().unwrap().split('=').nth(1).unwrap().to_string()
|
||||
})
|
||||
}
|
||||
async move { app.register_with(json!({"email": email, "referral": slug})).await }
|
||||
};
|
||||
|
||||
// signing up is not enough: the reward comes with their own chart
|
||||
@@ -2332,14 +2371,7 @@ async fn a_new_user_from_a_shared_link_earns_an_analysis(pool: PgPool) {
|
||||
|
||||
// nothing while the rewards are off
|
||||
let off = TestApp::with_config(pool, |c| c.referral_rewards = false).await;
|
||||
let r = off
|
||||
.post(
|
||||
"/v1/auth/register",
|
||||
None,
|
||||
json!({"email": "late@example.com", "password": "titkos-jelszo-123", "referral": slug}),
|
||||
)
|
||||
.await;
|
||||
assert_eq!(r.status, StatusCode::CREATED);
|
||||
off.register_with(json!({"email": "late@example.com", "referral": slug})).await;
|
||||
let count: i64 = sqlx::query_scalar(
|
||||
"SELECT count(*) FROM referrals r JOIN users u ON u.id = r.user_id WHERE u.email = 'late@example.com'",
|
||||
)
|
||||
|
||||
@@ -0,0 +1,203 @@
|
||||
"use client";
|
||||
|
||||
import { useRouter } from "next/navigation";
|
||||
import { useState } from "react";
|
||||
|
||||
import { Waitlist } from "@/components/Waitlist";
|
||||
import { ApiError, api, errorText } from "@/lib/api";
|
||||
|
||||
type Mode = "login" | "register" | "forgot";
|
||||
|
||||
function loginError(e: unknown): string {
|
||||
if (e instanceof ApiError) {
|
||||
if (e.code === "invalid_credentials") return "Hibás e-mail-cím vagy jelszó.";
|
||||
if (e.code === "too_many_requests") return "Túl sok sikertelen próbálkozás. Próbáld újra negyedóra múlva.";
|
||||
}
|
||||
return errorText(e);
|
||||
}
|
||||
|
||||
/**
|
||||
* E-mail and password: login, sign-up and forgotten password. Sign-up asks
|
||||
* no password: it is set through the link sent to the address, so nobody can
|
||||
* set a password for someone else's address.
|
||||
*/
|
||||
export function PasswordLogin({
|
||||
target,
|
||||
inviteToken = null,
|
||||
initialMode = "login",
|
||||
}: {
|
||||
target: string;
|
||||
inviteToken?: string | null;
|
||||
initialMode?: Mode;
|
||||
}) {
|
||||
const router = useRouter();
|
||||
const [mode, setMode] = useState<Mode>(initialMode);
|
||||
const [email, setEmail] = useState("");
|
||||
const [password, setPassword] = useState("");
|
||||
const [name, setName] = useState("");
|
||||
const [busy, setBusy] = useState(false);
|
||||
const [error, setError] = useState<string | null>(null);
|
||||
const [sent, setSent] = useState<Mode | null>(null);
|
||||
const [uninvited, setUninvited] = useState(false);
|
||||
|
||||
function switchTo(next: Mode) {
|
||||
setMode(next);
|
||||
setError(null);
|
||||
setSent(null);
|
||||
setUninvited(false);
|
||||
}
|
||||
|
||||
async function submit(e: React.FormEvent) {
|
||||
e.preventDefault();
|
||||
setBusy(true);
|
||||
setError(null);
|
||||
setUninvited(false);
|
||||
try {
|
||||
if (mode === "login") {
|
||||
await api("/auth/login", { body: { email, password } });
|
||||
router.replace(target);
|
||||
router.refresh();
|
||||
return;
|
||||
}
|
||||
if (mode === "register") {
|
||||
let referral: string | null = null;
|
||||
try {
|
||||
referral = localStorage.getItem("sf_ref");
|
||||
} catch {
|
||||
// storage blocked
|
||||
}
|
||||
await api("/auth/register", {
|
||||
body: { email, display_name: name.trim() || null, locale: "hu", invite_token: inviteToken, referral },
|
||||
});
|
||||
} else {
|
||||
await api("/auth/password-reset", { body: { email } });
|
||||
}
|
||||
setSent(mode);
|
||||
} catch (err) {
|
||||
if (err instanceof ApiError && err.code === "not_invited") setUninvited(true);
|
||||
else setError(mode === "login" ? loginError(err) : errorText(err));
|
||||
} finally {
|
||||
setBusy(false);
|
||||
}
|
||||
}
|
||||
|
||||
if (sent) {
|
||||
return (
|
||||
<div className="field pw-sent" role="status">
|
||||
<p className="msg msg-ok" style={{ margin: 0 }}>
|
||||
{sent === "register"
|
||||
? "Küldtünk egy levelet a(z) "
|
||||
: "Ha ehhez a címhez tartozik fiók, küldtünk egy levelet a(z) "}
|
||||
<strong>{email}</strong> címre. A benne lévő linkkel adhatod meg a jelszavad
|
||||
{sent === "register" ? ", és utána már be is vagy lépve." : "."}
|
||||
</p>
|
||||
<p className="hint" style={{ margin: 0 }}>
|
||||
Nem jött meg pár percen belül? Nézd meg a spam mappát is, vagy{" "}
|
||||
<button type="button" className="link-btn" onClick={() => switchTo(sent)}>
|
||||
próbáld újra
|
||||
</button>
|
||||
.
|
||||
</p>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
return (
|
||||
<form className="field pw-form" onSubmit={submit} style={{ gap: 14 }}>
|
||||
{mode === "register" && (
|
||||
<div className="field">
|
||||
<label htmlFor="pw-name">Név (nem kötelező)</label>
|
||||
<input
|
||||
id="pw-name"
|
||||
className="inp"
|
||||
autoComplete="name"
|
||||
maxLength={100}
|
||||
value={name}
|
||||
onChange={(e) => setName(e.target.value)}
|
||||
/>
|
||||
</div>
|
||||
)}
|
||||
<div className="field">
|
||||
<label htmlFor="pw-email">E-mail-cím</label>
|
||||
<input
|
||||
id="pw-email"
|
||||
className="inp"
|
||||
type="email"
|
||||
required
|
||||
autoComplete={mode === "login" ? "username" : "email"}
|
||||
value={email}
|
||||
onChange={(e) => setEmail(e.target.value)}
|
||||
placeholder="nev@pelda.hu"
|
||||
/>
|
||||
</div>
|
||||
{mode === "login" && (
|
||||
<div className="field">
|
||||
<div className="pw-label-row">
|
||||
<label htmlFor="pw-password">Jelszó</label>
|
||||
<button type="button" className="link-btn" onClick={() => switchTo("forgot")}>
|
||||
Elfelejtett jelszó?
|
||||
</button>
|
||||
</div>
|
||||
<input
|
||||
id="pw-password"
|
||||
className="inp"
|
||||
type="password"
|
||||
required
|
||||
autoComplete="current-password"
|
||||
value={password}
|
||||
onChange={(e) => setPassword(e.target.value)}
|
||||
/>
|
||||
</div>
|
||||
)}
|
||||
{mode === "register" && (
|
||||
<p className="hint" style={{ margin: 0 }}>
|
||||
A jelszavadat a levélben kapott linken adod meg. Így biztos, hogy a cím a tiéd.
|
||||
</p>
|
||||
)}
|
||||
{mode === "forgot" && (
|
||||
<p className="hint" style={{ margin: 0 }}>
|
||||
Küldünk egy linket, amellyel új jelszót adhatsz meg. Ha eddig Google- vagy Apple-fiókkal léptél be, így
|
||||
jelszót is beállíthatsz.
|
||||
</p>
|
||||
)}
|
||||
<button type="submit" className="btn btn-primary" disabled={busy}>
|
||||
{busy
|
||||
? "Küldés…"
|
||||
: mode === "login"
|
||||
? "Belépés"
|
||||
: mode === "register"
|
||||
? "Regisztráció"
|
||||
: "Link küldése"}
|
||||
</button>
|
||||
{error && (
|
||||
<p className="msg msg-error" role="alert" style={{ margin: 0 }}>
|
||||
{error}
|
||||
</p>
|
||||
)}
|
||||
{uninvited && (
|
||||
<>
|
||||
<p className="msg msg-error" role="alert" style={{ margin: 0 }}>
|
||||
{inviteToken
|
||||
? "Ez a meghívó már nem érvényes, és ehhez a címhez sem tartozik másik."
|
||||
: "A Sorsfonalak jelenleg meghívásos, és ehhez az e-mail-címhez nem tartozik meghívó. Ha kaptál meghívót, nyisd meg a levélben kapott linket."}
|
||||
</p>
|
||||
<Waitlist email={email} />
|
||||
</>
|
||||
)}
|
||||
<p className="hint pw-switch" style={{ margin: 0 }}>
|
||||
{mode === "login" ? (
|
||||
<>
|
||||
Még nincs fiókod?{" "}
|
||||
<button type="button" className="link-btn" onClick={() => switchTo("register")}>
|
||||
Regisztráció e-mail-címmel
|
||||
</button>
|
||||
</>
|
||||
) : (
|
||||
<button type="button" className="link-btn" onClick={() => switchTo("login")}>
|
||||
Vissza a belépéshez
|
||||
</button>
|
||||
)}
|
||||
</p>
|
||||
</form>
|
||||
);
|
||||
}
|
||||
@@ -10,6 +10,7 @@ import type { InvitationLanding, PublicConfig } from "@/lib/types";
|
||||
|
||||
import { AppleLogin } from "./AppleLogin";
|
||||
import { GoogleLogin } from "./GoogleLogin";
|
||||
import { PasswordLogin } from "./PasswordLogin";
|
||||
|
||||
export const metadata: Metadata = { title: "Belépés" };
|
||||
|
||||
@@ -48,7 +49,15 @@ const CLOSED: Record<string, string> = {
|
||||
};
|
||||
|
||||
/** The invitation the visitor came with: who sent it and what they wrote. */
|
||||
function InvitationCard({ invitation, apple }: { invitation: InvitationLanding | null; apple: boolean }) {
|
||||
function InvitationCard({
|
||||
invitation,
|
||||
apple,
|
||||
password,
|
||||
}: {
|
||||
invitation: InvitationLanding | null;
|
||||
apple: boolean;
|
||||
password: boolean;
|
||||
}) {
|
||||
if (!invitation) {
|
||||
return (
|
||||
<p className="msg msg-error" role="alert">
|
||||
@@ -71,7 +80,9 @@ function InvitationCard({ invitation, apple }: { invitation: InvitationLanding |
|
||||
</p>
|
||||
{invitation.message && <blockquote className="invite-quote">{invitation.message}</blockquote>}
|
||||
<p className="hint" style={{ margin: 0 }}>
|
||||
Bármelyik {apple ? "Google- vagy Apple-fiókoddal" : "Google-fiókoddal"} elfogadhatod. Érvényes: {formatDate(invitation.expires_at).replace(/\.$/, "")}-ig.
|
||||
Bármelyik {apple ? "Google- vagy Apple-fiókoddal" : "Google-fiókoddal"}
|
||||
{password ? ", vagy e-mail-címmel regisztrálva" : ""} elfogadhatod. Érvényes:{" "}
|
||||
{formatDate(invitation.expires_at).replace(/\.$/, "")}-ig.
|
||||
</p>
|
||||
</div>
|
||||
);
|
||||
@@ -91,6 +102,9 @@ export default async function LoginPage({ searchParams }: { searchParams: Promis
|
||||
const appleId = config?.apple_login?.enabled ? config.apple_login.client_id : null;
|
||||
const pendingInvite = invitation?.status === "pending" ? inviteToken : null;
|
||||
const inviteOnly = config?.signup_mode === "invite";
|
||||
const password = config?.password_login === true;
|
||||
const mod = Array.isArray(params.mod) ? params.mod[0] : params.mod;
|
||||
const initialMode = mod === "elfelejtett" ? "forgot" : mod === "regisztracio" || rawToken ? "register" : "login";
|
||||
|
||||
return (
|
||||
<div className="auth">
|
||||
@@ -114,16 +128,28 @@ export default async function LoginPage({ searchParams }: { searchParams: Promis
|
||||
<h1 style={{ fontSize: 44 }}>{rawToken ? "Meghívó" : "Belépés"}</h1>
|
||||
<p className="muted">{rawToken ? "Lépj be, és már kezdheted is." : "Üdv újra! Lépj be a fiókodba."}</p>
|
||||
</div>
|
||||
{rawToken && <InvitationCard invitation={inviteToken ? invitation : null} apple={appleId !== null} />}
|
||||
{rawToken && (
|
||||
<InvitationCard invitation={inviteToken ? invitation : null} apple={appleId !== null} password={password} />
|
||||
)}
|
||||
{config === null ? (
|
||||
<p className="msg msg-error" role="alert">
|
||||
A szerver most nem érhető el. Próbáld újra egy kicsit később.
|
||||
</p>
|
||||
) : clientId ? (
|
||||
) : clientId || password ? (
|
||||
<>
|
||||
{clientId && (
|
||||
<div className="field" style={{ gap: 12 }}>
|
||||
<GoogleLogin clientId={clientId} target={target} inviteToken={pendingInvite} />
|
||||
{appleId && <AppleLogin clientId={appleId} target={target} inviteToken={pendingInvite} />}
|
||||
</div>
|
||||
)}
|
||||
{clientId && password && (
|
||||
<div className="auth-or" role="separator">
|
||||
<span>vagy</span>
|
||||
</div>
|
||||
)}
|
||||
{password && <PasswordLogin target={target} inviteToken={pendingInvite} initialMode={initialMode} />}
|
||||
</>
|
||||
) : (
|
||||
<p className="msg msg-error" role="alert">
|
||||
A Google-belépés még nincs beállítva (a backend <code>GOOGLE_CLIENT_IDS</code> változója üres).
|
||||
@@ -134,6 +160,8 @@ export default async function LoginPage({ searchParams }: { searchParams: Promis
|
||||
? "A fiókod az első belépéskor jön létre."
|
||||
: inviteOnly
|
||||
? "Az oldal jelenleg meghívásos: új fiók csak meghívóval jön létre."
|
||||
: password
|
||||
? "Google- vagy Apple-fiókkal az első belépéskor létrejön a fiókod."
|
||||
: "Még nincs fiókod? Az első belépéskor létrejön."}
|
||||
</p>
|
||||
<p className="hint">
|
||||
|
||||
@@ -198,6 +198,18 @@ td.num { font-variant-numeric: tabular-nums; white-space: nowrap; }
|
||||
.tagline { font-family: var(--font-display); font-size: 38px; font-weight: 600; line-height: 1.1; }
|
||||
.auth-foot { font-size: 15px; color: var(--muted); text-align: center; }
|
||||
|
||||
/* E-mail and password next to the social buttons */
|
||||
.auth-or { display: flex; align-items: center; gap: 14px; color: var(--muted); font-size: 13px; margin: -6px 0; }
|
||||
.auth-or::before, .auth-or::after { content: ""; flex: 1; border-top: 1px solid var(--line); }
|
||||
.pw-label-row { display: flex; align-items: baseline; justify-content: space-between; gap: 12px; }
|
||||
.pw-switch { text-align: center; }
|
||||
.link-btn {
|
||||
background: none; border: 0; padding: 0; font: inherit; color: var(--gold); cursor: pointer;
|
||||
text-decoration: underline; text-underline-offset: 2px;
|
||||
}
|
||||
.link-btn:hover { color: var(--gold-hover); }
|
||||
.pw-label-row .link-btn { font-size: 13px; text-decoration: none; }
|
||||
|
||||
/* Social login buttons; Google's own button lies invisibly on top (.gsi-overlay). */
|
||||
.social-login { position: relative; }
|
||||
.btn-social {
|
||||
|
||||
@@ -0,0 +1,92 @@
|
||||
"use client";
|
||||
|
||||
import Link from "next/link";
|
||||
import { useRouter } from "next/navigation";
|
||||
import { useState } from "react";
|
||||
|
||||
import { ApiError, api, errorText } from "@/lib/api";
|
||||
|
||||
/** Sets the password with the e-mailed link's token; logs in on success. */
|
||||
export function SetPasswordForm({ token, minLength }: { token: string; minLength: number }) {
|
||||
const router = useRouter();
|
||||
const [password, setPassword] = useState("");
|
||||
const [again, setAgain] = useState("");
|
||||
const [busy, setBusy] = useState(false);
|
||||
const [error, setError] = useState<string | null>(null);
|
||||
const [expired, setExpired] = useState(false);
|
||||
|
||||
async function submit(e: React.FormEvent) {
|
||||
e.preventDefault();
|
||||
setError(null);
|
||||
if (password.length < minLength) {
|
||||
setError(`A jelszó legalább ${minLength} karakter legyen.`);
|
||||
return;
|
||||
}
|
||||
if (password !== again) {
|
||||
setError("A két jelszó nem egyezik.");
|
||||
return;
|
||||
}
|
||||
setBusy(true);
|
||||
try {
|
||||
await api("/auth/set-password", { body: { token, password } });
|
||||
router.replace("/");
|
||||
router.refresh();
|
||||
} catch (err) {
|
||||
if (err instanceof ApiError && err.code === "invalid_token") setExpired(true);
|
||||
else setError(errorText(err));
|
||||
setBusy(false);
|
||||
}
|
||||
}
|
||||
|
||||
if (expired) {
|
||||
return (
|
||||
<div className="field" role="alert">
|
||||
<p className="msg msg-error" style={{ margin: 0 }}>
|
||||
Ez a link lejárt, vagy már felhasználták.
|
||||
</p>
|
||||
<p className="hint" style={{ margin: 0 }}>
|
||||
A <Link href="/belepes?mod=elfelejtett">belépésnél</Link> az „Elfelejtett jelszó?” linkkel kérhetsz újat.
|
||||
</p>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
return (
|
||||
<form className="field" onSubmit={submit} style={{ gap: 14 }}>
|
||||
<div className="field">
|
||||
<label htmlFor="new-password">Új jelszó</label>
|
||||
<input
|
||||
id="new-password"
|
||||
className="inp"
|
||||
type="password"
|
||||
required
|
||||
minLength={minLength}
|
||||
autoComplete="new-password"
|
||||
value={password}
|
||||
onChange={(e) => setPassword(e.target.value)}
|
||||
/>
|
||||
<span className="hint">Legalább {minLength} karakter.</span>
|
||||
</div>
|
||||
<div className="field">
|
||||
<label htmlFor="new-password-again">Új jelszó még egyszer</label>
|
||||
<input
|
||||
id="new-password-again"
|
||||
className="inp"
|
||||
type="password"
|
||||
required
|
||||
autoComplete="new-password"
|
||||
value={again}
|
||||
onChange={(e) => setAgain(e.target.value)}
|
||||
/>
|
||||
</div>
|
||||
<button type="submit" className="btn btn-primary" disabled={busy}>
|
||||
{busy ? "Mentés…" : "Jelszó mentése és belépés"}
|
||||
</button>
|
||||
{error && (
|
||||
<p className="msg msg-error" role="alert" style={{ margin: 0 }}>
|
||||
{error}
|
||||
</p>
|
||||
)}
|
||||
</form>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,53 @@
|
||||
import type { Metadata } from "next";
|
||||
import Link from "next/link";
|
||||
|
||||
import { Logo } from "@/components/SiteHeader";
|
||||
import { BACKEND_URL } from "@/lib/server";
|
||||
import type { PublicConfig } from "@/lib/types";
|
||||
|
||||
import { SetPasswordForm } from "./SetPasswordForm";
|
||||
|
||||
export const metadata: Metadata = { title: "Jelszó megadása", robots: { index: false } };
|
||||
|
||||
async function minLength(): Promise<number> {
|
||||
try {
|
||||
const res = await fetch(`${BACKEND_URL}/v1/config`, { cache: "no-store" });
|
||||
if (res.ok) return ((await res.json()) as PublicConfig).password_min_length;
|
||||
} catch {
|
||||
// backend down: the form still works, the backend checks the length
|
||||
}
|
||||
return 10;
|
||||
}
|
||||
|
||||
/** The page of the e-mailed password link (sign-up and forgotten password). */
|
||||
export default async function SetPasswordPage({
|
||||
searchParams,
|
||||
}: {
|
||||
searchParams: Promise<Record<string, string | string[]>>;
|
||||
}) {
|
||||
const params = await searchParams;
|
||||
const raw = Array.isArray(params.token) ? params.token[0] : params.token;
|
||||
const token = raw && /^[A-Za-z0-9_-]{8,200}$/.test(raw) ? raw : null;
|
||||
|
||||
return (
|
||||
<div className="auth">
|
||||
<main className="auth-main">
|
||||
<div className="auth-box">
|
||||
<Logo />
|
||||
<div className="page-head">
|
||||
<h1 style={{ fontSize: 40 }}>Jelszó megadása</h1>
|
||||
<p className="muted">Add meg a jelszavad, amellyel ezentúl belépsz.</p>
|
||||
</div>
|
||||
{token ? (
|
||||
<SetPasswordForm token={token} minLength={await minLength()} />
|
||||
) : (
|
||||
<p className="msg msg-error" role="alert">
|
||||
Hiányos a link. Nyisd meg a teljes linket a levélből, vagy kérj újat a{" "}
|
||||
<Link href="/belepes?mod=elfelejtett">belépésnél</Link>.
|
||||
</p>
|
||||
)}
|
||||
</div>
|
||||
</main>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
@@ -7,18 +7,19 @@ use crate::templates::{TemplateError, render};
|
||||
|
||||
#[test]
|
||||
fn templates_in_both_languages() {
|
||||
let payload = json!({"url": "https://example.com/verify-email?token=abc", "display_name": "Anna"});
|
||||
let payload = json!({"url": "https://example.com/jelszo?token=abc", "display_name": "Anna"});
|
||||
let hu = render("verify_email", "hu", &payload).unwrap();
|
||||
assert_eq!(hu.subject, "Erősítsd meg az e-mail-címed");
|
||||
assert_eq!(hu.subject, "Add meg a jelszavad");
|
||||
assert!(hu.text.starts_with("Szia Anna!") && hu.text.contains("token=abc"));
|
||||
assert!(
|
||||
hu.html.contains(r#"<html lang="hu">"#)
|
||||
&& hu.html.contains(r#"href="https://example.com/verify-email?token=abc""#)
|
||||
hu.html.contains(r#"<html lang="hu">"#) && hu.html.contains(r#"href="https://example.com/jelszo?token=abc""#)
|
||||
);
|
||||
|
||||
let en = render("reset_password", "en", &payload).unwrap();
|
||||
assert_eq!(en.subject, "Set a new password");
|
||||
assert!(en.text.starts_with("Hi Anna,"));
|
||||
let exists = render("account_exists", "hu", &payload).unwrap();
|
||||
assert_eq!(exists.subject, "Már van fiókod a Sorsfonalakon");
|
||||
// Unknown locales fall back to English.
|
||||
assert_eq!(render("reset_password", "de", &payload).unwrap(), en);
|
||||
|
||||
|
||||
Reference in New Issue
Block a user