mirror of
https://github.com/Memo-2023/mana-monorepo.git
synced 2026-05-14 17:41:09 +02:00
🐛 fix(auth): implement password reset email link handler
- Add GET /api/auth/reset-password/:token endpoint to handle email links - Create password-reset-redirect store to track source app URLs - Include callbackURL in reset emails for proper app redirection - Add redirectTo parameter to forgotPassword in shared-auth - Create /reset-password page in calendar app with DE/EN translations - Update calendar authStore with resetPasswordWithToken method Fixes 404 error when clicking password reset link from email
This commit is contained in:
parent
2c341b5328
commit
111fc473d9
7 changed files with 427 additions and 5 deletions
|
|
@ -192,7 +192,32 @@ export const authStore = {
|
|||
}
|
||||
|
||||
try {
|
||||
const result = await authService.forgotPassword(email);
|
||||
// Pass current app origin so user is redirected back here after clicking email link
|
||||
const redirectTo = browser ? window.location.origin : undefined;
|
||||
const result = await authService.forgotPassword(email, redirectTo);
|
||||
|
||||
if (!result.success) {
|
||||
return { success: false, error: result.error || 'Password reset failed' };
|
||||
}
|
||||
|
||||
return { success: true };
|
||||
} catch (error) {
|
||||
const errorMessage = error instanceof Error ? error.message : 'Unknown error';
|
||||
return { success: false, error: errorMessage };
|
||||
}
|
||||
},
|
||||
|
||||
/**
|
||||
* Reset password with token (from email link)
|
||||
*/
|
||||
async resetPasswordWithToken(token: string, newPassword: string) {
|
||||
const authService = getAuthService();
|
||||
if (!authService) {
|
||||
return { success: false, error: 'Auth not available on server' };
|
||||
}
|
||||
|
||||
try {
|
||||
const result = await authService.resetPassword(token, newPassword);
|
||||
|
||||
if (!result.success) {
|
||||
return { success: false, error: result.error || 'Password reset failed' };
|
||||
|
|
|
|||
|
|
@ -0,0 +1,231 @@
|
|||
<script lang="ts">
|
||||
import { onMount } from 'svelte';
|
||||
import { page } from '$app/stores';
|
||||
import { goto } from '$app/navigation';
|
||||
import { locale } from 'svelte-i18n';
|
||||
import { CalendarLogo } from '@manacore/shared-branding';
|
||||
import { authStore } from '$lib/stores/auth.svelte';
|
||||
import LanguageSelector from '$lib/components/LanguageSelector.svelte';
|
||||
import '$lib/i18n';
|
||||
|
||||
// State
|
||||
let loading = $state(false);
|
||||
let hasToken = $state(false);
|
||||
let token = $state<string | null>(null);
|
||||
let password = $state('');
|
||||
let confirmPassword = $state('');
|
||||
let error = $state<string | null>(null);
|
||||
let success = $state(false);
|
||||
|
||||
// Translations based on locale
|
||||
const t = $derived({
|
||||
title: $locale === 'de' ? 'Passwort zurücksetzen' : 'Reset Password',
|
||||
subtitle: $locale === 'de' ? 'Gib dein neues Passwort ein' : 'Enter your new password',
|
||||
newPassword: $locale === 'de' ? 'Neues Passwort' : 'New Password',
|
||||
confirmPassword: $locale === 'de' ? 'Passwort bestätigen' : 'Confirm Password',
|
||||
placeholder: $locale === 'de' ? 'Neues Passwort eingeben' : 'Enter new password',
|
||||
confirmPlaceholder: $locale === 'de' ? 'Passwort bestätigen' : 'Confirm password',
|
||||
submit: $locale === 'de' ? 'Passwort ändern' : 'Update Password',
|
||||
submitting: $locale === 'de' ? 'Passwort wird geändert...' : 'Updating password...',
|
||||
success: $locale === 'de' ? 'Passwort erfolgreich geändert' : 'Password reset successfully',
|
||||
successMessage:
|
||||
$locale === 'de'
|
||||
? 'Dein Passwort wurde erfolgreich geändert. Du wirst gleich zur Anmeldeseite weitergeleitet.'
|
||||
: 'Your password has been reset successfully. You will be redirected to the login page shortly.',
|
||||
goToLogin: $locale === 'de' ? 'Zur Anmeldung' : 'Go to login',
|
||||
invalidToken: $locale === 'de' ? 'Ungültiger oder fehlender Token' : 'Invalid or missing token',
|
||||
invalidTokenMessage:
|
||||
$locale === 'de'
|
||||
? 'Dieser Link zum Zurücksetzen des Passworts ist ungültig oder abgelaufen.'
|
||||
: 'This password reset link is invalid or has expired.',
|
||||
requestNew: $locale === 'de' ? 'Neuen Link anfordern' : 'Request a new link',
|
||||
passwordMismatch:
|
||||
$locale === 'de' ? 'Passwörter stimmen nicht überein' : 'Passwords do not match',
|
||||
passwordTooShort:
|
||||
$locale === 'de'
|
||||
? 'Passwort muss mindestens 8 Zeichen lang sein'
|
||||
: 'Password must be at least 8 characters',
|
||||
minChars: $locale === 'de' ? 'Mindestens 8 Zeichen' : 'At least 8 characters',
|
||||
});
|
||||
|
||||
onMount(() => {
|
||||
// Get token from URL query parameter
|
||||
token = $page.url.searchParams.get('token');
|
||||
hasToken = !!token;
|
||||
});
|
||||
|
||||
async function handleSubmit(e: Event) {
|
||||
e.preventDefault();
|
||||
error = null;
|
||||
|
||||
if (!token) {
|
||||
error = t.invalidToken;
|
||||
return;
|
||||
}
|
||||
|
||||
if (password !== confirmPassword) {
|
||||
error = t.passwordMismatch;
|
||||
return;
|
||||
}
|
||||
|
||||
if (password.length < 8) {
|
||||
error = t.passwordTooShort;
|
||||
return;
|
||||
}
|
||||
|
||||
loading = true;
|
||||
|
||||
try {
|
||||
const result = await authStore.resetPasswordWithToken(token, password);
|
||||
|
||||
if (!result.success) {
|
||||
error = result.error || 'Failed to reset password';
|
||||
} else {
|
||||
success = true;
|
||||
// Redirect to login after 3 seconds
|
||||
setTimeout(() => {
|
||||
goto('/login');
|
||||
}, 3000);
|
||||
}
|
||||
} catch (err) {
|
||||
error = err instanceof Error ? err.message : 'An error occurred';
|
||||
} finally {
|
||||
loading = false;
|
||||
}
|
||||
}
|
||||
</script>
|
||||
|
||||
<svelte:head>
|
||||
<title>{t.title} | Kalender</title>
|
||||
</svelte:head>
|
||||
|
||||
<div
|
||||
class="flex min-h-screen flex-col bg-gradient-to-b from-sky-100 to-white dark:from-slate-900 dark:to-slate-800"
|
||||
>
|
||||
<!-- Header -->
|
||||
<header class="flex items-center justify-between p-4">
|
||||
<a href="/" class="flex items-center gap-2">
|
||||
<CalendarLogo class="h-8 w-8" />
|
||||
<span class="text-xl font-semibold text-sky-600 dark:text-sky-400">Kalender</span>
|
||||
</a>
|
||||
<LanguageSelector />
|
||||
</header>
|
||||
|
||||
<!-- Main Content -->
|
||||
<main class="flex flex-1 items-center justify-center p-4">
|
||||
<div class="w-full max-w-md">
|
||||
<div class="text-center mb-8">
|
||||
<h1 class="text-3xl font-bold text-gray-900 dark:text-white">{t.title}</h1>
|
||||
<p class="mt-2 text-gray-600 dark:text-gray-400">
|
||||
{#if success}
|
||||
{t.success}
|
||||
{:else if hasToken}
|
||||
{t.subtitle}
|
||||
{:else}
|
||||
{t.invalidToken}
|
||||
{/if}
|
||||
</p>
|
||||
</div>
|
||||
|
||||
{#if success}
|
||||
<!-- Success State -->
|
||||
<div class="rounded-xl bg-white p-8 shadow-lg dark:bg-slate-800">
|
||||
<div class="text-center">
|
||||
<div class="mb-4 text-6xl">✅</div>
|
||||
<p class="mb-6 text-gray-600 dark:text-gray-400">
|
||||
{t.successMessage}
|
||||
</p>
|
||||
<a
|
||||
href="/login"
|
||||
class="inline-block rounded-lg bg-sky-500 px-6 py-3 font-medium text-white transition-colors hover:bg-sky-600"
|
||||
>
|
||||
{t.goToLogin}
|
||||
</a>
|
||||
</div>
|
||||
</div>
|
||||
{:else if hasToken}
|
||||
<!-- Reset Form -->
|
||||
<div class="rounded-xl bg-white p-8 shadow-lg dark:bg-slate-800">
|
||||
<form onsubmit={handleSubmit}>
|
||||
{#if error}
|
||||
<div
|
||||
class="mb-4 rounded-lg bg-red-50 p-4 text-sm text-red-800 dark:bg-red-900/20 dark:text-red-400"
|
||||
>
|
||||
{error}
|
||||
</div>
|
||||
{/if}
|
||||
|
||||
<div class="space-y-4">
|
||||
<div>
|
||||
<label
|
||||
for="password"
|
||||
class="mb-2 block text-sm font-medium text-gray-900 dark:text-gray-100"
|
||||
>
|
||||
{t.newPassword}
|
||||
</label>
|
||||
<input
|
||||
type="password"
|
||||
name="password"
|
||||
id="password"
|
||||
autocomplete="new-password"
|
||||
placeholder={t.placeholder}
|
||||
required
|
||||
minlength={8}
|
||||
bind:value={password}
|
||||
class="w-full rounded-lg border border-gray-300 px-4 py-3 text-gray-900 focus:border-sky-500 focus:outline-none focus:ring-2 focus:ring-sky-500/20 dark:border-slate-600 dark:bg-slate-700 dark:text-white dark:placeholder-gray-400"
|
||||
/>
|
||||
<p class="mt-1 text-xs text-gray-500 dark:text-gray-400">
|
||||
{t.minChars}
|
||||
</p>
|
||||
</div>
|
||||
|
||||
<div>
|
||||
<label
|
||||
for="confirmPassword"
|
||||
class="mb-2 block text-sm font-medium text-gray-900 dark:text-gray-100"
|
||||
>
|
||||
{t.confirmPassword}
|
||||
</label>
|
||||
<input
|
||||
type="password"
|
||||
name="confirmPassword"
|
||||
id="confirmPassword"
|
||||
autocomplete="new-password"
|
||||
placeholder={t.confirmPlaceholder}
|
||||
required
|
||||
minlength={8}
|
||||
bind:value={confirmPassword}
|
||||
class="w-full rounded-lg border border-gray-300 px-4 py-3 text-gray-900 focus:border-sky-500 focus:outline-none focus:ring-2 focus:ring-sky-500/20 dark:border-slate-600 dark:bg-slate-700 dark:text-white dark:placeholder-gray-400"
|
||||
/>
|
||||
</div>
|
||||
|
||||
<button
|
||||
type="submit"
|
||||
disabled={loading}
|
||||
class="w-full rounded-lg bg-sky-500 px-4 py-3 font-medium text-white transition-colors hover:bg-sky-600 disabled:cursor-not-allowed disabled:opacity-50"
|
||||
>
|
||||
{loading ? t.submitting : t.submit}
|
||||
</button>
|
||||
</div>
|
||||
</form>
|
||||
</div>
|
||||
{:else}
|
||||
<!-- Invalid Token State -->
|
||||
<div class="rounded-xl bg-white p-8 shadow-lg dark:bg-slate-800">
|
||||
<div class="text-center">
|
||||
<div class="mb-4 text-6xl">⚠️</div>
|
||||
<p class="mb-6 text-gray-600 dark:text-gray-400">
|
||||
{t.invalidTokenMessage}
|
||||
</p>
|
||||
<a
|
||||
href="/forgot-password"
|
||||
class="inline-block rounded-lg bg-sky-500 px-6 py-3 font-medium text-white transition-colors hover:bg-sky-600"
|
||||
>
|
||||
{t.requestNew}
|
||||
</a>
|
||||
</div>
|
||||
</div>
|
||||
{/if}
|
||||
</div>
|
||||
</main>
|
||||
</div>
|
||||
|
|
@ -181,13 +181,15 @@ export function createAuthService(config: AuthServiceConfig) {
|
|||
|
||||
/**
|
||||
* Send password reset email
|
||||
* @param email - User's email address
|
||||
* @param redirectTo - Optional URL to redirect after password reset (current app origin)
|
||||
*/
|
||||
async forgotPassword(email: string): Promise<AuthResult> {
|
||||
async forgotPassword(email: string, redirectTo?: string): Promise<AuthResult> {
|
||||
try {
|
||||
const response = await fetch(`${baseUrl}${endpoints.forgotPassword}`, {
|
||||
method: 'POST',
|
||||
headers: { 'Content-Type': 'application/json' },
|
||||
body: JSON.stringify({ email }),
|
||||
body: JSON.stringify({ email, redirectTo }),
|
||||
});
|
||||
|
||||
if (!response.ok) {
|
||||
|
|
|
|||
|
|
@ -6,12 +6,13 @@
|
|||
*
|
||||
* Routes handled:
|
||||
* - GET /api/auth/verify-email - Email verification from verification emails
|
||||
* - GET /api/auth/reset-password/:token - Password reset from reset emails
|
||||
*
|
||||
* This is necessary because Better Auth generates URLs with `/api/auth/*`
|
||||
* but our NestJS API uses `/api/v1/*` as the global prefix.
|
||||
*/
|
||||
|
||||
import { Controller, Get, Query, Res, HttpStatus } from '@nestjs/common';
|
||||
import { Controller, Get, Param, Query, Res, HttpStatus } from '@nestjs/common';
|
||||
import { Response } from 'express';
|
||||
import { BetterAuthService } from './services/better-auth.service';
|
||||
|
||||
|
|
@ -116,4 +117,50 @@ export class BetterAuthPassthroughController {
|
|||
return res.redirect(`${fallbackUrl}/verification-failed?error=verification_failed`);
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Handle password reset link from email
|
||||
*
|
||||
* Better Auth sends password reset emails with links to:
|
||||
* {baseURL}/api/auth/reset-password/{token}?callbackURL=...
|
||||
*
|
||||
* This endpoint:
|
||||
* 1. Extracts the reset token from the URL
|
||||
* 2. Redirects the user to the frontend /reset-password page with the token
|
||||
* 3. The frontend then shows a form to enter the new password
|
||||
* 4. Frontend submits to POST /api/v1/auth/reset-password with token + newPassword
|
||||
*/
|
||||
@Get('reset-password/:token')
|
||||
async resetPassword(
|
||||
@Param('token') token: string,
|
||||
@Query('callbackURL') callbackURL: string | undefined,
|
||||
@Res() res: Response
|
||||
) {
|
||||
const fallbackUrl = process.env.FRONTEND_URL || this.defaultFrontendUrl;
|
||||
|
||||
try {
|
||||
if (!token) {
|
||||
return res.redirect(`${fallbackUrl}/login?error=missing_reset_token`);
|
||||
}
|
||||
|
||||
// Determine redirect URL:
|
||||
// 1. First try the callbackURL query param (from the email link)
|
||||
// 2. Fall back to default frontend URL
|
||||
let baseUrl = this.validateRedirectUrl(callbackURL);
|
||||
|
||||
if (!baseUrl) {
|
||||
baseUrl = fallbackUrl;
|
||||
}
|
||||
|
||||
// Redirect to frontend's reset-password page with token
|
||||
const resetUrl = new URL('/reset-password', baseUrl);
|
||||
resetUrl.searchParams.set('token', token);
|
||||
|
||||
console.log(`[reset-password] Redirecting to: ${resetUrl.toString()}`);
|
||||
return res.redirect(resetUrl.toString());
|
||||
} catch (error) {
|
||||
console.error('[reset-password] Error:', error);
|
||||
return res.redirect(`${fallbackUrl}/login?error=reset_failed`);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
|
|
|||
|
|
@ -28,6 +28,7 @@ import {
|
|||
sendVerificationEmail,
|
||||
} from '../email/email.service';
|
||||
import { sourceAppStore } from './stores/source-app.store';
|
||||
import { passwordResetRedirectStore } from './stores/password-reset-redirect.store';
|
||||
|
||||
/**
|
||||
* JWT Custom Payload Interface
|
||||
|
|
@ -100,6 +101,9 @@ export function createBetterAuth(databaseUrl: string) {
|
|||
* - auth.api.requestPasswordReset({ body: { email } }) - Sends reset email
|
||||
* - auth.api.resetPassword({ body: { newPassword, token } }) - Resets password
|
||||
*
|
||||
* The reset URL is modified to include callbackURL parameter
|
||||
* so users are redirected back to the app they requested reset from.
|
||||
*
|
||||
* @see https://www.better-auth.com/docs/authentication/email-password#password-reset
|
||||
*/
|
||||
sendResetPassword: async ({
|
||||
|
|
@ -109,7 +113,18 @@ export function createBetterAuth(databaseUrl: string) {
|
|||
user: { email: string; name: string };
|
||||
url: string;
|
||||
}) => {
|
||||
await sendPasswordResetEmail(user.email, url, user.name);
|
||||
// Check if we have a redirect URL stored for this user's password reset request
|
||||
const redirectUrl = passwordResetRedirectStore.get(user.email);
|
||||
|
||||
// Modify reset URL to include callbackURL parameter
|
||||
let resetUrl = url;
|
||||
if (redirectUrl) {
|
||||
const urlObj = new URL(url);
|
||||
urlObj.searchParams.set('callbackURL', redirectUrl);
|
||||
resetUrl = urlObj.toString();
|
||||
}
|
||||
|
||||
await sendPasswordResetEmail(user.email, resetUrl, user.name);
|
||||
},
|
||||
},
|
||||
|
||||
|
|
|
|||
|
|
@ -33,6 +33,7 @@ import { ReferralTierService } from '../../referrals/services/referral-tier.serv
|
|||
import { ReferralTrackingService } from '../../referrals/services/referral-tracking.service';
|
||||
import { hasUser, hasToken, hasMember, hasMembers, hasSession } from '../types/better-auth.types';
|
||||
import { sourceAppStore } from '../stores/source-app.store';
|
||||
import { passwordResetRedirectStore } from '../stores/password-reset-redirect.store';
|
||||
import type {
|
||||
RegisterB2CDto,
|
||||
RegisterB2BDto,
|
||||
|
|
@ -876,6 +877,11 @@ export class BetterAuthService {
|
|||
redirectTo?: string
|
||||
): Promise<{ success: boolean; message: string }> {
|
||||
try {
|
||||
// Store the redirect URL so sendResetPassword callback can include it in the email link
|
||||
if (redirectTo) {
|
||||
passwordResetRedirectStore.set(email, redirectTo);
|
||||
}
|
||||
|
||||
// Better Auth's requestPasswordReset endpoint
|
||||
// See: https://www.better-auth.com/docs/authentication/email-password#password-reset
|
||||
await (this.auth.api as any).requestPasswordReset({
|
||||
|
|
|
|||
|
|
@ -0,0 +1,96 @@
|
|||
/**
|
||||
* Password Reset Redirect Store
|
||||
*
|
||||
* Temporary in-memory store for tracking which app a user requested
|
||||
* password reset from. This allows redirecting users back to the correct
|
||||
* app's reset-password page after clicking the email link.
|
||||
*
|
||||
* TTL: 1 hour (password reset tokens are short-lived)
|
||||
*/
|
||||
|
||||
interface ResetRedirectEntry {
|
||||
redirectUrl: string;
|
||||
expiresAt: number;
|
||||
}
|
||||
|
||||
// In-memory store: email -> { redirectUrl, expiresAt }
|
||||
const store = new Map<string, ResetRedirectEntry>();
|
||||
|
||||
// TTL in milliseconds (1 hour)
|
||||
const TTL_MS = 60 * 60 * 1000;
|
||||
|
||||
// Cleanup interval (every 15 minutes)
|
||||
const CLEANUP_INTERVAL_MS = 15 * 60 * 1000;
|
||||
|
||||
// Start cleanup interval
|
||||
setInterval(() => {
|
||||
const now = Date.now();
|
||||
for (const [email, entry] of store.entries()) {
|
||||
if (entry.expiresAt < now) {
|
||||
store.delete(email);
|
||||
}
|
||||
}
|
||||
}, CLEANUP_INTERVAL_MS);
|
||||
|
||||
export const passwordResetRedirectStore = {
|
||||
/**
|
||||
* Store the redirect URL for a password reset request
|
||||
*/
|
||||
set(email: string, redirectUrl: string): void {
|
||||
const normalizedEmail = email.toLowerCase().trim();
|
||||
store.set(normalizedEmail, {
|
||||
redirectUrl,
|
||||
expiresAt: Date.now() + TTL_MS,
|
||||
});
|
||||
},
|
||||
|
||||
/**
|
||||
* Get the redirect URL for an email
|
||||
* Returns null if not found or expired
|
||||
*/
|
||||
get(email: string): string | null {
|
||||
const normalizedEmail = email.toLowerCase().trim();
|
||||
const entry = store.get(normalizedEmail);
|
||||
|
||||
if (!entry) {
|
||||
return null;
|
||||
}
|
||||
|
||||
// Check if expired
|
||||
if (entry.expiresAt < Date.now()) {
|
||||
store.delete(normalizedEmail);
|
||||
return null;
|
||||
}
|
||||
|
||||
return entry.redirectUrl;
|
||||
},
|
||||
|
||||
/**
|
||||
* Get and remove the redirect URL for an email
|
||||
* This is used after the user clicks the link to prevent re-use
|
||||
*/
|
||||
getAndDelete(email: string): string | null {
|
||||
const normalizedEmail = email.toLowerCase().trim();
|
||||
const entry = store.get(normalizedEmail);
|
||||
|
||||
if (!entry) {
|
||||
return null;
|
||||
}
|
||||
|
||||
store.delete(normalizedEmail);
|
||||
|
||||
// Check if expired
|
||||
if (entry.expiresAt < Date.now()) {
|
||||
return null;
|
||||
}
|
||||
|
||||
return entry.redirectUrl;
|
||||
},
|
||||
|
||||
/**
|
||||
* Clear all entries (for testing)
|
||||
*/
|
||||
clear(): void {
|
||||
store.clear();
|
||||
},
|
||||
};
|
||||
Loading…
Add table
Add a link
Reference in a new issue