Skip to content

armgit / papra

Public Imported from GitHub
0

The minimalistic document archiving platform.

feat(auth): added an email verification confirmation/expiration page (#602)

Corentin Thomasset79e9bb1b6169
diff --git a/.changeset/beige-olives-sink.md b/.changeset/beige-olives-sink.md
new file mode 100644
index 00000000..82ec2356
--- /dev/null
+++ b/.changeset/beige-olives-sink.md
@@ -0,0 +1,5 @@
+---
+"@papra/docker": patch
+---
+
+Added an email verification confirmation/expiration page
diff --git a/apps/papra-client/src/locales/de.dictionary.ts b/apps/papra-client/src/locales/de.dictionary.ts
index 5d99b8ac..8916b4bd 100644
--- a/apps/papra-client/src/locales/de.dictionary.ts
+++ b/apps/papra-client/src/locales/de.dictionary.ts
@@ -70,6 +70,13 @@ export const translations: Partial<TranslationsDictionary> = {
'auth.email-validation-required.title': 'E-Mail verifizieren',
'auth.email-validation-required.description': 'Eine Verifizierungs-E-Mail wurde an Ihre E-Mail-Adresse gesendet. Bitte verifizieren Sie Ihre E-Mail-Adresse, indem Sie auf den Link in der E-Mail klicken.',
+ 'auth.email-verification.success.title': 'E-Mail verifiziert',
+ 'auth.email-verification.success.description': 'Ihre E-Mail wurde erfolgreich verifiziert. Sie können sich jetzt in Ihr Konto einloggen.',
+ 'auth.email-verification.success.login': 'Zur Anmeldung',
+ 'auth.email-verification.error.title': 'Verifizierung fehlgeschlagen',
+ 'auth.email-verification.error.description': 'Der Verifizierungslink ist ungültig oder abgelaufen. Bitte fordern Sie eine neue Verifizierungs-E-Mail an, indem Sie sich anmelden.',
+ 'auth.email-verification.error.back': 'Zurück zur Anmeldung',
+
'auth.legal-links.description': 'Indem Sie fortfahren, bestätigen Sie, dass Sie die {{ terms }} und die {{ privacy }} verstanden haben und ihnen zustimmen.',
'auth.legal-links.terms': 'Nutzungsbedingungen',
'auth.legal-links.privacy': 'Datenschutzrichtlinie',
diff --git a/apps/papra-client/src/locales/en.dictionary.ts b/apps/papra-client/src/locales/en.dictionary.ts
index 2383d2c5..7e356f67 100644
--- a/apps/papra-client/src/locales/en.dictionary.ts
+++ b/apps/papra-client/src/locales/en.dictionary.ts
@@ -68,6 +68,13 @@ export const translations = {
'auth.email-validation-required.title': 'Verify your email',
'auth.email-validation-required.description': 'A verification email has been sent to your email address. Please verify your email address by clicking the link in the email.',
+ 'auth.email-verification.success.title': 'Email verified',
+ 'auth.email-verification.success.description': 'Your email has been successfully verified. You can now log in to your account.',
+ 'auth.email-verification.success.login': 'Go to login',
+ 'auth.email-verification.error.title': 'Verification failed',
+ 'auth.email-verification.error.description': 'The verification link has expired or is invalid. Please request a new verification email by logging in.',
+ 'auth.email-verification.error.back': 'Back to login',
+
'auth.legal-links.description': 'By continuing, you acknowledge that you understand and agree to the {{ terms }} and {{ privacy }}.',
'auth.legal-links.terms': 'Terms of Service',
'auth.legal-links.privacy': 'Privacy Policy',
diff --git a/apps/papra-client/src/locales/es.dictionary.ts b/apps/papra-client/src/locales/es.dictionary.ts
index 0c115fa8..db65a245 100644
--- a/apps/papra-client/src/locales/es.dictionary.ts
+++ b/apps/papra-client/src/locales/es.dictionary.ts
@@ -70,6 +70,13 @@ export const translations: Partial<TranslationsDictionary> = {
'auth.email-validation-required.title': 'Verifica tu correo electrónico',
'auth.email-validation-required.description': 'Se ha enviado un correo de verificación a tu dirección de correo electrónico. Por favor, verifica tu correo haciendo clic en el enlace del correo.',
+ 'auth.email-verification.success.title': 'Correo verificado',
+ 'auth.email-verification.success.description': 'Tu correo ha sido verificado exitosamente. Ahora puedes iniciar sesión en tu cuenta.',
+ 'auth.email-verification.success.login': 'Ir a iniciar sesión',
+ 'auth.email-verification.error.title': 'Verificación fallida',
+ 'auth.email-verification.error.description': 'El enlace de verificación es inválido o ha expirado. Por favor, solicita un nuevo correo de verificación iniciando sesión.',
+ 'auth.email-verification.error.back': 'Volver a iniciar sesión',
+
'auth.legal-links.description': 'Al continuar, reconoces que entiendes y aceptas los {{ terms }} y la {{ privacy }}.',
'auth.legal-links.terms': 'Términos de servicio',
'auth.legal-links.privacy': 'Política de privacidad',
diff --git a/apps/papra-client/src/locales/fr.dictionary.ts b/apps/papra-client/src/locales/fr.dictionary.ts
index fb3e4ad0..7e0bbc47 100644
--- a/apps/papra-client/src/locales/fr.dictionary.ts
+++ b/apps/papra-client/src/locales/fr.dictionary.ts
@@ -70,6 +70,13 @@ export const translations: Partial<TranslationsDictionary> = {
'auth.email-validation-required.title': 'Vérifier votre email',
'auth.email-validation-required.description': 'Un email de vérification a été envoyé à votre adresse email. Veuillez vérifier votre adresse email en cliquant sur le lien dans l\'email.',
+ 'auth.email-verification.success.title': 'Email vérifié',
+ 'auth.email-verification.success.description': 'Votre email a été vérifié avec succès. Vous pouvez maintenant vous connecter à votre compte.',
+ 'auth.email-verification.success.login': 'Aller à la connexion',
+ 'auth.email-verification.error.title': 'Échec de la vérification',
+ 'auth.email-verification.error.description': 'Le lien de vérification est invalide ou a expiré. Veuillez demander un nouvel email de vérification en vous connectant.',
+ 'auth.email-verification.error.back': 'Retour à la connexion',
+
'auth.legal-links.description': 'En continuant, vous reconnaissez que vous comprenez et acceptez les {{ terms }} et {{ privacy }}.',
'auth.legal-links.terms': 'Conditions d\'utilisation',
'auth.legal-links.privacy': 'Politique de confidentialité',
diff --git a/apps/papra-client/src/locales/it.dictionary.ts b/apps/papra-client/src/locales/it.dictionary.ts
index 08cd9676..35c6a657 100644
--- a/apps/papra-client/src/locales/it.dictionary.ts
+++ b/apps/papra-client/src/locales/it.dictionary.ts
@@ -70,6 +70,13 @@ export const translations: Partial<TranslationsDictionary> = {
'auth.email-validation-required.title': 'Verifica la tua email',
'auth.email-validation-required.description': 'Una email di verifica è stata inviata al tuo indirizzo email. Verifica il tuo indirizzo cliccando il link nell\'email.',
+ 'auth.email-verification.success.title': 'Email verificata',
+ 'auth.email-verification.success.description': 'La tua email è stata verificata con successo. Ora puoi accedere al tuo account.',
+ 'auth.email-verification.success.login': 'Vai al login',
+ 'auth.email-verification.error.title': 'Verifica fallita',
+ 'auth.email-verification.error.description': 'Il link di verifica non è valido o è scaduto. Richiedi una nuova email di verifica effettuando l\'accesso.',
+ 'auth.email-verification.error.back': 'Torna al login',
+
'auth.legal-links.description': 'Continuando, confermi di aver letto e accettato i {{ terms }} e l\'{{ privacy }}.',
'auth.legal-links.terms': 'Termini di servizio',
'auth.legal-links.privacy': 'Informativa sulla privacy',
diff --git a/apps/papra-client/src/locales/pl.dictionary.ts b/apps/papra-client/src/locales/pl.dictionary.ts
index 940ebd40..96869ebd 100644
--- a/apps/papra-client/src/locales/pl.dictionary.ts
+++ b/apps/papra-client/src/locales/pl.dictionary.ts
@@ -70,6 +70,13 @@ export const translations: Partial<TranslationsDictionary> = {
'auth.email-validation-required.title': 'Zweryfikuj swój adres e-mail',
'auth.email-validation-required.description': 'Wiadomość weryfikacyjna została wysłana na Twój adres e-mail. Zweryfikuj swój adres e-mail, klikając link w wiadomości.',
+ 'auth.email-verification.success.title': 'E-mail zweryfikowany',
+ 'auth.email-verification.success.description': 'Twój adres e-mail został pomyślnie zweryfikowany. Możesz teraz zalogować się do swojego konta.',
+ 'auth.email-verification.success.login': 'Przejdź do logowania',
+ 'auth.email-verification.error.title': 'Weryfikacja nie powiodła się',
+ 'auth.email-verification.error.description': 'Link weryfikacyjny jest nieprawidłowy lub wygasł. Poproś o nową wiadomość weryfikacyjną, logując się.',
+ 'auth.email-verification.error.back': 'Powrót do logowania',
+
'auth.legal-links.description': 'Kontynuując, potwierdzasz, że rozumiesz i zgadzasz się na {{ terms }} oraz {{ privacy }}.',
'auth.legal-links.terms': 'Warunki korzystania z usługi',
'auth.legal-links.privacy': 'Polityka prywatności',
diff --git a/apps/papra-client/src/locales/pt-BR.dictionary.ts b/apps/papra-client/src/locales/pt-BR.dictionary.ts
index ae96b310..715a7a48 100644
--- a/apps/papra-client/src/locales/pt-BR.dictionary.ts
+++ b/apps/papra-client/src/locales/pt-BR.dictionary.ts
@@ -70,6 +70,13 @@ export const translations: Partial<TranslationsDictionary> = {
'auth.email-validation-required.title': 'Verifique seu e-mail',
'auth.email-validation-required.description': 'Um e-mail de verificação foi enviado para seu endereço. Por favor, verifique seu e-mail clicando no link enviado.',
+ 'auth.email-verification.success.title': 'E-mail verificado',
+ 'auth.email-verification.success.description': 'Seu e-mail foi verificado com sucesso. Você já pode fazer login na sua conta.',
+ 'auth.email-verification.success.login': 'Ir para login',
+ 'auth.email-verification.error.title': 'Falha na verificação',
+ 'auth.email-verification.error.description': 'O link de verificação é inválido ou expirou. Por favor, solicite um novo e-mail de verificação ao fazer login.',
+ 'auth.email-verification.error.back': 'Voltar ao login',
+
'auth.legal-links.description': 'Ao continuar, você reconhece que leu e concorda com os {{ terms }} e a {{ privacy }}.',
'auth.legal-links.terms': 'Termos de Serviço',
'auth.legal-links.privacy': 'Política de Privacidade',
diff --git a/apps/papra-client/src/locales/pt.dictionary.ts b/apps/papra-client/src/locales/pt.dictionary.ts
index b66b04c5..9a3dad63 100644
--- a/apps/papra-client/src/locales/pt.dictionary.ts
+++ b/apps/papra-client/src/locales/pt.dictionary.ts
@@ -70,6 +70,13 @@ export const translations: Partial<TranslationsDictionary> = {
'auth.email-validation-required.title': 'Verifique o seu e-mail',
'auth.email-validation-required.description': 'Foi enviado um e-mail de verificação para o seu endereço de e-mail. Por favor, verifique o seu endereço de e-mail clicando na ligação no e-mail.',
+ 'auth.email-verification.success.title': 'E-mail verificado',
+ 'auth.email-verification.success.description': 'O seu e-mail foi verificado com sucesso. Pode agora iniciar sessão na sua conta.',
+ 'auth.email-verification.success.login': 'Ir para o login',
+ 'auth.email-verification.error.title': 'Falha na verificação',
+ 'auth.email-verification.error.description': 'A ligação de verificação é inválida ou expirou. Por favor, solicite um novo e-mail de verificação ao iniciar sessão.',
+ 'auth.email-verification.error.back': 'Voltar ao login',
+
'auth.legal-links.description': 'Ao continuar, reconhece que compreende e concorda com os {{ terms }} e a {{ privacy }}.',
'auth.legal-links.terms': 'Termos de Serviço',
'auth.legal-links.privacy': 'Política de Privacidade',
diff --git a/apps/papra-client/src/locales/ro.dictionary.ts b/apps/papra-client/src/locales/ro.dictionary.ts
index dbb47c1d..af809416 100644
--- a/apps/papra-client/src/locales/ro.dictionary.ts
+++ b/apps/papra-client/src/locales/ro.dictionary.ts
@@ -70,6 +70,13 @@ export const translations: Partial<TranslationsDictionary> = {
'auth.email-validation-required.title': 'Verifică-ți email-ul',
'auth.email-validation-required.description': 'A fost trimis un e-mail de verificare la adresa ta de e-mail. Te rugăm să îți verifici adresa de e-mail dând click pe linkul din e-mail.',
+ 'auth.email-verification.success.title': 'Email verificat',
+ 'auth.email-verification.success.description': 'Email-ul tău a fost verificat cu succes. Acum te poți autentifica în contul tău.',
+ 'auth.email-verification.success.login': 'Mergi la autentificare',
+ 'auth.email-verification.error.title': 'Verificare eșuată',
+ 'auth.email-verification.error.description': 'Linkul de verificare este invalid sau a expirat. Te rugăm să soliciți un nou e-mail de verificare autentificându-te.',
+ 'auth.email-verification.error.back': 'Înapoi la autentificare',
+
'auth.legal-links.description': 'Continuând, confirmați că întelegeți și sunteti de acord cu {{ terms }} și {{ privacy }}.',
'auth.legal-links.terms': 'Termenii și condițiile',
'auth.legal-links.privacy': 'Politica de confidențialitate',
diff --git a/apps/papra-client/src/modules/auth/auth.constants.ts b/apps/papra-client/src/modules/auth/auth.constants.ts
index ad214de9..c040d4d6 100644
--- a/apps/papra-client/src/modules/auth/auth.constants.ts
+++ b/apps/papra-client/src/modules/auth/auth.constants.ts
@@ -10,3 +10,7 @@ export const ssoProviders = [
icon: 'i-tabler-brand-github',
},
] as const;
+
+export const authPagesPaths = {
+ emailVerification: '/email-verification',
+};
diff --git a/apps/papra-client/src/modules/auth/pages/email-verification.page.tsx b/apps/papra-client/src/modules/auth/pages/email-verification.page.tsx
new file mode 100644
index 00000000..23c0298c
--- /dev/null
+++ b/apps/papra-client/src/modules/auth/pages/email-verification.page.tsx
@@ -0,0 +1,56 @@
+import type { Component } from 'solid-js';
+import { A, useSearchParams } from '@solidjs/router';
+import { useI18n } from '@/modules/i18n/i18n.provider';
+import { Button } from '@/modules/ui/components/button';
+import { AuthLayout } from '../../ui/layouts/auth-layout.component';
+
+export const EmailVerificationPage: Component = () => {
+ const { t } = useI18n();
+ const [searchParams] = useSearchParams();
+
+ const getHasError = () => Boolean(searchParams.error);
+
+ return (
+ <AuthLayout>
+ <div class="flex items-center justify-center h-full p-6 sm:pb-32">
+ <div class="max-w-xs w-full flex flex-col items-center text-center">
+ {getHasError()
+ ? (
+ <>
+ <div class="i-tabler-alert-circle size-12 text-destructive mb-2" />
+
+ <h1 class="text-xl font-bold">
+ {t('auth.email-verification.error.title')}
+ </h1>
+ <p class="text-muted-foreground mt-1 mb-4">
+ {t('auth.email-verification.error.description')}
+ </p>
+
+ <Button as={A} href="/login" class="gap-2" variant="secondary">
+ <div class="i-tabler-arrow-left size-4" />
+ {t('auth.email-verification.error.back')}
+ </Button>
+ </>
+ )
+ : (
+ <>
+ <div class="i-tabler-circle-check size-12 text-primary mb-2" />
+
+ <h1 class="text-xl font-bold">
+ {t('auth.email-verification.success.title')}
+ </h1>
+ <p class="text-muted-foreground mt-1 mb-4">
+ {t('auth.email-verification.success.description')}
+ </p>
+
+ <Button as={A} href="/login" class="gap-2">
+ {t('auth.email-verification.success.login')}
+ <div class="i-tabler-arrow-right size-4" />
+ </Button>
+ </>
+ )}
+ </div>
+ </div>
+ </AuthLayout>
+ );
+};
diff --git a/apps/papra-client/src/modules/auth/pages/login.page.tsx b/apps/papra-client/src/modules/auth/pages/login.page.tsx
index c7943317..35329795 100644
--- a/apps/papra-client/src/modules/auth/pages/login.page.tsx
+++ b/apps/papra-client/src/modules/auth/pages/login.page.tsx
@@ -1,5 +1,6 @@
import type { Component } from 'solid-js';
import type { SsoProviderConfig } from '../auth.types';
+import { buildUrl } from '@corentinth/chisels';
import { A, useNavigate } from '@solidjs/router';
import { createSignal, For, Show } from 'solid-js';
import * as v from 'valibot';
@@ -12,6 +13,7 @@ import { Checkbox, CheckboxControl, CheckboxLabel } from '@/modules/ui/component
import { Separator } from '@/modules/ui/components/separator';
import { TextField, TextFieldLabel, TextFieldRoot } from '@/modules/ui/components/textfield';
import { AuthLayout } from '../../ui/layouts/auth-layout.component';
+import { authPagesPaths } from '../auth.constants';
import { getEnabledSsoProviderConfigs, isEmailVerificationRequiredError } from '../auth.models';
import { authWithProvider, signIn } from '../auth.services';
import { AuthLegalLinks } from '../components/legal-links.component';
@@ -26,7 +28,13 @@ export const EmailLoginForm: Component = () => {
const { form, Form, Field } = createForm({
onSubmit: async ({ email, password, rememberMe }) => {
- const { error } = await signIn.email({ email, password, rememberMe, callbackURL: config.baseUrl });
+ const { error } = await signIn.email({
+ email,
+ password,
+ rememberMe,
+ // This URL is where the user will be redirected after email verification
+ callbackURL: buildUrl({ baseUrl: config.baseUrl, path: authPagesPaths.emailVerification }),
+ });
if (isEmailVerificationRequiredError({ error })) {
navigate('/email-validation-required');
@@ -35,6 +43,8 @@ export const EmailLoginForm: Component = () => {
if (error) {
throw createI18nApiError({ error });
}
+
+ // If all good guard will redirect to dashboard
},
schema: v.object({
email: v.pipe(
diff --git a/apps/papra-client/src/modules/auth/pages/register.page.tsx b/apps/papra-client/src/modules/auth/pages/register.page.tsx
index 3d920733..253c8159 100644
--- a/apps/papra-client/src/modules/auth/pages/register.page.tsx
+++ b/apps/papra-client/src/modules/auth/pages/register.page.tsx
@@ -1,5 +1,6 @@
import type { Component } from 'solid-js';
import type { SsoProviderConfig } from '../auth.types';
+import { buildUrl } from '@corentinth/chisels';
import { A, useNavigate } from '@solidjs/router';
import { createSignal, For, Show } from 'solid-js';
import * as v from 'valibot';
@@ -11,6 +12,7 @@ import { Button } from '@/modules/ui/components/button';
import { Separator } from '@/modules/ui/components/separator';
import { TextField, TextFieldLabel, TextFieldRoot } from '@/modules/ui/components/textfield';
import { AuthLayout } from '../../ui/layouts/auth-layout.component';
+import { authPagesPaths } from '../auth.constants';
import { getEnabledSsoProviderConfigs } from '../auth.models';
import { authWithProvider, signUp } from '../auth.services';
import { AuthLegalLinks } from '../components/legal-links.component';
@@ -29,7 +31,8 @@ export const EmailRegisterForm: Component = () => {
email,
password,
name,
- callbackURL: config.baseUrl,
+ // This URL is where the user will be redirected after email verification
+ callbackURL: buildUrl({ baseUrl: config.baseUrl, path: authPagesPaths.emailVerification }),
});
if (error) {
diff --git a/apps/papra-client/src/routes.tsx b/apps/papra-client/src/routes.tsx
index 8a877cb6..aa906ac8 100644
--- a/apps/papra-client/src/routes.tsx
+++ b/apps/papra-client/src/routes.tsx
@@ -4,8 +4,10 @@ import { useQuery } from '@tanstack/solid-query';
import { Match, Show, Suspense, Switch } from 'solid-js';
import { ApiKeysPage } from './modules/api-keys/pages/api-keys.page';
import { CreateApiKeyPage } from './modules/api-keys/pages/create-api-key.page';
+import { authPagesPaths } from './modules/auth/auth.constants';
import { createProtectedPage } from './modules/auth/middleware/protected-page.middleware';
import { EmailValidationRequiredPage } from './modules/auth/pages/email-validation-required.page';
+import { EmailVerificationPage } from './modules/auth/pages/email-verification.page';
import { LoginPage } from './modules/auth/pages/login.page';
import { RegisterPage } from './modules/auth/pages/register.page';
import { RequestPasswordResetPage } from './modules/auth/pages/request-password-reset.page';
@@ -239,6 +241,10 @@ export const routes: RouteDefinition[] = [
path: '/email-validation-required',
component: createProtectedPage({ authType: 'public-only', component: EmailValidationRequiredPage }),
},
+ {
+ path: authPagesPaths.emailVerification,
+ component: createProtectedPage({ authType: 'public-only', component: EmailVerificationPage }),
+ },
{
path: '/checkout-success',
component: CheckoutSuccessPage,
diff --git a/apps/papra-server/src/modules/app/auth/auth.services.ts b/apps/papra-server/src/modules/app/auth/auth.services.ts
index 398901bc..159b7fe7 100644
--- a/apps/papra-server/src/modules/app/auth/auth.services.ts
+++ b/apps/papra-server/src/modules/app/auth/auth.services.ts
@@ -54,9 +54,14 @@ export function getAuth({
enabled: true,
},
},
- emailVerification: {
- sendVerificationEmail: authEmailsServices.sendVerificationEmail,
- },
+ emailVerification: config.auth.isEmailVerificationRequired
+ ? {
+ sendVerificationEmail: authEmailsServices.sendVerificationEmail,
+ autoSignInAfterVerification: false,
+ sendOnSignIn: true,
+ sendOnSignUp: true,
+ }
+ : undefined,
database: drizzleAdapter(
db,
diff --git a/apps/papra-server/src/modules/app/auth/e2e/email-verification.e2e.test.ts b/apps/papra-server/src/modules/app/auth/e2e/email-verification.e2e.test.ts
new file mode 100644
index 00000000..51daf3ce
--- /dev/null
+++ b/apps/papra-server/src/modules/app/auth/e2e/email-verification.e2e.test.ts
@@ -0,0 +1,208 @@
+import { describe, expect, test, vi } from 'vitest';
+import { overrideConfig } from '../../../config/config.test-utils';
+import { createInMemoryDatabase } from '../../database/database.test-utils';
+import { createServer } from '../../server';
+import { createAuthEmailsServices } from '../auth.emails.services';
+import { getAuth } from '../auth.services';
+
+function createTestEmailServices() {
+ const args: Array<{ to: string; subject: string; html: string }> = [];
+
+ return {
+ name: 'test',
+ sendEmail: async (emailArgs: { to: string; subject: string; html: string }) => {
+ args.push(emailArgs);
+ },
+ getSentEmails: () => args,
+ clear: () => {
+ args.length = 0;
+ },
+ };
+}
+
+describe('email verification e2e', () => {
+ describe('signup with email verification', () => {
+ describe('when email verification is required, the verification email is sent during signup', () => {
+ test('an email is sent after signup with verification URL', async () => {
+ const { db } = await createInMemoryDatabase();
+ const mockEmailsServices = createTestEmailServices();
+
+ const config = overrideConfig({
+ auth: {
+ isEmailVerificationRequired: true,
+ },
+ });
+
+ const authEmailsServices = createAuthEmailsServices({ emailsServices: mockEmailsServices });
+ const { auth } = getAuth({ db, config, authEmailsServices, trackingServices: { captureUserEvent: vi.fn(), shutdown: vi.fn() } });
+
+ const { app } = await createServer({ db, config, auth });
+
+ const response = await app.request('/api/auth/sign-up/email', {
+ method: 'POST',
+ headers: {
+ 'Content-Type': 'application/json',
+ },
+ body: JSON.stringify({
+ email: '[email protected]',
+ password: 'StrongPassword123!',
+ name: 'Test User',
+ }),
+ });
+
+ expect(response.status).to.eql(200);
+
+ expect(
+ mockEmailsServices.getSentEmails().map(({ to, subject }) => ({ to, subject })),
+ ).to.eql([
+ {
+ subject: 'Verify your email',
+ },
+ ]);
+ });
+ });
+
+ describe('when email verification is required, users cannot login without verifying their email', () => {
+ test('login attempt without verified email returns an error', async () => {
+ const { db } = await createInMemoryDatabase();
+ const mockEmailsServices = createTestEmailServices();
+
+ const config = overrideConfig({
+ auth: {
+ isEmailVerificationRequired: true,
+ },
+ });
+
+ const authEmailsServices = createAuthEmailsServices({ emailsServices: mockEmailsServices });
+ const { auth } = getAuth({ db, config, authEmailsServices, trackingServices: { captureUserEvent: vi.fn(), shutdown: vi.fn() } });
+
+ const { app } = await createServer({ db, config, auth });
+
+ // First, sign up
+ await app.request('/api/auth/sign-up/email', {
+ method: 'POST',
+ headers: {
+ 'Content-Type': 'application/json',
+ },
+ body: JSON.stringify({
+ email: '[email protected]',
+ password: 'StrongPassword123!',
+ name: 'Test User',
+ }),
+ });
+
+ // Clear sent emails to check if login triggers another email
+ mockEmailsServices.clear();
+
+ // Try to login without verifying
+ const loginResponse = await app.request('/api/auth/sign-in/email', {
+ method: 'POST',
+ headers: {
+ 'Content-Type': 'application/json',
+ },
+ body: JSON.stringify({
+ email: '[email protected]',
+ password: 'StrongPassword123!',
+ }),
+ });
+
+ // Better auth returns 403 for unverified email
+ expect(loginResponse.status).to.eql(403);
+
+ expect(
+ await loginResponse.json(),
+ ).to.eql({
+ code: 'EMAIL_NOT_VERIFIED',
+ message: 'Email not verified',
+ });
+
+ // An email should be sent on sign-in attempt with unverified email (per config: sendOnSignIn: true)
+ expect(mockEmailsServices.getSentEmails()).toHaveLength(1);
+ expect(mockEmailsServices.getSentEmails()[0]?.subject).to.eql('Verify your email');
+ });
+ });
+
+ describe('when email verification is disabled, no verification email is sent', () => {
+ test('signup without email verification requirement does not send email', async () => {
+ const { db } = await createInMemoryDatabase();
+ const mockEmailsServices = createTestEmailServices();
+
+ const config = overrideConfig({
+ auth: {
+ isEmailVerificationRequired: false,
+ },
+ });
+
+ const authEmailsServices = createAuthEmailsServices({ emailsServices: mockEmailsServices });
+ const { auth } = getAuth({ db, config, authEmailsServices, trackingServices: { captureUserEvent: vi.fn(), shutdown: vi.fn() } });
+
+ const { app } = await createServer({ db, config, auth });
+
+ const response = await app.request('/api/auth/sign-up/email', {
+ method: 'POST',
+ headers: {
+ 'Content-Type': 'application/json',
+ },
+ body: JSON.stringify({
+ email: '[email protected]',
+ password: 'StrongPassword123!',
+ name: 'Test User',
+ }),
+ });
+
+ expect(response.status).to.eql(200);
+ expect(mockEmailsServices.getSentEmails()).toHaveLength(0);
+ });
+
+ test('users can login immediately after signup when email verification is disabled', async () => {
+ const { db } = await createInMemoryDatabase();
+ const mockEmailsServices = createTestEmailServices();
+
+ const config = overrideConfig({
+ auth: {
+ isEmailVerificationRequired: false,
+ },
+ });
+
+ const authEmailsServices = createAuthEmailsServices({ emailsServices: mockEmailsServices });
+ const { auth } = getAuth({ db, config, authEmailsServices, trackingServices: { captureUserEvent: vi.fn(), shutdown: vi.fn() } });
+
+ const { app } = await createServer({ db, config, auth });
+
+ // Sign up
+ await app.request('/api/auth/sign-up/email', {
+ method: 'POST',
+ headers: {
+ 'Content-Type': 'application/json',
+ },
+ body: JSON.stringify({
+ email: '[email protected]',
+ password: 'StrongPassword123!',
+ name: 'Test User',
+ }),
+ });
+
+ // Login immediately without verification
+ const loginResponse = await app.request('/api/auth/sign-in/email', {
+ method: 'POST',
+ headers: {
+ 'Content-Type': 'application/json',
+ },
+ body: JSON.stringify({
+ email: '[email protected]',
+ password: 'StrongPassword123!',
+ }),
+ });
+
+ expect(loginResponse.status).to.eql(200);
+ expect(mockEmailsServices.getSentEmails()).toHaveLength(0);
+
+ const loginBody: any = await loginResponse.json();
+ expect(loginBody).to.have.property('user');
+ // eslint-disable-next-line ts/no-unsafe-member-access
+ expect(loginBody?.user?.email).to.eql('[email protected]');
+ });
+ });
+ });
+});