2026-02-14 10:30:27 +01:00
|
|
|
/**
|
|
|
|
|
* Auth API — validates album passwords and sets auth cookies.
|
|
|
|
|
* POST /api/auth { slug, password }
|
|
|
|
|
*/
|
|
|
|
|
|
|
|
|
|
import { NextRequest, NextResponse } from 'next/server';
|
|
|
|
|
import { authenticate, isProtected } from '@/lib/auth';
|
2026-02-15 11:23:51 +01:00
|
|
|
import { checkRateLimit } from '@/lib/rate-limit';
|
|
|
|
|
|
|
|
|
|
/** Tight limit for auth attempts — 10 per minute per IP. */
|
|
|
|
|
const AUTH_RPM = 10;
|
2026-02-14 10:30:27 +01:00
|
|
|
|
|
|
|
|
export async function POST(request: NextRequest) {
|
2026-02-15 11:23:51 +01:00
|
|
|
// ── Rate limiting (brute-force protection) ──────────
|
|
|
|
|
const ip = request.headers.get('x-forwarded-for')?.split(',')[0].trim() || 'unknown';
|
|
|
|
|
const { success } = checkRateLimit(`auth:${ip}`, AUTH_RPM);
|
|
|
|
|
|
|
|
|
|
if (!success) {
|
|
|
|
|
return NextResponse.json({ error: 'Too many attempts, try again later' }, { status: 429 });
|
|
|
|
|
}
|
|
|
|
|
|
2026-02-14 11:47:26 +01:00
|
|
|
try {
|
|
|
|
|
const body = await request.json();
|
|
|
|
|
const { slug, password } = body;
|
2026-02-14 10:30:27 +01:00
|
|
|
|
2026-02-14 11:47:26 +01:00
|
|
|
if (!slug || !password) {
|
|
|
|
|
return NextResponse.json({ error: 'Missing slug or password' }, { status: 400 });
|
|
|
|
|
}
|
2026-02-14 10:30:27 +01:00
|
|
|
|
2026-02-14 11:47:26 +01:00
|
|
|
if (!isProtected(slug)) {
|
|
|
|
|
return NextResponse.json({ error: 'Album is not password-protected' }, { status: 400 });
|
|
|
|
|
}
|
2026-02-14 10:30:27 +01:00
|
|
|
|
2026-02-14 11:47:26 +01:00
|
|
|
const setCookie = authenticate(slug, password);
|
|
|
|
|
if (!setCookie) {
|
|
|
|
|
return NextResponse.json({ error: 'Invalid password' }, { status: 401 });
|
2026-02-14 10:30:27 +01:00
|
|
|
}
|
2026-02-14 11:47:26 +01:00
|
|
|
|
|
|
|
|
return NextResponse.json({ success: true }, { headers: { 'Set-Cookie': setCookie } });
|
|
|
|
|
} catch {
|
|
|
|
|
return NextResponse.json({ error: 'Invalid request body' }, { status: 400 });
|
|
|
|
|
}
|
2026-02-14 10:30:27 +01:00
|
|
|
}
|