Files
chadebebe/app/api/lock/route.ts
Michael T 30c661a364 fix(auth): resolve cookie authentication failure over HTTP
Cookies were set with secure flag based solely on NODE_ENV, causing
401 errors when accessing over HTTP with NODE_ENV=production.

- Add COOKIE_SECURE env var for explicit control
- Auto-detect HTTPS via X-Forwarded-Proto header in production
- Extract isSecureCookie() utility to lib/auth/utils.ts
- Document COOKIE_SECURE in README and .env.example

Fixes #39
2026-01-23 15:26:24 -05:00

68 lines
1.7 KiB
TypeScript

import { NextRequest, NextResponse } from 'next/server';
import { eq } from 'drizzle-orm';
import { db, settings } from '@/lib/db';
import crypto from 'crypto';
import { isSecureCookie } from '@/lib/auth/utils';
// POST /api/lock - Verify password
export async function POST(request: NextRequest) {
try {
const body = await request.json();
const { password } = body;
if (!password) {
return NextResponse.json(
{ error: 'Password is required' },
{ status: 400 }
);
}
// Get the stored password hash
const hashSetting = await db
.select()
.from(settings)
.where(eq(settings.key, 'passwordLockHash'))
.limit(1);
if (hashSetting.length === 0) {
return NextResponse.json(
{ error: 'Password lock not configured' },
{ status: 400 }
);
}
// Hash the provided password
const hash = crypto.createHash('sha256').update(password).digest('hex');
// Compare hashes
if (hash === hashSetting[0].value) {
// Password correct - set a cookie
const response = NextResponse.json({
success: true,
message: 'Password verified',
});
response.cookies.set('site_unlocked', 'true', {
httpOnly: true,
secure: isSecureCookie(request),
sameSite: 'lax',
maxAge: 60 * 60 * 24,
path: '/',
});
return response;
} else {
return NextResponse.json(
{ error: 'Incorrect password' },
{ status: 401 }
);
}
} catch (error) {
console.error('Error verifying password:', error);
return NextResponse.json(
{ error: 'Failed to verify password' },
{ status: 500 }
);
}
}