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

@ -22,7 +22,8 @@
"Bash(npm run build:*)", "Bash(npm run build:*)",
"Bash(ls:*)", "Bash(ls:*)",
"Bash(curl:*)", "Bash(curl:*)",
"Bash(echo \"\n\n## CSRF Debug aktiviert!\n\nBitte teste jetzt:\n1. Browser zu http://localhost:3050/create\n2. Dynamic QR Code erstellen versuchen\n3. Server-Logs zeigen jetzt [CSRF Debug] Output\n\nIch sehe dann:\n- Ob headerToken vorhanden ist\n- Ob cookieToken vorhanden ist \n- Ob sie übereinstimmen\n\n---\n\nStripe Portal 500 Error ist separates Problem:\nhttps://dashboard.stripe.com/test/settings/billing/portal\n→ Customer Portal Configuration muss erstellt werden\n\")" "Bash(echo \"\n\n## CSRF Debug aktiviert!\n\nBitte teste jetzt:\n1. Browser zu http://localhost:3050/create\n2. Dynamic QR Code erstellen versuchen\n3. Server-Logs zeigen jetzt [CSRF Debug] Output\n\nIch sehe dann:\n- Ob headerToken vorhanden ist\n- Ob cookieToken vorhanden ist \n- Ob sie übereinstimmen\n\n---\n\nStripe Portal 500 Error ist separates Problem:\nhttps://dashboard.stripe.com/test/settings/billing/portal\n→ Customer Portal Configuration muss erstellt werden\n\")",
"Bash(pkill:*)"
], ],
"deny": [], "deny": [],
"ask": [] "ask": []

98
package-lock.json generated
View File

@ -33,6 +33,7 @@
"react-dom": "^18.2.0", "react-dom": "^18.2.0",
"react-dropzone": "^14.2.3", "react-dropzone": "^14.2.3",
"react-i18next": "^13.5.0", "react-i18next": "^13.5.0",
"resend": "^6.4.2",
"sharp": "^0.33.1", "sharp": "^0.33.1",
"stripe": "^19.1.0", "stripe": "^19.1.0",
"tailwind-merge": "^2.2.0", "tailwind-merge": "^2.2.0",
@ -1508,6 +1509,12 @@
"dev": true, "dev": true,
"license": "MIT" "license": "MIT"
}, },
"node_modules/@stablelib/base64": {
"version": "1.0.1",
"resolved": "https://registry.npmjs.org/@stablelib/base64/-/base64-1.0.1.tgz",
"integrity": "sha512-1bnPQqSxSuc3Ii6MhBysoWCg58j97aUjuCSZrGSmDxNqtytIi0k8utUenAwTZN4V5mXXYGsVUI9zeBqy+jBOSQ==",
"license": "MIT"
},
"node_modules/@stripe/stripe-js": { "node_modules/@stripe/stripe-js": {
"version": "8.3.0", "version": "8.3.0",
"resolved": "https://registry.npmjs.org/@stripe/stripe-js/-/stripe-js-8.3.0.tgz", "resolved": "https://registry.npmjs.org/@stripe/stripe-js/-/stripe-js-8.3.0.tgz",
@ -3441,6 +3448,12 @@
"url": "https://github.com/sponsors/ljharb" "url": "https://github.com/sponsors/ljharb"
} }
}, },
"node_modules/es6-promise": {
"version": "4.2.8",
"resolved": "https://registry.npmjs.org/es6-promise/-/es6-promise-4.2.8.tgz",
"integrity": "sha512-HJDGx5daxeIvxdBxvG2cb9g4tEvwIk3i8+nhX0yGrYmZUzbkdg8QbDevheDB8gd0//uPj4c1EQua8Q+MViT0/w==",
"license": "MIT"
},
"node_modules/esbuild": { "node_modules/esbuild": {
"version": "0.25.12", "version": "0.25.12",
"resolved": "https://registry.npmjs.org/esbuild/-/esbuild-0.25.12.tgz", "resolved": "https://registry.npmjs.org/esbuild/-/esbuild-0.25.12.tgz",
@ -4005,6 +4018,12 @@
"dev": true, "dev": true,
"license": "MIT" "license": "MIT"
}, },
"node_modules/fast-sha256": {
"version": "1.3.0",
"resolved": "https://registry.npmjs.org/fast-sha256/-/fast-sha256-1.3.0.tgz",
"integrity": "sha512-n11RGP/lrWEFI/bWdygLxhI+pVeo1ZYIVwvvPkW7azl/rOy+F3HYRZ2K5zeE9mmkhQppyv9sQFx0JM9UabnpPQ==",
"license": "Unlicense"
},
"node_modules/fastq": { "node_modules/fastq": {
"version": "1.19.1", "version": "1.19.1",
"resolved": "https://registry.npmjs.org/fastq/-/fastq-1.19.1.tgz", "resolved": "https://registry.npmjs.org/fastq/-/fastq-1.19.1.tgz",
@ -6471,6 +6490,12 @@
"url": "https://github.com/sponsors/ljharb" "url": "https://github.com/sponsors/ljharb"
} }
}, },
"node_modules/querystringify": {
"version": "2.2.0",
"resolved": "https://registry.npmjs.org/querystringify/-/querystringify-2.2.0.tgz",
"integrity": "sha512-FIqgj2EUvTa7R50u0rGsyTftzjYmv/a3hO345bZNrqabNqjtgiDMgmo4mkUjd+nzU5oF3dClKqFIPUKybUyqoQ==",
"license": "MIT"
},
"node_modules/queue-microtask": { "node_modules/queue-microtask": {
"version": "1.2.3", "version": "1.2.3",
"resolved": "https://registry.npmjs.org/queue-microtask/-/queue-microtask-1.2.3.tgz", "resolved": "https://registry.npmjs.org/queue-microtask/-/queue-microtask-1.2.3.tgz",
@ -6690,6 +6715,32 @@
"integrity": "sha512-NKN5kMDylKuldxYLSUfrbo5Tuzh4hd+2E8NPPX02mZtn1VuREQToYe/ZdlJy+J3uCpfaiGF05e7B8W0iXbQHmg==", "integrity": "sha512-NKN5kMDylKuldxYLSUfrbo5Tuzh4hd+2E8NPPX02mZtn1VuREQToYe/ZdlJy+J3uCpfaiGF05e7B8W0iXbQHmg==",
"license": "ISC" "license": "ISC"
}, },
"node_modules/requires-port": {
"version": "1.0.0",
"resolved": "https://registry.npmjs.org/requires-port/-/requires-port-1.0.0.tgz",
"integrity": "sha512-KigOCHcocU3XODJxsu8i/j8T9tzT4adHiecwORRQ0ZZFcp7ahwXuRU1m+yuO90C5ZUyGeGfocHDI14M3L3yDAQ==",
"license": "MIT"
},
"node_modules/resend": {
"version": "6.4.2",
"resolved": "https://registry.npmjs.org/resend/-/resend-6.4.2.tgz",
"integrity": "sha512-YnxmwneltZtjc7Xff+8ZjG1/xPLdstCiqsedgO/JxWTf7vKRAPCx6CkhQ3ZXskG0mrmf8+I5wr/wNRd8PQMUfw==",
"license": "MIT",
"dependencies": {
"svix": "1.76.1"
},
"engines": {
"node": ">=18"
},
"peerDependencies": {
"@react-email/render": "*"
},
"peerDependenciesMeta": {
"@react-email/render": {
"optional": true
}
}
},
"node_modules/resolve": { "node_modules/resolve": {
"version": "1.22.11", "version": "1.22.11",
"resolved": "https://registry.npmjs.org/resolve/-/resolve-1.22.11.tgz", "resolved": "https://registry.npmjs.org/resolve/-/resolve-1.22.11.tgz",
@ -7507,6 +7558,42 @@
"url": "https://github.com/sponsors/ljharb" "url": "https://github.com/sponsors/ljharb"
} }
}, },
"node_modules/svix": {
"version": "1.76.1",
"resolved": "https://registry.npmjs.org/svix/-/svix-1.76.1.tgz",
"integrity": "sha512-CRuDWBTgYfDnBLRaZdKp9VuoPcNUq9An14c/k+4YJ15Qc5Grvf66vp0jvTltd4t7OIRj+8lM1DAgvSgvf7hdLw==",
"license": "MIT",
"dependencies": {
"@stablelib/base64": "^1.0.0",
"@types/node": "^22.7.5",
"es6-promise": "^4.2.8",
"fast-sha256": "^1.3.0",
"url-parse": "^1.5.10",
"uuid": "^10.0.0"
}
},
"node_modules/svix/node_modules/@types/node": {
"version": "22.19.1",
"resolved": "https://registry.npmjs.org/@types/node/-/node-22.19.1.tgz",
"integrity": "sha512-LCCV0HdSZZZb34qifBsyWlUmok6W7ouER+oQIGBScS8EsZsQbrtFTUrDX4hOl+CS6p7cnNC4td+qrSVGSCTUfQ==",
"license": "MIT",
"dependencies": {
"undici-types": "~6.21.0"
}
},
"node_modules/svix/node_modules/uuid": {
"version": "10.0.0",
"resolved": "https://registry.npmjs.org/uuid/-/uuid-10.0.0.tgz",
"integrity": "sha512-8XkAphELsDnEGrDxUOHB3RGvXz6TeuYSGEZBOjtTtPm2lwhGBjLgOzLHB63IUWfBpNucQjND6d3AOudO+H3RWQ==",
"funding": [
"https://github.com/sponsors/broofa",
"https://github.com/sponsors/ctavan"
],
"license": "MIT",
"bin": {
"uuid": "dist/bin/uuid"
}
},
"node_modules/tailwind-merge": { "node_modules/tailwind-merge": {
"version": "2.6.0", "version": "2.6.0",
"resolved": "https://registry.npmjs.org/tailwind-merge/-/tailwind-merge-2.6.0.tgz", "resolved": "https://registry.npmjs.org/tailwind-merge/-/tailwind-merge-2.6.0.tgz",
@ -7838,7 +7925,6 @@
"version": "6.21.0", "version": "6.21.0",
"resolved": "https://registry.npmjs.org/undici-types/-/undici-types-6.21.0.tgz", "resolved": "https://registry.npmjs.org/undici-types/-/undici-types-6.21.0.tgz",
"integrity": "sha512-iwDZqg0QAGrg9Rav5H4n0M64c3mkR59cJ6wQp+7C4nI0gsmExaedaYLNO44eT4AtBBwjbTiGPMlt2Md0T9H9JQ==", "integrity": "sha512-iwDZqg0QAGrg9Rav5H4n0M64c3mkR59cJ6wQp+7C4nI0gsmExaedaYLNO44eT4AtBBwjbTiGPMlt2Md0T9H9JQ==",
"dev": true,
"license": "MIT" "license": "MIT"
}, },
"node_modules/unrs-resolver": { "node_modules/unrs-resolver": {
@ -7917,6 +8003,16 @@
"punycode": "^2.1.0" "punycode": "^2.1.0"
} }
}, },
"node_modules/url-parse": {
"version": "1.5.10",
"resolved": "https://registry.npmjs.org/url-parse/-/url-parse-1.5.10.tgz",
"integrity": "sha512-WypcfiRhfeUP9vvF0j6rw0J3hrWrw6iZv3+22h6iRMJ/8z1Tj6XfLP4DsUix5MhMPnXpiHDoKyoZ/bdCkwBCiQ==",
"license": "MIT",
"dependencies": {
"querystringify": "^2.1.1",
"requires-port": "^1.0.0"
}
},
"node_modules/util-deprecate": { "node_modules/util-deprecate": {
"version": "1.0.2", "version": "1.0.2",
"resolved": "https://registry.npmjs.org/util-deprecate/-/util-deprecate-1.0.2.tgz", "resolved": "https://registry.npmjs.org/util-deprecate/-/util-deprecate-1.0.2.tgz",

View File

@ -49,6 +49,7 @@
"react-dom": "^18.2.0", "react-dom": "^18.2.0",
"react-dropzone": "^14.2.3", "react-dropzone": "^14.2.3",
"react-i18next": "^13.5.0", "react-i18next": "^13.5.0",
"resend": "^6.4.2",
"sharp": "^0.33.1", "sharp": "^0.33.1",
"stripe": "^19.1.0", "stripe": "^19.1.0",
"tailwind-merge": "^2.2.0", "tailwind-merge": "^2.2.0",

View File

@ -28,6 +28,10 @@ model User {
stripeCurrentPeriodEnd DateTime? stripeCurrentPeriodEnd DateTime?
plan Plan @default(FREE) plan Plan @default(FREE)
// Password reset fields
resetPasswordToken String? @unique
resetPasswordExpires DateTime?
qrCodes QRCode[] qrCodes QRCode[]
integrations Integration[] integrations Integration[]
accounts Account[] accounts Account[]

View File

@ -6,11 +6,13 @@ import { Card, CardHeader, CardTitle, CardContent } from '@/components/ui/Card';
import { Button } from '@/components/ui/Button'; import { Button } from '@/components/ui/Button';
import { Input } from '@/components/ui/Input'; import { Input } from '@/components/ui/Input';
import { showToast } from '@/components/ui/Toast'; import { showToast } from '@/components/ui/Toast';
import { useCsrf } from '@/hooks/useCsrf';
export default function EditQRPage() { export default function EditQRPage() {
const router = useRouter(); const router = useRouter();
const params = useParams(); const params = useParams();
const qrId = params.id as string; const qrId = params.id as string;
const { fetchWithCsrf, loading: csrfLoading } = useCsrf();
const [loading, setLoading] = useState(true); const [loading, setLoading] = useState(true);
const [saving, setSaving] = useState(false); const [saving, setSaving] = useState(false);
@ -47,11 +49,8 @@ export default function EditQRPage() {
setSaving(true); setSaving(true);
try { try {
const response = await fetch(`/api/qrs/${qrId}`, { const response = await fetchWithCsrf(`/api/qrs/${qrId}`, {
method: 'PATCH', method: 'PATCH',
headers: {
'Content-Type': 'application/json',
},
body: JSON.stringify({ body: JSON.stringify({
title, title,
content, content,
@ -253,8 +252,9 @@ export default function EditQRPage() {
<Button <Button
onClick={handleSave} onClick={handleSave}
loading={saving} loading={saving}
disabled={csrfLoading || saving}
> >
Save Changes {csrfLoading ? 'Loading...' : 'Save Changes'}
</Button> </Button>
</div> </div>
</CardContent> </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> </p>
</div> </div>
{/* Action Buttons */} {/* Action Button */}
<div className="flex flex-col sm:flex-row gap-4 justify-center items-center"> <div className="flex justify-center">
<Link href="/"> <Link href="/">
<Button size="lg"> <Button size="lg">
<svg <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" 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> </svg>
Go Home Back to Home
</Button> </Button>
</Link> </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> </div>
</div> </div>

104
src/lib/email.ts Normal file
View File

@ -0,0 +1,104 @@
import { Resend } from 'resend';
const resend = new Resend(process.env.RESEND_API_KEY);
export async function sendPasswordResetEmail(email: string, resetToken: string) {
const appUrl = process.env.NEXT_PUBLIC_APP_URL || 'http://localhost:3050';
const resetUrl = `${appUrl}/reset-password?token=${resetToken}`;
try {
await resend.emails.send({
from: 'QR Master <onboarding@resend.dev>', // Use Resend's testing domain
to: email,
subject: 'Reset Your Password - QR Master',
html: `
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Reset Your Password</title>
</head>
<body style="margin: 0; padding: 0; font-family: Arial, sans-serif; background-color: #f4f4f4;">
<table width="100%" cellpadding="0" cellspacing="0" style="background-color: #f4f4f4; padding: 20px 0;">
<tr>
<td align="center">
<table width="600" cellpadding="0" cellspacing="0" style="background-color: #ffffff; border-radius: 8px; overflow: hidden; box-shadow: 0 2px 8px rgba(0,0,0,0.1);">
<!-- Header -->
<tr>
<td style="background: linear-gradient(135deg, #667eea 0%, #764ba2 100%); padding: 40px 30px; text-align: center;">
<h1 style="margin: 0; color: #ffffff; font-size: 28px; font-weight: bold;">QR Master</h1>
</td>
</tr>
<!-- Content -->
<tr>
<td style="padding: 40px 30px;">
<h2 style="margin: 0 0 20px 0; color: #333333; font-size: 24px;">Reset Your Password</h2>
<p style="margin: 0 0 20px 0; color: #666666; font-size: 16px; line-height: 1.5;">
Hi there,
</p>
<p style="margin: 0 0 30px 0; color: #666666; font-size: 16px; line-height: 1.5;">
You requested to reset your password for your QR Master account. Click the button below to choose a new password:
</p>
<!-- Button -->
<table width="100%" cellpadding="0" cellspacing="0">
<tr>
<td align="center" style="padding: 20px 0;">
<a href="${resetUrl}" style="background: linear-gradient(135deg, #667eea 0%, #764ba2 100%); color: #ffffff; text-decoration: none; padding: 16px 40px; border-radius: 6px; font-size: 16px; font-weight: bold; display: inline-block;">
Reset Password
</a>
</td>
</tr>
</table>
<p style="margin: 30px 0 20px 0; color: #666666; font-size: 14px; line-height: 1.5;">
Or copy and paste this link into your browser:
</p>
<p style="margin: 0 0 30px 0; padding: 15px; background-color: #f8f8f8; border-radius: 4px; word-break: break-all;">
<a href="${resetUrl}" style="color: #667eea; text-decoration: none; font-size: 14px;">${resetUrl}</a>
</p>
<div style="border-top: 1px solid #eeeeee; padding-top: 20px; margin-top: 30px;">
<p style="margin: 0 0 10px 0; color: #999999; font-size: 13px; line-height: 1.5;">
<strong>This link will expire in 1 hour.</strong>
</p>
<p style="margin: 0; color: #999999; font-size: 13px; line-height: 1.5;">
If you didn't request a password reset, you can safely ignore this email. Your password will not be changed.
</p>
</div>
</td>
</tr>
<!-- Footer -->
<tr>
<td style="background-color: #f8f8f8; padding: 30px; text-align: center; border-top: 1px solid #eeeeee;">
<p style="margin: 0 0 10px 0; color: #999999; font-size: 12px;">
© 2025 QR Master. All rights reserved.
</p>
<p style="margin: 0; color: #999999; font-size: 12px;">
This is an automated email. Please do not reply.
</p>
</td>
</tr>
</table>
</td>
</tr>
</table>
</body>
</html>
`,
});
console.log('Password reset email sent successfully to:', email);
return { success: true };
} catch (error) {
console.error('Error sending password reset email:', error);
throw new Error('Failed to send password reset email');
}
}