auth: e-mail + password login with e-mailed password links
CI / test (push) Failing after 1m39s
CI / build (push) Skipped
CI / deploy (push) Skipped

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:
feco
2026-11-21 18:24:48 +00:00
co-authored by Claude Opus 5.5
parent a63f8f9928
commit 7d6a6c3d92
11 changed files with 651 additions and 192 deletions
+115 -94
View File
@@ -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,57 +221,57 @@ 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)")
.bind(user_id)
.bind(&email)
.bind(clean_name(req.display_name))
.bind(&locale)
.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,
&email,
req.invite_token.as_deref(),
state.config.free_person_slots,
)
.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?;
}
}
super::invitations::admit(&state, &mut tx, &email, req.invite_token.as_deref()).await?;
let user_id = Uuid::now_v7();
sqlx::query("INSERT INTO users (id, email, display_name, locale) VALUES ($1, $2, $3, $4)")
.bind(user_id)
.bind(&email)
.bind(clean_name(req.display_name))
.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?;
super::invitations::mark_accepted(
&mut tx,
user_id,
&email,
req.invite_token.as_deref(),
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?;
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.
+1 -3
View File
@@ -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
View File
@@ -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'",
)