Register: auto sign-in to /me and speed/cleanup improvements

- Send the verification email after the response via after() so it
  never blocks sign-up
- Invalidate the cached login lookup right after account creation so
  the automatic sign-in always finds the fresh row
- Auto sign in with the submitted credentials and go straight to /me,
  with a fallback to /login?registered=1 if sign-in is refused (e.g.
  email verification required)
- Cache the register page's online/latest user queries to cut DB load
  under traffic
- Fix terms checkbox label double-toggle cancelling the selection
- Add pages.register.redirecting translation to all locales
This commit is contained in:
openhands committed 2026-08-26 14:57:51 +02:00
1 parent 2d09a4a92c
commit f25a26a93e
25 files changed
+143 -53

No files matched your search

+46 -24
View File
@@ -1,10 +1,11 @@
"use server";
import { count, eq } from "drizzle-orm";
import { redirect } from "next/navigation";
import { after } from "next/server";
import { z } from "zod";
import { sendVerification } from "@/actions/email-verify";
import { hashPassword } from "@/lib/auth/password";
import { invalidateKey } from "@/lib/cached-db";
import { db, User } from "@/lib/db";
import { logger } from "@/lib/logger";
import { clientIp, rateLimit } from "@/lib/rate-limit";
@@ -36,10 +37,16 @@ const registerSchema = z.object({
// A valid starter Habbo figure so the avatar renders in-client immediately.
const DEFAULT_LOOK = "hr-100-.hd-180-1.ch-255-66.lg-280-110.sh-305-62";
export interface RegisterState {
error: string | null;
ok: boolean;
}
export async function register(
_prevState: string | null,
_prevState: RegisterState,
formData: FormData,
): Promise<string | null> {
): Promise<RegisterState> {
const fail = (error: string): RegisterState => ({ error, ok: false });
const raw = {
username: String(formData.get("username") ?? "")
.normalize("NFC")
@@ -61,11 +68,11 @@ export async function register(
const parsed = registerSchema.safeParse(raw);
if (!parsed.success) {
return parsed.error.issues[0]?.message ?? "Invalid input";
return fail(parsed.error.issues[0]?.message ?? "Invalid input");
}
if (parsed.data.password !== parsed.data.passwordConfirmation) {
return "Passwords do not match";
return fail("Passwords do not match");
}
const { username, mail, password, look } = parsed.data;
@@ -74,7 +81,9 @@ export async function register(
// Throttle sign-ups per IP (5 per 10 minutes) to curb account spam.
if (!(await rateLimit(`register:${ip}`, 5, 10 * 60_000)).ok) {
return "Too many sign-up attempts. Please wait a few minutes and try again.";
return fail(
"Too many sign-up attempts. Please wait a few minutes and try again.",
);
}
// CAPTCHA (Turnstile / reCAPTCHA) — only enforced when configured in settings.
@@ -82,18 +91,18 @@ export async function register(
if (cfg.provider !== "none") {
const token = String(formData.get(cfg.field) ?? "").normalize("NFC");
if (!(await verifyCaptcha(token, ip)))
return "Captcha verification failed. Please try again.";
return fail("Captcha verification failed. Please try again.");
}
// Terms acceptance check.
if (!raw.termsAccepted)
return "You must accept the terms and conditions to register.";
return fail("You must accept the terms and conditions to register.");
// VPN/proxy block (only when enabled in /admin/vpn).
if ((await checkVpn(ip)).blocked) {
return (
return fail(
(await siteSettings.get("vpn_block_message", "")) ||
"Registrations from VPN/proxy connections are not allowed."
"Registrations from VPN/proxy connections are not allowed.",
);
}
@@ -106,7 +115,9 @@ export async function register(
.where(eq(User.ipRegister, ip))
.catch(() => [{ total: 0 }]);
if (Number(row?.total ?? 0) >= max)
return "You have reached the maximum number of accounts for your connection.";
return fail(
"You have reached the maximum number of accounts for your connection.",
);
}
// Uniqueness check.
@@ -116,10 +127,10 @@ export async function register(
.from(User)
.where(eq(User.username, username))
.limit(1);
if (existing) return "That username is already taken";
if (existing) return fail("That username is already taken");
} catch {
logger.warn("Username uniqueness check failed during registration");
return "Registration is temporarily unavailable";
return fail("Registration is temporarily unavailable");
}
const now = Math.floor(Date.now() / 1000);
@@ -134,25 +145,36 @@ export async function register(
look,
termsAccepted: raw.termsAccepted,
});
if (hasEmail) {
try {
await sendVerification(mail);
} catch {
logger.warn("Failed to send verification email after registration");
}
}
} catch (err) {
const code = (err as { cause?: { code?: string } }).cause?.code;
if (code === "ER_DUP_ENTRY") {
return "That username is already taken";
return fail("That username is already taken");
}
logger.error("Account creation failed", {
code,
message: err instanceof Error ? err.message : String(err),
});
return "Could not create the account. Please try again or contact staff.";
return fail(
"Could not create the account. Please try again or contact staff.",
);
}
redirect("/login?registered=1");
// The login lookup is cached for 15s — drop any stale entry so the
// immediate auto sign-in sees the fresh row.
await invalidateKey(`login:user:${username}`);
// Verification email must never block the sign-up response — it is sent
// after the response is flushed (no-op when mail is unconfigured).
if (hasEmail) {
after(async () => {
try {
await sendVerification(mail);
} catch {
logger.warn("Failed to send verification email after registration");
}
});
}
// Client auto signs in with these credentials and navigates to /me.
return { error: null, ok: true };
}
+14 -12
View File
@@ -33,18 +33,20 @@ export default async function RegisterPage() {
.where(eq(User.online, "1"))
.then((rows) => rows[0]?.total ?? 0),
).catch(() => 0),
db
.select({ username: User.username, look: User.look })
.from(User)
.where(eq(User.online, "1"))
.limit(8)
.catch(() => []),
db
.select({ username: User.username, look: User.look })
.from(User)
.orderBy(desc(User.accountCreated))
.limit(8)
.catch(() => []),
cached("register_online_users", 10_000, () =>
db
.select({ username: User.username, look: User.look })
.from(User)
.where(eq(User.online, "1"))
.limit(8),
).catch(() => []),
cached("register_latest_users", 30_000, () =>
db
.select({ username: User.username, look: User.look })
.from(User)
.orderBy(desc(User.accountCreated))
.limit(8),
).catch(() => []),
]);
return (
+61 -17
View File
@@ -3,9 +3,11 @@
import Image from "next/image";
import Link from "next/link";
import Script from "next/script";
import { signIn } from "next-auth/react";
import { useTranslations } from "next-intl";
import { useActionState, useState } from "react";
import { register } from "@/actions/register";
import { useActionState, useEffect, useRef, useState } from "react";
import { type RegisterState, register } from "@/actions/register";
import { signInWithTransientRetry } from "@/lib/auth/sign-in-retry";
interface RegisterFormProps {
hotelName: string;
@@ -40,13 +42,56 @@ export function RegisterForm({
}: RegisterFormProps) {
const t = useTranslations("pages.register");
const showCaptcha = captcha.provider !== "none" && !!captcha.siteKey;
const [serverError, formAction, isPending] = useActionState(register, null);
const [state, formAction, isPending] = useActionState<
RegisterState,
FormData
>(register, { error: null, ok: false });
const [termsAccepted, setTermsAccepted] = useState(false);
const [password, setPassword] = useState("");
const [showPassword, setShowPassword] = useState(false);
const [showConfirm, setShowConfirm] = useState(false);
const [signingIn, setSigningIn] = useState(false);
const credentialsRef = useRef<{ username: string; password: string } | null>(
null,
);
const autoLoginStartedRef = useRef(false);
const strength = passwordStrength(password);
// Successful sign-up: sign in with the submitted credentials and go
// straight to /me. If the automatic sign-in is refused (e.g. email
// verification required), fall back to the regular login page.
useEffect(() => {
if (!state.ok || autoLoginStartedRef.current) return;
autoLoginStartedRef.current = true;
const creds = credentialsRef.current;
if (!creds) {
window.location.href = "/login?registered=1";
return;
}
let cancelled = false;
setSigningIn(true);
(async () => {
try {
const res = await signInWithTransientRetry(() =>
signIn("credentials", { ...creds, code: "", redirect: false }),
);
if (!cancelled && res && !res.error) {
window.location.href = "/me";
return;
}
} catch {
/* fall through to fallback below */
}
if (!cancelled) window.location.href = "/login?registered=1";
})();
return () => {
cancelled = true;
};
}, [state.ok]);
return (
<div className="mx-auto w-full max-w-[800px]">
{showCaptcha && captcha.provider === "turnstile" ? (
@@ -112,7 +157,13 @@ export function RegisterForm({
{/* Form */}
<form
action={formAction}
action={(fd) => {
credentialsRef.current = {
username: String(fd.get("username") ?? "").trim(),
password: String(fd.get("password") ?? ""),
};
formAction(fd);
}}
className="p-6 flex flex-col gap-6"
style={{
backgroundColor:
@@ -120,12 +171,12 @@ export function RegisterForm({
borderRadius: "0 0 12px 12px",
}}
>
{(error || serverError) && (
{(error || state.error) && (
<div
className="animate-fade-in-up p-3 rounded-lg text-sm font-semibold text-white"
style={{ backgroundColor: "var(--color-danger)" }}
>
{error || serverError}
{error || state.error}
</div>
)}
@@ -301,14 +352,7 @@ export function RegisterForm({
/>
<label
htmlFor="terms"
className="font-medium text-sm text-[var(--color-text-readable)]"
onClick={() => setTermsAccepted(!termsAccepted)}
onKeyDown={(e) => {
if (e.key === "Enter" || e.key === " ") {
e.preventDefault();
setTermsAccepted(!termsAccepted);
}
}}
className="font-medium text-sm text-[var(--color-text-readable)] cursor-pointer"
>
{t("termsAccept", { hotel: hotelName })}
</label>
@@ -332,7 +376,7 @@ export function RegisterForm({
{/* Submit */}
<button
type="submit"
disabled={isPending}
disabled={isPending || signingIn}
className="btn-shine w-full rounded-xl font-extrabold text-sm py-3.5 transition-all duration-200 hover:scale-[1.02] active:scale-95 shadow-lg disabled:opacity-60"
style={{
background: "var(--color-primary)",
@@ -341,7 +385,7 @@ export function RegisterForm({
"0 4px 24px color-mix(in srgb, var(--color-primary) 35%, transparent)",
}}
>
{isPending ? (
{isPending || signingIn ? (
<span className="inline-flex items-center justify-center gap-2">
<svg
className="animate-spin h-4 w-4"
@@ -364,7 +408,7 @@ export function RegisterForm({
d="M4 12a8 8 0 018-8V0C5.373 0 0 5.373 0 12h4z"
/>
</svg>
{t("creatingAccount")}
{signingIn ? t("redirecting") : t("creatingAccount")}
</span>
) : (
t("createAccount")
+1
View File
@@ -754,6 +754,7 @@
"termsAccept": "Аз съм на 18+ и приемам условията и правилата на {hotel}.",
"createAccount": "Създаване на акаунт",
"creatingAccount": "Създаване на акаунт...",
"redirecting": "Прехвърляне към вашия акаунт...",
"alreadyHaveAccount": "Вече имате акаунт? Вход!",
"register": "Регистрирайте се",
"termsError": "Трябва да приемете условията и правилата, за да се регистрирате.",
+1
View File
@@ -754,6 +754,7 @@
"termsAccept": "Je mi 18+ a souhlasím s podmínkami a pravidly {hotel}.",
"createAccount": "Vytvořit účet",
"creatingAccount": "Vytváření účtu...",
"redirecting": "Přesměrovávám na váš účet...",
"alreadyHaveAccount": "Už máte účet? Přihlášení!",
"register": "Zaregistrujte se",
"termsError": "Chcete-li se zaregistrovat, musíte přijmout podmínky a pravidla.",
+1
View File
@@ -754,6 +754,7 @@
"termsAccept": "Jeg er 18+ og accepterer vilkårene og reglerne for {hotel}.",
"createAccount": "Opret konto",
"creatingAccount": "Opretter konto...",
"redirecting": "Omdirigerer til din konto...",
"alreadyHaveAccount": "Har du allerede en konto? Log ind!",
"register": "Tilmeld dig",
"termsError": "Du skal acceptere vilkårene og reglerne for at registrere dig.",
+1
View File
@@ -724,6 +724,7 @@
"termsAccept": "Ich bin 18+ und akzeptiere die {hotel} AGB & Regeln.",
"createAccount": "Konto erstellen",
"creatingAccount": "Konto wird erstellt...",
"redirecting": "Weiterleitung zu deinem Account...",
"alreadyHaveAccount": "Bereits ein Konto? Anmelden!",
"register": "Registrieren",
"termsError": "Du musst die AGB & Regeln akzeptieren, um dich zu registrieren.",
+1
View File
@@ -754,6 +754,7 @@
"termsAccept": "Είμαι 18+ και αποδέχομαι τους όρους και τους κανόνες του {hotel}.",
"createAccount": "Δημιουργία λογαριασμού",
"creatingAccount": "Δημιουργία λογαριασμού...",
"redirecting": "Ανακατεύθυνση στον λογαριασμό σας...",
"alreadyHaveAccount": "Έχετε ήδη λογαριασμό; Σύνδεση!",
"register": "Εγγραφή",
"termsError": "Πρέπει να αποδεχτείτε τους όρους και τους κανόνες για να εγγραφείτε.",
+1
View File
@@ -903,6 +903,7 @@
"termsAccept": "I am 18+ and accept the {hotel} terms & rules.",
"createAccount": "Create account",
"creatingAccount": "Creating account...",
"redirecting": "Redirecting to your account...",
"alreadyHaveAccount": "Already have an account? Login!",
"alreadyHaveAccountPre": "Already have an account?",
"alreadyHaveAccountLink": "Sign in",
+1
View File
@@ -724,6 +724,7 @@
"termsAccept": "Soy mayor de 18 años y acepto los términos y reglas de {hotel}.",
"createAccount": "Crear cuenta",
"creatingAccount": "Creando cuenta...",
"redirecting": "Redirigiendo a tu cuenta...",
"alreadyHaveAccount": "¿Ya tienes una cuenta? ¡Inicia sesión!",
"register": "Registrarse",
"termsError": "Debes aceptar los términos y reglas para registrarte.",
+1
View File
@@ -724,6 +724,7 @@
"termsAccept": "J'ai 18 ans ou plus et j'accepte les conditions et règles de {hotel}.",
"createAccount": "Créer un compte",
"creatingAccount": "Création du compte...",
"redirecting": "Redirection vers votre compte...",
"alreadyHaveAccount": "Vous avez déjà un compte ? Connectez-vous !",
"register": "S'inscrire",
"termsError": "Vous devez accepter les conditions et règles pour vous inscrire.",
+1
View File
@@ -754,6 +754,7 @@
"termsAccept": "Imam 18+ godina i prihvaćam odredbe i pravila hotela {hotel}.",
"createAccount": "Napravi račun",
"creatingAccount": "Izrada računa...",
"redirecting": "Preusmjeravanje na vaš račun...",
"alreadyHaveAccount": "Već imate račun? Prijava!",
"register": "Registrirajte se",
"termsError": "Za registraciju morate prihvatiti uvjete i pravila.",
+1
View File
@@ -754,6 +754,7 @@
"termsAccept": "18 évesnél idősebb vagyok, és elfogadom a {hotel} feltételeit és szabályait.",
"createAccount": "Hozzon létre fiókot",
"creatingAccount": "Fiók létrehozása...",
"redirecting": "Átirányítás a fiókjához...",
"alreadyHaveAccount": "Már van fiókja? Bejelentkezés!",
"register": "Regisztráció",
"termsError": "A regisztrációhoz el kell fogadnia a feltételeket és szabályokat.",
+1
View File
@@ -877,6 +877,7 @@
"termsAccept": "Ho 18+ anni e accetto i termini e regole di {hotel}.",
"createAccount": "Crea account",
"creatingAccount": "Creazione account...",
"redirecting": "Reindirizzamento al tuo account...",
"alreadyHaveAccount": "Hai già un account? Accedi!",
"register": "Registrati",
"termsError": "Devi accettare i termini e regole per registrarti.",
+1
View File
@@ -907,6 +907,7 @@
"termsAccept": "Ik ben 18+ en accepteer de {hotel} voorwaarden & regels.",
"createAccount": "Account aanmaken",
"creatingAccount": "Account wordt aangemaakt...",
"redirecting": "Doorgaan naar je account...",
"alreadyHaveAccount": "Al een account? Inloggen!",
"register": "Registreren",
"alreadyHaveAccountPre": "Al een account?",
+1
View File
@@ -754,6 +754,7 @@
"termsAccept": "Jeg er 18+ og godtar vilkårene og reglene for {hotel}.",
"createAccount": "Opprett konto",
"creatingAccount": "Oppretter konto ...",
"redirecting": "Videre til kontoen din...",
"alreadyHaveAccount": "Har du allerede en konto? Logg inn!",
"register": "Registrer deg",
"termsError": "Du må godta vilkårene og reglene for å registrere deg.",
+1
View File
@@ -754,6 +754,7 @@
"termsAccept": "Mam ukończone 18 lat i akceptuję warunki i zasady hotelu {hotel}.",
"createAccount": "Utwórz konto",
"creatingAccount": "Tworzenie konta...",
"redirecting": "Przekierowywanie na twoje konto...",
"alreadyHaveAccount": "Masz już konto? Login!",
"register": "Zarejestruj się",
"termsError": "Aby się zarejestrować, musisz zaakceptować regulamin.",
+1
View File
@@ -754,6 +754,7 @@
"termsAccept": "Tenho mais de 18 anos e aceito os termos e regras do {hotel}.",
"createAccount": "Criar conta",
"creatingAccount": "Criando conta...",
"redirecting": "A redirecionar para a sua conta...",
"alreadyHaveAccount": "Já tem uma conta? Conecte-se!",
"register": "Cadastre-se",
"termsError": "Você deve aceitar os termos e regras para se registrar.",
+1
View File
@@ -754,6 +754,7 @@
"termsAccept": "Am peste 18 ani și accept termenii și regulile {hotel}.",
"createAccount": "Creați cont",
"creatingAccount": "Se creează cont...",
"redirecting": "Se redirecționează către contul tău...",
"alreadyHaveAccount": "Aveți deja un cont? Log in!",
"register": "Înregistrează-te",
"termsError": "Trebuie să acceptați termenii și regulile pentru a vă înregistra.",
+1
View File
@@ -752,6 +752,7 @@
"termsAccept": "Мне 18+ и я принимаю условия и правила {hotel}.",
"createAccount": "Создать аккаунт",
"creatingAccount": "Создание учетной записи...",
"redirecting": "Переход в ваш аккаунт...",
"alreadyHaveAccount": "Уже есть аккаунт? Войти!",
"register": "Регистрация",
"termsError": "Чтобы зарегистрироваться, вы должны принять условия и правила.",
+1
View File
@@ -754,6 +754,7 @@
"termsAccept": "Mám 18+ a súhlasím so zmluvnými podmienkami a pravidlami {hotel}.",
"createAccount": "Vytvoriť účet",
"creatingAccount": "Vytvára sa účet...",
"redirecting": "Presmerovávam na váš účet...",
"alreadyHaveAccount": "Už máte účet? Prihláste sa!",
"register": "Zaregistrujte sa",
"termsError": "Ak sa chcete zaregistrovať, musíte prijať podmienky a pravidlá.",
+1
View File
@@ -754,6 +754,7 @@
"termsAccept": "I am 18+ and accept the {hotel} terms & rules.",
"createAccount": "Креирајте налог",
"creatingAccount": "Прављење налога...",
"redirecting": "Преусмеравање на ваш налог...",
"alreadyHaveAccount": "Већ имате налог? Пријавите се!",
"register": "Региструјте се",
"termsError": "Морате прихватити услове и правила да бисте се регистровали.",
+1
View File
@@ -754,6 +754,7 @@
"termsAccept": "Jag är 18+ och accepterar villkoren och reglerna för {hotel}.",
"createAccount": "Skapa konto",
"creatingAccount": "Skapar konto...",
"redirecting": "Vidare till ditt konto...",
"alreadyHaveAccount": "Har du redan ett konto? Inloggning!",
"register": "Registrera dig",
"termsError": "Du måste acceptera villkoren och reglerna för att registrera dig.",
+1
View File
@@ -754,6 +754,7 @@
"termsAccept": "18 yaşındayım ve {hotel} şartlarını ve kurallarını kabul ediyorum.",
"createAccount": "Hesap oluştur",
"creatingAccount": "Hesap oluşturuluyor...",
"redirecting": "Hesabınıza yönlendiriliyorsunuz...",
"alreadyHaveAccount": "Zaten bir hesabınız var mı? Giriş yapmak!",
"register": "Kayıt ol",
"termsError": "Kayıt olmak için şartları ve kuralları kabul etmelisiniz.",
+1
View File
@@ -754,6 +754,7 @@
"termsAccept": "Мені 18+ і я приймаю умови та правила {hotel}.",
"createAccount": "Створити акаунт",
"creatingAccount": "Створення облікового запису...",
"redirecting": "Перехід до вашого акаунту...",
"alreadyHaveAccount": "Вже маєте акаунт? Вхід!",
"register": "зареєструватися",
"termsError": "Ви повинні прийняти умови та правила, щоб зареєструватися.",