Compare commits
3 Commits
c11565aaf8
...
v1.0.4
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
8ef2cbe68e | ||
|
|
b75bf9bb30 | ||
|
|
25d3d553ff |
@@ -31,6 +31,18 @@ const nextConfig = {
|
||||
key: 'Cross-Origin-Opener-Policy',
|
||||
value: 'same-origin',
|
||||
},
|
||||
{
|
||||
key: 'Strict-Transport-Security',
|
||||
value: 'max-age=63072000; includeSubDomains; preload',
|
||||
},
|
||||
{
|
||||
key: 'X-DNS-Prefetch-Control',
|
||||
value: 'on',
|
||||
},
|
||||
{
|
||||
key: 'X-XSS-Protection',
|
||||
value: '1; mode=block',
|
||||
},
|
||||
{
|
||||
key: 'Content-Security-Policy',
|
||||
value: [
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
{
|
||||
"name": "lageplan",
|
||||
"version": "1.0.2",
|
||||
"version": "1.0.4",
|
||||
"description": "Feuerwehr Lageplan - Krokier-App für Einsatzdokumentation",
|
||||
"private": true,
|
||||
"scripts": {
|
||||
|
||||
@@ -2,9 +2,16 @@ import { NextRequest, NextResponse } from 'next/server'
|
||||
import { getSession } from '@/lib/auth'
|
||||
import { prisma } from '@/lib/db'
|
||||
import bcrypt from 'bcryptjs'
|
||||
import { rateLimit, getClientIp, rateLimitResponse } from '@/lib/rate-limit'
|
||||
|
||||
const changePwLimiter = rateLimit({ id: 'change-pw', max: 5, windowSeconds: 60 * 15 })
|
||||
|
||||
export async function POST(req: NextRequest) {
|
||||
try {
|
||||
const ip = getClientIp(req)
|
||||
const rl = changePwLimiter.check(ip)
|
||||
if (!rl.success) return rateLimitResponse(rl.resetAt)
|
||||
|
||||
const user = await getSession()
|
||||
if (!user) return NextResponse.json({ error: 'Nicht autorisiert' }, { status: 401 })
|
||||
|
||||
@@ -14,8 +21,8 @@ export async function POST(req: NextRequest) {
|
||||
return NextResponse.json({ error: 'Beide Felder sind erforderlich' }, { status: 400 })
|
||||
}
|
||||
|
||||
if (newPassword.length < 6) {
|
||||
return NextResponse.json({ error: 'Neues Kennwort muss mindestens 6 Zeichen lang sein' }, { status: 400 })
|
||||
if (newPassword.length < 8) {
|
||||
return NextResponse.json({ error: 'Neues Kennwort muss mindestens 8 Zeichen lang sein' }, { status: 400 })
|
||||
}
|
||||
|
||||
const dbUser = await (prisma as any).user.findUnique({
|
||||
|
||||
70
src/app/api/auth/delete-account/route.ts
Normal file
70
src/app/api/auth/delete-account/route.ts
Normal file
@@ -0,0 +1,70 @@
|
||||
import { NextRequest, NextResponse } from 'next/server'
|
||||
import { prisma } from '@/lib/db'
|
||||
import { getSession } from '@/lib/auth'
|
||||
import bcrypt from 'bcryptjs'
|
||||
import { cookies } from 'next/headers'
|
||||
import { deleteAccountLimiter, getClientIp, rateLimitResponse } from '@/lib/rate-limit'
|
||||
|
||||
// POST: User deletes their own account
|
||||
export async function POST(req: NextRequest) {
|
||||
try {
|
||||
const ip = getClientIp(req)
|
||||
const rl = deleteAccountLimiter.check(ip)
|
||||
if (!rl.success) return rateLimitResponse(rl.resetAt)
|
||||
|
||||
const session = await getSession()
|
||||
if (!session) return NextResponse.json({ error: 'Nicht autorisiert' }, { status: 401 })
|
||||
|
||||
const { password } = await req.json()
|
||||
if (!password) {
|
||||
return NextResponse.json({ error: 'Passwort erforderlich' }, { status: 400 })
|
||||
}
|
||||
|
||||
// Verify password
|
||||
const user = await (prisma as any).user.findUnique({
|
||||
where: { id: session.id },
|
||||
select: { id: true, password: true, role: true },
|
||||
})
|
||||
if (!user) return NextResponse.json({ error: 'Benutzer nicht gefunden' }, { status: 404 })
|
||||
|
||||
const validPw = await bcrypt.compare(password, user.password)
|
||||
if (!validPw) {
|
||||
return NextResponse.json({ error: 'Falsches Passwort' }, { status: 403 })
|
||||
}
|
||||
|
||||
// If user is the only TENANT_ADMIN, they must delete the org first or transfer ownership
|
||||
if (session.tenantId && session.role === 'TENANT_ADMIN') {
|
||||
const adminCount = await (prisma as any).tenantMembership.count({
|
||||
where: { tenantId: session.tenantId, role: 'TENANT_ADMIN' },
|
||||
})
|
||||
if (adminCount <= 1) {
|
||||
return NextResponse.json({
|
||||
error: 'Sie sind der einzige Administrator. Bitte löschen Sie die Organisation unter Einstellungen oder übertragen Sie die Admin-Rolle.',
|
||||
}, { status: 400 })
|
||||
}
|
||||
}
|
||||
|
||||
console.log(`[Account Delete] User ${session.id} (${session.email}) deleting own account`)
|
||||
|
||||
// Clean up user data
|
||||
try { await (prisma as any).upgradeRequest.deleteMany({ where: { requestedById: session.id } }) } catch {}
|
||||
try { await (prisma as any).iconAsset.updateMany({ where: { ownerId: session.id }, data: { ownerId: null } }) } catch {}
|
||||
try { await (prisma as any).project.updateMany({ where: { ownerId: session.id }, data: { ownerId: null } }) } catch {}
|
||||
|
||||
// Remove memberships
|
||||
await (prisma as any).tenantMembership.deleteMany({ where: { userId: session.id } })
|
||||
|
||||
// Delete user
|
||||
await (prisma as any).user.delete({ where: { id: session.id } })
|
||||
|
||||
// Clear auth cookie
|
||||
;(await cookies()).delete('auth-token')
|
||||
|
||||
console.log(`[Account Delete] User ${session.email} deleted successfully`)
|
||||
|
||||
return NextResponse.json({ success: true, message: 'Konto wurde gelöscht' })
|
||||
} catch (error: any) {
|
||||
console.error('[Account Delete] Error:', error?.message || error)
|
||||
return NextResponse.json({ error: 'Löschung fehlgeschlagen' }, { status: 500 })
|
||||
}
|
||||
}
|
||||
@@ -2,9 +2,14 @@ import { NextRequest, NextResponse } from 'next/server'
|
||||
import { prisma } from '@/lib/db'
|
||||
import { randomBytes } from 'crypto'
|
||||
import { sendEmail, getSmtpConfig } from '@/lib/email'
|
||||
import { forgotPasswordLimiter, getClientIp, rateLimitResponse } from '@/lib/rate-limit'
|
||||
|
||||
export async function POST(req: NextRequest) {
|
||||
try {
|
||||
const ip = getClientIp(req)
|
||||
const rl = forgotPasswordLimiter.check(ip)
|
||||
if (!rl.success) return rateLimitResponse(rl.resetAt)
|
||||
|
||||
const { email } = await req.json()
|
||||
if (!email) {
|
||||
return NextResponse.json({ error: 'E-Mail erforderlich' }, { status: 400 })
|
||||
|
||||
@@ -3,9 +3,14 @@ import { cookies } from 'next/headers'
|
||||
import { login, createToken } from '@/lib/auth'
|
||||
import { loginSchema } from '@/lib/validations'
|
||||
import { prisma } from '@/lib/db'
|
||||
import { loginLimiter, getClientIp, rateLimitResponse } from '@/lib/rate-limit'
|
||||
|
||||
export async function POST(request: NextRequest) {
|
||||
try {
|
||||
const ip = getClientIp(request)
|
||||
const rl = loginLimiter.check(ip)
|
||||
if (!rl.success) return rateLimitResponse(rl.resetAt)
|
||||
|
||||
const body = await request.json()
|
||||
|
||||
const validated = loginSchema.safeParse(body)
|
||||
|
||||
@@ -4,16 +4,21 @@ import { hashPassword } from '@/lib/auth'
|
||||
import { sendEmail } from '@/lib/email'
|
||||
import { randomBytes } from 'crypto'
|
||||
import { z } from 'zod'
|
||||
import { registerLimiter, getClientIp, rateLimitResponse } from '@/lib/rate-limit'
|
||||
|
||||
const registerSchema = z.object({
|
||||
organizationName: z.string().min(2, 'Organisationsname zu kurz').max(200),
|
||||
name: z.string().min(2, 'Name zu kurz').max(200),
|
||||
email: z.string().email('Ungültige E-Mail-Adresse'),
|
||||
password: z.string().min(6, 'Passwort muss mindestens 6 Zeichen haben'),
|
||||
password: z.string().min(8, 'Passwort muss mindestens 8 Zeichen haben'),
|
||||
})
|
||||
|
||||
export async function POST(req: NextRequest) {
|
||||
try {
|
||||
const ip = getClientIp(req)
|
||||
const rl = registerLimiter.check(ip)
|
||||
if (!rl.success) return rateLimitResponse(rl.resetAt)
|
||||
|
||||
const body = await req.json()
|
||||
const data = registerSchema.parse(body)
|
||||
|
||||
|
||||
75
src/app/api/auth/resend-verification/route.ts
Normal file
75
src/app/api/auth/resend-verification/route.ts
Normal file
@@ -0,0 +1,75 @@
|
||||
import { NextRequest, NextResponse } from 'next/server'
|
||||
import { prisma } from '@/lib/db'
|
||||
import { sendEmail } from '@/lib/email'
|
||||
import { randomBytes } from 'crypto'
|
||||
import { resendVerificationLimiter, getClientIp, rateLimitResponse } from '@/lib/rate-limit'
|
||||
|
||||
export async function POST(req: NextRequest) {
|
||||
try {
|
||||
const ip = getClientIp(req)
|
||||
const rl = resendVerificationLimiter.check(ip)
|
||||
if (!rl.success) return rateLimitResponse(rl.resetAt)
|
||||
|
||||
const { email } = await req.json()
|
||||
|
||||
if (!email) {
|
||||
return NextResponse.json({ error: 'E-Mail-Adresse erforderlich.' }, { status: 400 })
|
||||
}
|
||||
|
||||
const user = await (prisma as any).user.findUnique({
|
||||
where: { email },
|
||||
include: { memberships: { include: { tenant: true } } },
|
||||
})
|
||||
|
||||
if (!user) {
|
||||
// Don't reveal whether user exists
|
||||
return NextResponse.json({ success: true, message: 'Falls ein Konto mit dieser E-Mail existiert, wurde eine neue Bestätigungsmail gesendet.' })
|
||||
}
|
||||
|
||||
if (user.emailVerified) {
|
||||
return NextResponse.json({ success: true, message: 'Ihre E-Mail-Adresse ist bereits bestätigt. Sie können sich anmelden.' })
|
||||
}
|
||||
|
||||
// Generate new verification token
|
||||
const verificationToken = randomBytes(32).toString('hex')
|
||||
await (prisma as any).user.update({
|
||||
where: { id: user.id },
|
||||
data: { emailVerificationToken: verificationToken },
|
||||
})
|
||||
|
||||
// Build verification URL
|
||||
let baseUrl = process.env.NEXTAUTH_URL || req.headers.get('origin') || `${req.headers.get('x-forwarded-proto') || 'https'}://${req.headers.get('host')}` || 'http://localhost:3000'
|
||||
if (baseUrl && !baseUrl.startsWith('http://') && !baseUrl.startsWith('https://')) {
|
||||
baseUrl = `https://${baseUrl}`
|
||||
}
|
||||
const verifyUrl = `${baseUrl}/api/auth/verify-email?token=${verificationToken}`
|
||||
|
||||
const orgName = user.memberships?.[0]?.tenant?.name || 'Lageplan'
|
||||
|
||||
await sendEmail(
|
||||
user.email,
|
||||
'E-Mail-Adresse bestätigen — Lageplan',
|
||||
`<div style="font-family:sans-serif;max-width:600px;margin:0 auto;">
|
||||
<div style="background:#dc2626;color:white;padding:20px 24px;border-radius:12px 12px 0 0;">
|
||||
<h1 style="margin:0;font-size:22px;">E-Mail bestätigen</h1>
|
||||
</div>
|
||||
<div style="border:1px solid #e5e7eb;border-top:none;padding:24px;border-radius:0 0 12px 12px;">
|
||||
<p>Hallo <strong>${user.name}</strong>,</p>
|
||||
<p>Bitte bestätigen Sie Ihre E-Mail-Adresse, um Ihr Konto für <strong>${orgName}</strong> zu aktivieren.</p>
|
||||
<div style="text-align:center;margin:24px 0;">
|
||||
<a href="${verifyUrl}" style="background:#dc2626;color:white;padding:12px 32px;text-decoration:none;border-radius:8px;font-weight:600;display:inline-block;">
|
||||
E-Mail bestätigen
|
||||
</a>
|
||||
</div>
|
||||
<p style="color:#666;font-size:13px;">Falls der Button nicht funktioniert, kopieren Sie diesen Link:<br/>
|
||||
<a href="${verifyUrl}" style="word-break:break-all;">${verifyUrl}</a></p>
|
||||
</div>
|
||||
</div>`
|
||||
)
|
||||
|
||||
return NextResponse.json({ success: true, message: 'Bestätigungsmail wurde erneut gesendet. Bitte prüfen Sie Ihren Posteingang.' })
|
||||
} catch (error) {
|
||||
console.error('Resend verification error:', error)
|
||||
return NextResponse.json({ error: 'Fehler beim Senden der Bestätigungsmail.' }, { status: 500 })
|
||||
}
|
||||
}
|
||||
@@ -1,16 +1,21 @@
|
||||
import { NextRequest, NextResponse } from 'next/server'
|
||||
import { prisma } from '@/lib/db'
|
||||
import { hashPassword } from '@/lib/auth'
|
||||
import { resetPasswordLimiter, getClientIp, rateLimitResponse } from '@/lib/rate-limit'
|
||||
|
||||
export async function POST(req: NextRequest) {
|
||||
try {
|
||||
const ip = getClientIp(req)
|
||||
const rl = resetPasswordLimiter.check(ip)
|
||||
if (!rl.success) return rateLimitResponse(rl.resetAt)
|
||||
|
||||
const { token, password } = await req.json()
|
||||
if (!token || !password) {
|
||||
return NextResponse.json({ error: 'Token und Passwort erforderlich' }, { status: 400 })
|
||||
}
|
||||
|
||||
if (password.length < 6) {
|
||||
return NextResponse.json({ error: 'Passwort muss mindestens 6 Zeichen lang sein' }, { status: 400 })
|
||||
if (password.length < 8) {
|
||||
return NextResponse.json({ error: 'Passwort muss mindestens 8 Zeichen lang sein' }, { status: 400 })
|
||||
}
|
||||
|
||||
const user = await (prisma as any).user.findFirst({
|
||||
|
||||
@@ -2,6 +2,7 @@ import { NextRequest, NextResponse } from 'next/server'
|
||||
import { prisma } from '@/lib/db'
|
||||
import { sendEmail, getSmtpConfig } from '@/lib/email'
|
||||
import { z } from 'zod'
|
||||
import { contactLimiter, getClientIp, rateLimitResponse } from '@/lib/rate-limit'
|
||||
|
||||
const contactSchema = z.object({
|
||||
name: z.string().min(1).max(200),
|
||||
@@ -23,6 +24,10 @@ async function getContactEmail(): Promise<string> {
|
||||
|
||||
export async function POST(req: NextRequest) {
|
||||
try {
|
||||
const ip = getClientIp(req)
|
||||
const rl = contactLimiter.check(ip)
|
||||
if (!rl.success) return rateLimitResponse(rl.resetAt)
|
||||
|
||||
const body = await req.json()
|
||||
const data = contactSchema.parse(body)
|
||||
|
||||
|
||||
@@ -19,7 +19,7 @@ import { Button } from '@/components/ui/button'
|
||||
import { Dialog, DialogContent, DialogHeader, DialogTitle } from '@/components/ui/dialog'
|
||||
import { JournalView } from '@/components/journal/journal-view'
|
||||
import { jsPDF } from 'jspdf'
|
||||
import { Lock, Unlock, Eye } from 'lucide-react'
|
||||
import { Lock, Unlock, Eye, AlertTriangle } from 'lucide-react'
|
||||
import { getSocket } from '@/lib/socket'
|
||||
import { CustomDragLayer } from '@/components/map/custom-drag-layer'
|
||||
|
||||
@@ -1130,6 +1130,32 @@ export default function AppPage() {
|
||||
}
|
||||
}
|
||||
|
||||
// Draw arrowheads for arrow features
|
||||
for (const f of currentFeatures.filter(f => f.type === 'arrow')) {
|
||||
if (f.geometry.type !== 'LineString') continue
|
||||
const lineCoords = f.geometry.coordinates as number[][]
|
||||
if (lineCoords.length < 2) continue
|
||||
const p1 = lineCoords[lineCoords.length - 2]
|
||||
const p2 = lineCoords[lineCoords.length - 1]
|
||||
const px1 = mapInstance.project(p1 as [number, number])
|
||||
const px2 = mapInstance.project(p2 as [number, number])
|
||||
const angle = Math.atan2(px2.y - px1.y, px2.x - px1.x)
|
||||
const color = (f.properties.color as string) || '#000000'
|
||||
const arrowSize = 14 * dpr
|
||||
|
||||
ctx.save()
|
||||
ctx.translate(px2.x * dpr, px2.y * dpr)
|
||||
ctx.rotate(angle + Math.PI / 2)
|
||||
ctx.beginPath()
|
||||
ctx.moveTo(0, -arrowSize)
|
||||
ctx.lineTo(-arrowSize * 0.7, arrowSize * 0.3)
|
||||
ctx.lineTo(arrowSize * 0.7, arrowSize * 0.3)
|
||||
ctx.closePath()
|
||||
ctx.fillStyle = color
|
||||
ctx.fill()
|
||||
ctx.restore()
|
||||
}
|
||||
|
||||
// Draw line/polygon label markers at midpoints
|
||||
for (const f of currentFeatures.filter(f => f.properties.label && (f.geometry.type === 'LineString' || f.geometry.type === 'Polygon'))) {
|
||||
const label = f.properties.label as string
|
||||
@@ -1363,6 +1389,29 @@ export default function AppPage() {
|
||||
onLogout={logout}
|
||||
/>
|
||||
|
||||
{/* Email verification banner */}
|
||||
{user && user.emailVerified === false && (
|
||||
<div className="flex items-center justify-center gap-3 px-4 py-2 bg-amber-50 dark:bg-amber-950/40 border-b border-amber-200 dark:border-amber-800 text-sm text-amber-800 dark:text-amber-300">
|
||||
<AlertTriangle className="w-4 h-4 shrink-0" />
|
||||
<span>Ihre E-Mail-Adresse wurde noch nicht bestätigt. Bitte prüfen Sie Ihren Posteingang.</span>
|
||||
<button
|
||||
onClick={async () => {
|
||||
try {
|
||||
const res = await fetch('/api/auth/resend-verification', {
|
||||
method: 'POST',
|
||||
headers: { 'Content-Type': 'application/json' },
|
||||
body: JSON.stringify({ email: user.email }),
|
||||
})
|
||||
if (res.ok) toast({ title: 'Bestätigungsmail gesendet', description: 'Bitte prüfen Sie Ihren Posteingang.' })
|
||||
else toast({ title: 'Fehler', description: 'Konnte Bestätigungsmail nicht senden.', variant: 'destructive' })
|
||||
} catch { toast({ title: 'Fehler', description: 'Verbindungsfehler.', variant: 'destructive' }) }
|
||||
}}
|
||||
className="shrink-0 text-xs font-semibold underline hover:no-underline text-amber-700 dark:text-amber-400"
|
||||
>
|
||||
Erneut senden
|
||||
</button>
|
||||
</div>
|
||||
)}
|
||||
|
||||
{/* Live editing banner */}
|
||||
{currentProject && (
|
||||
|
||||
@@ -23,6 +23,8 @@ function LoginForm() {
|
||||
const [email, setEmail] = useState('')
|
||||
const [password, setPassword] = useState('')
|
||||
const [isLoading, setIsLoading] = useState(false)
|
||||
const [resendLoading, setResendLoading] = useState(false)
|
||||
const [resendSuccess, setResendSuccess] = useState(false)
|
||||
const [tenantLogo, setTenantLogo] = useState<string | null>(null)
|
||||
const [tenantName, setTenantName] = useState<string | null>(null)
|
||||
const { login } = useAuth()
|
||||
@@ -110,7 +112,32 @@ function LoginForm() {
|
||||
)}
|
||||
{errorParam === 'invalid-token' && (
|
||||
<div className="bg-red-50 dark:bg-red-950/30 border border-red-200 dark:border-red-800 rounded-lg p-3 mb-4 text-sm text-red-700 dark:text-red-400 text-center">
|
||||
Ungültiger oder abgelaufener Bestätigungslink.
|
||||
<p>Ungültiger oder abgelaufener Bestätigungslink.</p>
|
||||
<p className="mt-1 text-xs">Geben Sie Ihre E-Mail ein und klicken Sie unten, um einen neuen Link zu erhalten.</p>
|
||||
{resendSuccess ? (
|
||||
<p className="mt-2 text-green-600 dark:text-green-400 font-medium">Neue Bestätigungsmail gesendet!</p>
|
||||
) : (
|
||||
<button
|
||||
type="button"
|
||||
disabled={resendLoading || !email}
|
||||
onClick={async () => {
|
||||
setResendLoading(true)
|
||||
try {
|
||||
const res = await fetch('/api/auth/resend-verification', {
|
||||
method: 'POST',
|
||||
headers: { 'Content-Type': 'application/json' },
|
||||
body: JSON.stringify({ email }),
|
||||
})
|
||||
if (res.ok) setResendSuccess(true)
|
||||
else toast({ title: 'Fehler', description: 'Konnte Bestätigungsmail nicht senden.', variant: 'destructive' })
|
||||
} catch { toast({ title: 'Fehler', description: 'Verbindungsfehler.', variant: 'destructive' }) }
|
||||
setResendLoading(false)
|
||||
}}
|
||||
className="mt-2 text-xs font-medium text-red-600 dark:text-red-400 underline hover:no-underline disabled:opacity-50"
|
||||
>
|
||||
{resendLoading ? 'Wird gesendet...' : 'Bestätigungsmail erneut senden'}
|
||||
</button>
|
||||
)}
|
||||
</div>
|
||||
)}
|
||||
|
||||
|
||||
@@ -30,8 +30,8 @@ export default function RegisterPage() {
|
||||
return
|
||||
}
|
||||
|
||||
if (password.length < 6) {
|
||||
toast({ title: 'Passwort muss mindestens 6 Zeichen haben', variant: 'destructive' })
|
||||
if (password.length < 8) {
|
||||
toast({ title: 'Passwort muss mindestens 8 Zeichen haben', variant: 'destructive' })
|
||||
return
|
||||
}
|
||||
|
||||
@@ -163,7 +163,7 @@ export default function RegisterPage() {
|
||||
<Input
|
||||
id="password"
|
||||
type="password"
|
||||
placeholder="Mindestens 6 Zeichen"
|
||||
placeholder="Mindestens 8 Zeichen"
|
||||
value={password}
|
||||
onChange={(e) => setPassword(e.target.value)}
|
||||
required
|
||||
|
||||
@@ -32,8 +32,8 @@ function ResetPasswordForm() {
|
||||
e.preventDefault()
|
||||
setError('')
|
||||
|
||||
if (password.length < 6) {
|
||||
setError('Passwort muss mindestens 6 Zeichen lang sein.')
|
||||
if (password.length < 8) {
|
||||
setError('Passwort muss mindestens 8 Zeichen lang sein.')
|
||||
return
|
||||
}
|
||||
if (password !== confirmPassword) {
|
||||
@@ -108,7 +108,7 @@ function ResetPasswordForm() {
|
||||
<Input
|
||||
id="password"
|
||||
type="password"
|
||||
placeholder="Min. 6 Zeichen"
|
||||
placeholder="Min. 8 Zeichen"
|
||||
value={password}
|
||||
onChange={(e) => setPassword(e.target.value)}
|
||||
required
|
||||
|
||||
@@ -1030,8 +1030,8 @@ export function JournalView({ projectId, projectTitle, projectLocation, einsatzl
|
||||
if (mapRef?.current) {
|
||||
const canvas = mapRef.current.getCanvas()
|
||||
if (canvas) {
|
||||
// Resize to max 1600px wide and convert to JPEG
|
||||
const maxW = 1600
|
||||
// Resize to max 2400px wide and convert to JPEG
|
||||
const maxW = 2400
|
||||
const ratio = Math.min(1, maxW / canvas.width)
|
||||
const offscreen = document.createElement('canvas')
|
||||
offscreen.width = Math.round(canvas.width * ratio)
|
||||
@@ -1039,18 +1039,18 @@ export function JournalView({ projectId, projectTitle, projectLocation, einsatzl
|
||||
const ctx = offscreen.getContext('2d')
|
||||
if (ctx) {
|
||||
ctx.drawImage(canvas, 0, 0, offscreen.width, offscreen.height)
|
||||
mapScreenshot = offscreen.toDataURL('image/jpeg', 0.75)
|
||||
mapScreenshot = offscreen.toDataURL('image/jpeg', 0.85)
|
||||
}
|
||||
}
|
||||
}
|
||||
} catch (e) { console.warn('Map screenshot failed:', e) }
|
||||
} else if (rawScreenshot.length > 500000) {
|
||||
} else if (rawScreenshot.length > 800000) {
|
||||
// Compress pre-captured screenshot if too large
|
||||
try {
|
||||
const img = new Image()
|
||||
img.src = rawScreenshot
|
||||
await new Promise(r => { img.onload = r; img.onerror = r })
|
||||
const maxW = 1600
|
||||
const maxW = 2400
|
||||
const ratio = Math.min(1, maxW / img.naturalWidth)
|
||||
const offscreen = document.createElement('canvas')
|
||||
offscreen.width = Math.round(img.naturalWidth * ratio)
|
||||
@@ -1058,7 +1058,7 @@ export function JournalView({ projectId, projectTitle, projectLocation, einsatzl
|
||||
const ctx = offscreen.getContext('2d')
|
||||
if (ctx) {
|
||||
ctx.drawImage(img, 0, 0, offscreen.width, offscreen.height)
|
||||
mapScreenshot = offscreen.toDataURL('image/jpeg', 0.75)
|
||||
mapScreenshot = offscreen.toDataURL('image/jpeg', 0.85)
|
||||
}
|
||||
} catch { mapScreenshot = rawScreenshot }
|
||||
} else {
|
||||
|
||||
@@ -91,6 +91,10 @@ export function Topbar({
|
||||
const [isLoadDialogOpen, setIsLoadDialogOpen] = useState(false)
|
||||
const [isHoseSettingsOpen, setIsHoseSettingsOpen] = useState(false)
|
||||
const [showPasswordDialog, setShowPasswordDialog] = useState(false)
|
||||
const [showDeleteAccountDialog, setShowDeleteAccountDialog] = useState(false)
|
||||
const [deleteAccountPw, setDeleteAccountPw] = useState('')
|
||||
const [deleteAccountLoading, setDeleteAccountLoading] = useState(false)
|
||||
const [deleteAccountError, setDeleteAccountError] = useState('')
|
||||
const [pwOld, setPwOld] = useState('')
|
||||
const [pwNew, setPwNew] = useState('')
|
||||
const [pwConfirm, setPwConfirm] = useState('')
|
||||
@@ -290,6 +294,13 @@ export function Topbar({
|
||||
Administration
|
||||
</DropdownMenuItem>
|
||||
)}
|
||||
<DropdownMenuItem
|
||||
onClick={() => { setShowDeleteAccountDialog(true); setDeleteAccountPw(''); setDeleteAccountError('') }}
|
||||
className="text-destructive focus:text-destructive"
|
||||
>
|
||||
<Trash2 className="w-4 h-4 mr-2" />
|
||||
Konto löschen
|
||||
</DropdownMenuItem>
|
||||
<DropdownMenuItem onClick={onLogout} className="text-destructive focus:text-destructive">
|
||||
<LogOut className="w-4 h-4 mr-2" />
|
||||
Abmelden
|
||||
@@ -539,6 +550,81 @@ export function Topbar({
|
||||
</div>
|
||||
</DialogContent>
|
||||
</Dialog>
|
||||
|
||||
{/* Delete Account Dialog */}
|
||||
<Dialog open={showDeleteAccountDialog} onOpenChange={setShowDeleteAccountDialog}>
|
||||
<DialogContent className="max-w-sm">
|
||||
<DialogHeader>
|
||||
<DialogTitle className="flex items-center gap-2 text-destructive">
|
||||
<AlertTriangle className="w-5 h-5" />
|
||||
Konto löschen
|
||||
</DialogTitle>
|
||||
</DialogHeader>
|
||||
<div className="space-y-4">
|
||||
<p className="text-sm text-muted-foreground">
|
||||
Ihr Konto wird unwiderruflich gelöscht. Ihre Projekte und Daten bleiben der Organisation erhalten,
|
||||
aber Ihr persönlicher Zugang wird entfernt.
|
||||
</p>
|
||||
{userRole === 'TENANT_ADMIN' && (
|
||||
<div className="bg-amber-50 dark:bg-amber-950/30 rounded-lg p-3 text-xs text-amber-800 dark:text-amber-300 border border-amber-200 dark:border-amber-800">
|
||||
<strong>Hinweis:</strong> Als einziger Administrator müssen Sie zuerst die Organisation unter Einstellungen löschen oder die Admin-Rolle übertragen.
|
||||
</div>
|
||||
)}
|
||||
<div className="space-y-1.5">
|
||||
<label className="text-sm font-medium">Passwort zur Bestätigung</label>
|
||||
<input
|
||||
type="password"
|
||||
value={deleteAccountPw}
|
||||
onChange={(e) => { setDeleteAccountPw(e.target.value); setDeleteAccountError('') }}
|
||||
placeholder="Ihr Passwort"
|
||||
className="w-full rounded-md border border-input bg-background px-3 py-2 text-sm"
|
||||
autoComplete="current-password"
|
||||
/>
|
||||
</div>
|
||||
{deleteAccountError && (
|
||||
<p className="text-sm text-destructive">{deleteAccountError}</p>
|
||||
)}
|
||||
<div className="flex gap-2 justify-end">
|
||||
<Button
|
||||
variant="outline"
|
||||
size="sm"
|
||||
onClick={() => setShowDeleteAccountDialog(false)}
|
||||
disabled={deleteAccountLoading}
|
||||
>
|
||||
Abbrechen
|
||||
</Button>
|
||||
<Button
|
||||
variant="destructive"
|
||||
size="sm"
|
||||
disabled={deleteAccountLoading || !deleteAccountPw}
|
||||
onClick={async () => {
|
||||
setDeleteAccountLoading(true)
|
||||
setDeleteAccountError('')
|
||||
try {
|
||||
const res = await fetch('/api/auth/delete-account', {
|
||||
method: 'POST',
|
||||
headers: { 'Content-Type': 'application/json' },
|
||||
body: JSON.stringify({ password: deleteAccountPw }),
|
||||
})
|
||||
const data = await res.json()
|
||||
if (res.ok) {
|
||||
window.location.href = '/'
|
||||
} else {
|
||||
setDeleteAccountError(data.error || 'Löschung fehlgeschlagen')
|
||||
}
|
||||
} catch {
|
||||
setDeleteAccountError('Verbindungsfehler')
|
||||
} finally {
|
||||
setDeleteAccountLoading(false)
|
||||
}
|
||||
}}
|
||||
>
|
||||
{deleteAccountLoading ? 'Wird gelöscht...' : 'Konto endgültig löschen'}
|
||||
</Button>
|
||||
</div>
|
||||
</div>
|
||||
</DialogContent>
|
||||
</Dialog>
|
||||
</header>
|
||||
)
|
||||
}
|
||||
|
||||
@@ -1377,12 +1377,12 @@ export function MapView({
|
||||
const lineCoords = f.geometry.coordinates as number[][]
|
||||
if (lineCoords.length < 2) return
|
||||
|
||||
// Get last two points to calculate arrow direction
|
||||
// Get last two points to calculate arrow direction using screen-projected coords
|
||||
const p1 = lineCoords[lineCoords.length - 2]
|
||||
const p2 = lineCoords[lineCoords.length - 1]
|
||||
const angle = Math.atan2(p2[1] - p1[1], p2[0] - p1[0]) * (180 / Math.PI)
|
||||
// MapLibre uses screen coords where Y is inverted, so negate the angle
|
||||
const screenAngle = -angle + 90
|
||||
const px1 = map.current.project(p1 as [number, number])
|
||||
const px2 = map.current.project(p2 as [number, number])
|
||||
const screenAngle = Math.atan2(px2.y - px1.y, px2.x - px1.x) * (180 / Math.PI) + 90
|
||||
|
||||
const color = (f.properties.color as string) || '#000000'
|
||||
const arrowEl = document.createElement('div')
|
||||
|
||||
@@ -9,6 +9,7 @@ export interface User {
|
||||
role: 'SERVER_ADMIN' | 'TENANT_ADMIN' | 'OPERATOR' | 'VIEWER'
|
||||
tenantId?: string
|
||||
tenantSlug?: string
|
||||
emailVerified?: boolean
|
||||
}
|
||||
|
||||
export interface TenantInfo {
|
||||
|
||||
@@ -18,6 +18,7 @@ export interface UserPayload {
|
||||
role: 'SERVER_ADMIN' | 'TENANT_ADMIN' | 'OPERATOR' | 'VIEWER'
|
||||
tenantId?: string
|
||||
tenantSlug?: string
|
||||
emailVerified?: boolean
|
||||
}
|
||||
|
||||
export async function createToken(user: UserPayload): Promise<string> {
|
||||
@@ -63,18 +64,16 @@ export async function login(
|
||||
}) as any)
|
||||
|
||||
if (!user) {
|
||||
return { success: false, error: 'Benutzer nicht gefunden' }
|
||||
return { success: false, error: 'E-Mail oder Passwort falsch' }
|
||||
}
|
||||
|
||||
const isValidPassword = await bcrypt.compare(password, user.password)
|
||||
if (!isValidPassword) {
|
||||
return { success: false, error: 'Ungültiges Passwort' }
|
||||
return { success: false, error: 'E-Mail oder Passwort falsch' }
|
||||
}
|
||||
|
||||
// Check email verification (skip for SERVER_ADMIN and users created before verification was added)
|
||||
if ((user as any).emailVerified === false && (user.role as string) !== 'SERVER_ADMIN') {
|
||||
return { success: false, error: 'Bitte bestätigen Sie zuerst Ihre E-Mail-Adresse. Prüfen Sie Ihren Posteingang.' }
|
||||
}
|
||||
// Track email verification status (allow login regardless)
|
||||
const emailVerified = (user as any).emailVerified !== false
|
||||
|
||||
// Get first tenant membership for non-server-admins
|
||||
let tenantId: string | undefined
|
||||
@@ -102,6 +101,7 @@ export async function login(
|
||||
role: (user.role === 'ADMIN' ? 'SERVER_ADMIN' : user.role) as UserPayload['role'],
|
||||
tenantId,
|
||||
tenantSlug,
|
||||
emailVerified,
|
||||
}
|
||||
|
||||
return { success: true, user: userPayload }
|
||||
|
||||
@@ -4,7 +4,7 @@ import { Document, Page, Text, View, StyleSheet, Font, Image } from '@react-pdf/
|
||||
// Register default font (Helvetica is built-in)
|
||||
const styles = StyleSheet.create({
|
||||
page: {
|
||||
padding: '12mm 15mm 15mm',
|
||||
padding: '12mm 15mm 32mm',
|
||||
fontFamily: 'Helvetica',
|
||||
fontSize: 10,
|
||||
lineHeight: 1.4,
|
||||
|
||||
107
src/lib/rate-limit.ts
Normal file
107
src/lib/rate-limit.ts
Normal file
@@ -0,0 +1,107 @@
|
||||
// In-memory rate limiter for API endpoints
|
||||
// Tracks request counts per IP within sliding windows
|
||||
|
||||
interface RateLimitEntry {
|
||||
count: number
|
||||
resetAt: number
|
||||
}
|
||||
|
||||
const stores = new Map<string, Map<string, RateLimitEntry>>()
|
||||
|
||||
interface RateLimitConfig {
|
||||
/** Unique identifier for this limiter (e.g. 'login', 'register') */
|
||||
id: string
|
||||
/** Maximum requests allowed within the window */
|
||||
max: number
|
||||
/** Window duration in seconds */
|
||||
windowSeconds: number
|
||||
}
|
||||
|
||||
interface RateLimitResult {
|
||||
success: boolean
|
||||
remaining: number
|
||||
resetAt: number
|
||||
}
|
||||
|
||||
function getStore(id: string): Map<string, RateLimitEntry> {
|
||||
if (!stores.has(id)) {
|
||||
stores.set(id, new Map())
|
||||
}
|
||||
return stores.get(id)!
|
||||
}
|
||||
|
||||
// Periodic cleanup of expired entries (every 5 minutes)
|
||||
setInterval(() => {
|
||||
const now = Date.now()
|
||||
for (const [, store] of stores) {
|
||||
for (const [key, entry] of store) {
|
||||
if (now > entry.resetAt) {
|
||||
store.delete(key)
|
||||
}
|
||||
}
|
||||
}
|
||||
}, 5 * 60 * 1000)
|
||||
|
||||
export function rateLimit(config: RateLimitConfig) {
|
||||
const store = getStore(config.id)
|
||||
|
||||
return {
|
||||
check(ip: string): RateLimitResult {
|
||||
const now = Date.now()
|
||||
const key = ip
|
||||
const entry = store.get(key)
|
||||
|
||||
// No entry or expired → fresh window
|
||||
if (!entry || now > entry.resetAt) {
|
||||
store.set(key, {
|
||||
count: 1,
|
||||
resetAt: now + config.windowSeconds * 1000,
|
||||
})
|
||||
return { success: true, remaining: config.max - 1, resetAt: now + config.windowSeconds * 1000 }
|
||||
}
|
||||
|
||||
// Within window
|
||||
entry.count++
|
||||
if (entry.count > config.max) {
|
||||
return { success: false, remaining: 0, resetAt: entry.resetAt }
|
||||
}
|
||||
|
||||
return { success: true, remaining: config.max - entry.count, resetAt: entry.resetAt }
|
||||
},
|
||||
}
|
||||
}
|
||||
|
||||
// Pre-configured limiters for different endpoints
|
||||
export const loginLimiter = rateLimit({ id: 'login', max: 5, windowSeconds: 60 * 15 }) // 5 attempts per 15 min
|
||||
export const registerLimiter = rateLimit({ id: 'register', max: 3, windowSeconds: 60 * 60 }) // 3 per hour
|
||||
export const forgotPasswordLimiter = rateLimit({ id: 'forgot-pw', max: 3, windowSeconds: 60 * 15 }) // 3 per 15 min
|
||||
export const resendVerificationLimiter = rateLimit({ id: 'resend-verify', max: 3, windowSeconds: 60 * 15 })
|
||||
export const contactLimiter = rateLimit({ id: 'contact', max: 5, windowSeconds: 60 * 60 }) // 5 per hour
|
||||
export const deleteAccountLimiter = rateLimit({ id: 'delete-acct', max: 3, windowSeconds: 60 * 15 })
|
||||
export const resetPasswordLimiter = rateLimit({ id: 'reset-pw', max: 5, windowSeconds: 60 * 15 })
|
||||
|
||||
/** Extract client IP from request headers */
|
||||
export function getClientIp(req: Request): string {
|
||||
const forwarded = req.headers.get('x-forwarded-for')
|
||||
if (forwarded) {
|
||||
return forwarded.split(',')[0].trim()
|
||||
}
|
||||
const realIp = req.headers.get('x-real-ip')
|
||||
if (realIp) return realIp
|
||||
return '127.0.0.1'
|
||||
}
|
||||
|
||||
/** Helper: create a 429 response with retry-after header */
|
||||
export function rateLimitResponse(resetAt: number) {
|
||||
const retryAfter = Math.ceil((resetAt - Date.now()) / 1000)
|
||||
return new Response(
|
||||
JSON.stringify({ error: 'Zu viele Anfragen. Bitte versuchen Sie es später erneut.' }),
|
||||
{
|
||||
status: 429,
|
||||
headers: {
|
||||
'Content-Type': 'application/json',
|
||||
'Retry-After': String(retryAfter),
|
||||
},
|
||||
}
|
||||
)
|
||||
}
|
||||
114
src/middleware.ts
Normal file
114
src/middleware.ts
Normal file
@@ -0,0 +1,114 @@
|
||||
import { NextRequest, NextResponse } from 'next/server'
|
||||
import { jwtVerify } from 'jose'
|
||||
|
||||
const JWT_SECRET = new TextEncoder().encode(
|
||||
process.env.NEXTAUTH_SECRET || 'dev-only-fallback-do-not-use-in-production'
|
||||
)
|
||||
|
||||
// Routes that require authentication
|
||||
const PROTECTED_ROUTES = ['/app', '/settings', '/admin']
|
||||
|
||||
// Routes that should redirect to /app if already logged in
|
||||
const AUTH_ROUTES = ['/login', '/register']
|
||||
|
||||
// API routes that are public (no auth needed)
|
||||
const PUBLIC_API_PREFIXES = [
|
||||
'/api/auth/login',
|
||||
'/api/auth/register',
|
||||
'/api/auth/forgot-password',
|
||||
'/api/auth/reset-password',
|
||||
'/api/auth/verify-email',
|
||||
'/api/auth/resend-verification',
|
||||
'/api/auth/logout',
|
||||
'/api/contact',
|
||||
'/api/demo',
|
||||
'/api/donate',
|
||||
'/api/rapports/',
|
||||
'/api/tenants/by-slug/',
|
||||
]
|
||||
|
||||
export async function middleware(req: NextRequest) {
|
||||
const { pathname } = req.nextUrl
|
||||
const token = req.cookies.get('auth-token')?.value
|
||||
|
||||
// Verify token if present
|
||||
let user: any = null
|
||||
if (token) {
|
||||
try {
|
||||
const { payload } = await jwtVerify(token, JWT_SECRET)
|
||||
user = payload.user
|
||||
} catch {
|
||||
// Invalid/expired token — clear it
|
||||
const response = NextResponse.redirect(new URL('/login', req.url))
|
||||
response.cookies.delete('auth-token')
|
||||
// Only redirect if accessing protected routes
|
||||
if (PROTECTED_ROUTES.some(r => pathname.startsWith(r))) {
|
||||
return response
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// Protected routes: redirect to login if not authenticated
|
||||
if (PROTECTED_ROUTES.some(r => pathname.startsWith(r))) {
|
||||
if (!user) {
|
||||
const loginUrl = new URL('/login', req.url)
|
||||
loginUrl.searchParams.set('redirect', pathname)
|
||||
return NextResponse.redirect(loginUrl)
|
||||
}
|
||||
|
||||
// Admin routes: only SERVER_ADMIN and TENANT_ADMIN
|
||||
if (pathname.startsWith('/admin') && user.role !== 'SERVER_ADMIN' && user.role !== 'TENANT_ADMIN') {
|
||||
return NextResponse.redirect(new URL('/app', req.url))
|
||||
}
|
||||
}
|
||||
|
||||
// Auth routes: redirect to /app if already logged in
|
||||
if (AUTH_ROUTES.some(r => pathname.startsWith(r))) {
|
||||
if (user) {
|
||||
return NextResponse.redirect(new URL('/app', req.url))
|
||||
}
|
||||
}
|
||||
|
||||
// API routes: check auth for non-public endpoints
|
||||
if (pathname.startsWith('/api/') && !PUBLIC_API_PREFIXES.some(p => pathname.startsWith(p))) {
|
||||
if (!user) {
|
||||
// Allow /api/auth/me to return null (used for auth check)
|
||||
if (pathname === '/api/auth/me') {
|
||||
return NextResponse.next()
|
||||
}
|
||||
// Allow /api/icons GET (public for symbol loading)
|
||||
if (pathname === '/api/icons' && req.method === 'GET') {
|
||||
return NextResponse.next()
|
||||
}
|
||||
return NextResponse.json({ error: 'Nicht autorisiert' }, { status: 401 })
|
||||
}
|
||||
}
|
||||
|
||||
// Security: block common attack paths
|
||||
if (
|
||||
pathname.includes('..') ||
|
||||
pathname.includes('.env') ||
|
||||
pathname.includes('wp-admin') ||
|
||||
pathname.includes('wp-login') ||
|
||||
pathname.includes('.php') ||
|
||||
pathname.includes('xmlrpc') ||
|
||||
pathname.match(/\.(sql|bak|config|log|ini)$/i)
|
||||
) {
|
||||
return new NextResponse(null, { status: 404 })
|
||||
}
|
||||
|
||||
return NextResponse.next()
|
||||
}
|
||||
|
||||
export const config = {
|
||||
matcher: [
|
||||
/*
|
||||
* Match all request paths except:
|
||||
* - _next/static (static files)
|
||||
* - _next/image (image optimization)
|
||||
* - favicon.ico, sitemap.xml, robots.txt
|
||||
* - public files (images, sw.js, etc.)
|
||||
*/
|
||||
'/((?!_next/static|_next/image|favicon.ico|sitemap.xml|robots.txt|icons/|sw.js|manifest.json|opengraph-image).*)',
|
||||
],
|
||||
}
|
||||
Reference in New Issue
Block a user