Forgot password implementierung

This commit is contained in:
Timo Knuth
2025-11-18 19:21:29 +01:00
parent 8ecd58b176
commit 424c61a176
11 changed files with 758 additions and 30 deletions

View File

@@ -6,11 +6,13 @@ import { Card, CardHeader, CardTitle, CardContent } from '@/components/ui/Card';
import { Button } from '@/components/ui/Button';
import { Input } from '@/components/ui/Input';
import { showToast } from '@/components/ui/Toast';
import { useCsrf } from '@/hooks/useCsrf';
export default function EditQRPage() {
const router = useRouter();
const params = useParams();
const qrId = params.id as string;
const { fetchWithCsrf, loading: csrfLoading } = useCsrf();
const [loading, setLoading] = useState(true);
const [saving, setSaving] = useState(false);
@@ -47,11 +49,8 @@ export default function EditQRPage() {
setSaving(true);
try {
const response = await fetch(`/api/qrs/${qrId}`, {
const response = await fetchWithCsrf(`/api/qrs/${qrId}`, {
method: 'PATCH',
headers: {
'Content-Type': 'application/json',
},
body: JSON.stringify({
title,
content,
@@ -253,8 +252,9 @@ export default function EditQRPage() {
<Button
onClick={handleSave}
loading={saving}
disabled={csrfLoading || saving}
>
Save Changes
{csrfLoading ? 'Loading...' : 'Save Changes'}
</Button>
</div>
</CardContent>

View File

@@ -0,0 +1,155 @@
'use client';
import React, { useState } from 'react';
import Link from 'next/link';
import { Card, CardContent } from '@/components/ui/Card';
import { Input } from '@/components/ui/Input';
import { Button } from '@/components/ui/Button';
import { useCsrf } from '@/hooks/useCsrf';
export default function ForgotPasswordPage() {
const { fetchWithCsrf, loading: csrfLoading } = useCsrf();
const [email, setEmail] = useState('');
const [loading, setLoading] = useState(false);
const [success, setSuccess] = useState(false);
const [error, setError] = useState('');
const handleSubmit = async (e: React.FormEvent) => {
e.preventDefault();
setLoading(true);
setError('');
try {
const response = await fetchWithCsrf('/api/auth/forgot-password', {
method: 'POST',
body: JSON.stringify({ email }),
});
const data = await response.json();
if (response.ok) {
setSuccess(true);
} else {
setError(data.error || 'Failed to send reset email');
}
} catch (err) {
setError('An error occurred. Please try again.');
} finally {
setLoading(false);
}
};
if (success) {
return (
<div className="min-h-screen bg-gradient-to-br from-primary-50 to-white flex items-center justify-center p-4">
<div className="w-full max-w-md">
<div className="text-center mb-8">
<Link href="/" className="inline-flex items-center space-x-2 mb-6">
<img src="/logo.svg" alt="QR Master" className="w-10 h-10" />
<span className="text-2xl font-bold text-gray-900">QR Master</span>
</Link>
<h1 className="text-3xl font-bold text-gray-900">Check Your Email</h1>
<p className="text-gray-600 mt-2">We've sent you a password reset link</p>
</div>
<Card>
<CardContent className="p-6">
<div className="text-center">
<div className="inline-flex items-center justify-center w-16 h-16 bg-green-100 rounded-full mb-4">
<svg className="w-8 h-8 text-green-600" fill="none" stroke="currentColor" viewBox="0 0 24 24">
<path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M5 13l4 4L19 7" />
</svg>
</div>
<p className="text-gray-700 mb-4">
We've sent a password reset link to <strong>{email}</strong>
</p>
<p className="text-sm text-gray-600 mb-6">
Please check your email and click the link to reset your password. The link will expire in 1 hour.
</p>
<div className="space-y-3">
<Link href="/login" className="block">
<Button variant="primary" className="w-full">
Back to Login
</Button>
</Link>
<button
onClick={() => {
setSuccess(false);
setEmail('');
}}
className="w-full text-primary-600 hover:text-primary-700 text-sm font-medium"
>
Try a different email
</button>
</div>
</div>
</CardContent>
</Card>
</div>
</div>
);
}
return (
<div className="min-h-screen bg-gradient-to-br from-primary-50 to-white flex items-center justify-center p-4">
<div className="w-full max-w-md">
<div className="text-center mb-8">
<Link href="/" className="inline-flex items-center space-x-2 mb-6">
<img src="/logo.svg" alt="QR Master" className="w-10 h-10" />
<span className="text-2xl font-bold text-gray-900">QR Master</span>
</Link>
<h1 className="text-3xl font-bold text-gray-900">Forgot Password?</h1>
<p className="text-gray-600 mt-2">No worries, we'll send you reset instructions</p>
</div>
<Card>
<CardContent className="p-6">
<form onSubmit={handleSubmit} className="space-y-4">
{error && (
<div className="bg-red-50 text-red-600 p-3 rounded-lg text-sm">
{error}
</div>
)}
<Input
label="Email"
type="email"
value={email}
onChange={(e) => setEmail(e.target.value)}
placeholder="you@example.com"
required
disabled={loading || csrfLoading}
/>
<Button
type="submit"
className="w-full"
loading={loading}
disabled={csrfLoading || loading}
>
{csrfLoading ? 'Loading...' : 'Send Reset Link'}
</Button>
<div className="text-center">
<Link href="/login" className="text-sm text-primary-600 hover:text-primary-700 font-medium">
← Back to Login
</Link>
</div>
</form>
</CardContent>
</Card>
<p className="text-center text-sm text-gray-500 mt-6">
Remember your password?{' '}
<Link href="/login" className="text-primary-600 hover:text-primary-700 font-medium">
Sign in
</Link>
</p>
</div>
</div>
);
}

View File

@@ -0,0 +1,208 @@
'use client';
import React, { useState, useEffect } from 'react';
import Link from 'next/link';
import { useSearchParams, useRouter } from 'next/navigation';
import { Card, CardContent } from '@/components/ui/Card';
import { Input } from '@/components/ui/Input';
import { Button } from '@/components/ui/Button';
import { useCsrf } from '@/hooks/useCsrf';
export default function ResetPasswordPage() {
const { fetchWithCsrf, loading: csrfLoading } = useCsrf();
const searchParams = useSearchParams();
const router = useRouter();
const [token, setToken] = useState('');
const [password, setPassword] = useState('');
const [confirmPassword, setConfirmPassword] = useState('');
const [loading, setLoading] = useState(false);
const [success, setSuccess] = useState(false);
const [error, setError] = useState('');
useEffect(() => {
const tokenParam = searchParams.get('token');
if (!tokenParam) {
setError('Invalid or missing reset token. Please request a new password reset link.');
} else {
setToken(tokenParam);
}
}, [searchParams]);
const handleSubmit = async (e: React.FormEvent) => {
e.preventDefault();
setLoading(true);
setError('');
// Validate passwords match
if (password !== confirmPassword) {
setError('Passwords do not match');
setLoading(false);
return;
}
// Validate password length
if (password.length < 8) {
setError('Password must be at least 8 characters long');
setLoading(false);
return;
}
try {
const response = await fetchWithCsrf('/api/auth/reset-password', {
method: 'POST',
body: JSON.stringify({ token, password }),
});
const data = await response.json();
if (response.ok) {
setSuccess(true);
// Redirect to login after 3 seconds
setTimeout(() => {
router.push('/login');
}, 3000);
} else {
setError(data.error || 'Failed to reset password');
}
} catch (err) {
setError('An error occurred. Please try again.');
} finally {
setLoading(false);
}
};
if (success) {
return (
<div className="min-h-screen bg-gradient-to-br from-primary-50 to-white flex items-center justify-center p-4">
<div className="w-full max-w-md">
<div className="text-center mb-8">
<Link href="/" className="inline-flex items-center space-x-2 mb-6">
<img src="/logo.svg" alt="QR Master" className="w-10 h-10" />
<span className="text-2xl font-bold text-gray-900">QR Master</span>
</Link>
<h1 className="text-3xl font-bold text-gray-900">Password Reset Successful</h1>
<p className="text-gray-600 mt-2">Your password has been updated</p>
</div>
<Card>
<CardContent className="p-6">
<div className="text-center">
<div className="inline-flex items-center justify-center w-16 h-16 bg-green-100 rounded-full mb-4">
<svg className="w-8 h-8 text-green-600" fill="none" stroke="currentColor" viewBox="0 0 24 24">
<path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M5 13l4 4L19 7" />
</svg>
</div>
<p className="text-gray-700 mb-4">
Your password has been successfully reset!
</p>
<p className="text-sm text-gray-600 mb-6">
Redirecting you to the login page in 3 seconds...
</p>
<Link href="/login" className="block">
<Button variant="primary" className="w-full">
Go to Login
</Button>
</Link>
</div>
</CardContent>
</Card>
</div>
</div>
);
}
return (
<div className="min-h-screen bg-gradient-to-br from-primary-50 to-white flex items-center justify-center p-4">
<div className="w-full max-w-md">
<div className="text-center mb-8">
<Link href="/" className="inline-flex items-center space-x-2 mb-6">
<img src="/logo.svg" alt="QR Master" className="w-10 h-10" />
<span className="text-2xl font-bold text-gray-900">QR Master</span>
</Link>
<h1 className="text-3xl font-bold text-gray-900">Reset Your Password</h1>
<p className="text-gray-600 mt-2">Enter your new password below</p>
</div>
<Card>
<CardContent className="p-6">
{!token ? (
<div className="text-center">
<div className="inline-flex items-center justify-center w-16 h-16 bg-red-100 rounded-full mb-4">
<svg className="w-8 h-8 text-red-600" fill="none" stroke="currentColor" viewBox="0 0 24 24">
<path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M6 18L18 6M6 6l12 12" />
</svg>
</div>
<p className="text-red-600 mb-4">{error}</p>
<Link href="/forgot-password" className="block">
<Button variant="primary" className="w-full">
Request New Reset Link
</Button>
</Link>
</div>
) : (
<form onSubmit={handleSubmit} className="space-y-4">
{error && (
<div className="bg-red-50 text-red-600 p-3 rounded-lg text-sm">
{error}
</div>
)}
<Input
label="New Password"
type="password"
value={password}
onChange={(e) => setPassword(e.target.value)}
placeholder="Enter new password"
required
disabled={loading || csrfLoading}
minLength={8}
/>
<Input
label="Confirm Password"
type="password"
value={confirmPassword}
onChange={(e) => setConfirmPassword(e.target.value)}
placeholder="Confirm new password"
required
disabled={loading || csrfLoading}
minLength={8}
/>
<div className="text-xs text-gray-500">
Password must be at least 8 characters long
</div>
<Button
type="submit"
className="w-full"
loading={loading}
disabled={csrfLoading || loading}
>
{csrfLoading ? 'Loading...' : 'Reset Password'}
</Button>
<div className="text-center">
<Link href="/login" className="text-sm text-primary-600 hover:text-primary-700 font-medium">
Back to Login
</Link>
</div>
</form>
)}
</CardContent>
</Card>
<p className="text-center text-sm text-gray-500 mt-6">
Remember your password?{' '}
<Link href="/login" className="text-primary-600 hover:text-primary-700 font-medium">
Sign in
</Link>
</p>
</div>
</div>
);
}

View File

@@ -0,0 +1,89 @@
import { NextRequest, NextResponse } from 'next/server';
import { db } from '@/lib/db';
import { csrfProtection } from '@/lib/csrf';
import { sendPasswordResetEmail } from '@/lib/email';
import crypto from 'crypto';
export async function POST(req: NextRequest) {
try {
// Verify CSRF token
const csrfCheck = csrfProtection(req);
if (!csrfCheck.valid) {
return NextResponse.json(
{ error: csrfCheck.error || 'Invalid CSRF token' },
{ status: 403 }
);
}
const body = await req.json();
const { email } = body;
if (!email) {
return NextResponse.json(
{ error: 'Email is required' },
{ status: 400 }
);
}
// Validate email format
const emailRegex = /^[^\s@]+@[^\s@]+\.[^\s@]+$/;
if (!emailRegex.test(email)) {
return NextResponse.json(
{ error: 'Invalid email format' },
{ status: 400 }
);
}
// Find user by email
const user = await db.user.findUnique({
where: { email: email.toLowerCase() },
});
// For security, always return success even if email doesn't exist
// This prevents email enumeration attacks
if (!user) {
console.log('Password reset requested for non-existent email:', email);
return NextResponse.json(
{ message: 'If an account with that email exists, a password reset link has been sent.' },
{ status: 200 }
);
}
// Generate secure random token
const resetToken = crypto.randomBytes(32).toString('hex');
// Set token expiration to 1 hour from now
const resetExpires = new Date(Date.now() + 3600000); // 1 hour
// Save token and expiration to database
await db.user.update({
where: { id: user.id },
data: {
resetPasswordToken: resetToken,
resetPasswordExpires: resetExpires,
},
});
// Send password reset email
try {
await sendPasswordResetEmail(email, resetToken);
} catch (emailError) {
console.error('Error sending password reset email:', emailError);
return NextResponse.json(
{ error: 'Failed to send reset email. Please try again later.' },
{ status: 500 }
);
}
return NextResponse.json(
{ message: 'Password reset email sent successfully' },
{ status: 200 }
);
} catch (error) {
console.error('Error in forgot-password route:', error);
return NextResponse.json(
{ error: 'An error occurred. Please try again.' },
{ status: 500 }
);
}
}

View File

@@ -0,0 +1,90 @@
import { NextRequest, NextResponse } from 'next/server';
import { db } from '@/lib/db';
import { csrfProtection } from '@/lib/csrf';
import bcrypt from 'bcryptjs';
export async function POST(req: NextRequest) {
try {
// Verify CSRF token
const csrfCheck = csrfProtection(req);
if (!csrfCheck.valid) {
return NextResponse.json(
{ error: csrfCheck.error || 'Invalid CSRF token' },
{ status: 403 }
);
}
const body = await req.json();
const { token, password } = body;
if (!token || !password) {
return NextResponse.json(
{ error: 'Token and password are required' },
{ status: 400 }
);
}
// Validate password length
if (password.length < 8) {
return NextResponse.json(
{ error: 'Password must be at least 8 characters long' },
{ status: 400 }
);
}
// Find user with this reset token
const user = await db.user.findUnique({
where: { resetPasswordToken: token },
});
if (!user) {
return NextResponse.json(
{ error: 'Invalid or expired reset token' },
{ status: 400 }
);
}
// Check if token has expired
if (!user.resetPasswordExpires || user.resetPasswordExpires < new Date()) {
// Clear expired token
await db.user.update({
where: { id: user.id },
data: {
resetPasswordToken: null,
resetPasswordExpires: null,
},
});
return NextResponse.json(
{ error: 'Reset token has expired. Please request a new password reset link.' },
{ status: 400 }
);
}
// Hash the new password
const hashedPassword = await bcrypt.hash(password, 10);
// Update user's password and clear reset token
await db.user.update({
where: { id: user.id },
data: {
password: hashedPassword,
resetPasswordToken: null,
resetPasswordExpires: null,
},
});
console.log('Password successfully reset for user:', user.email);
return NextResponse.json(
{ message: 'Password reset successfully' },
{ status: 200 }
);
} catch (error) {
console.error('Error in reset-password route:', error);
return NextResponse.json(
{ error: 'An error occurred. Please try again.' },
{ status: 500 }
);
}
}

View File

@@ -35,8 +35,8 @@ export default function NotFound() {
</p>
</div>
{/* Action Buttons */}
<div className="flex flex-col sm:flex-row gap-4 justify-center items-center">
{/* Action Button */}
<div className="flex justify-center">
<Link href="/">
<Button size="lg">
<svg
@@ -53,29 +53,9 @@ export default function NotFound() {
d="M3 12l2-2m0 0l7-7 7 7M5 10v10a1 1 0 001 1h3m10-11l2 2m-2-2v10a1 1 0 01-1 1h-3m-6 0a1 1 0 001-1v-4a1 1 0 011-1h2a1 1 0 011 1v4a1 1 0 001 1m-6 0h6"
/>
</svg>
Go Home
Back to Home
</Button>
</Link>
<Link href="/create">
<Button variant="outline" size="lg">
Create QR Code
</Button>
</Link>
</div>
{/* Help Text */}
<div className="mt-12 pt-8 border-t border-gray-200">
<p className="text-sm text-gray-500">
Need help?{' '}
<Link href="/#faq" className="text-primary-600 hover:text-primary-700 font-medium">
Visit our FAQ
</Link>{' '}
or{' '}
<Link href="/blog" className="text-primary-600 hover:text-primary-700 font-medium">
read our blog
</Link>
</p>
</div>
</div>
</div>