41 lines
1.2 KiB
TypeScript
41 lines
1.2 KiB
TypeScript
import { NextResponse } from 'next/server'
|
|
import type { NextRequest } from 'next/server'
|
|
import * as crypto from 'crypto'
|
|
|
|
export function middleware(request: NextRequest) {
|
|
const { pathname } = request.nextUrl
|
|
|
|
// Allow auth API and static assets
|
|
if (
|
|
pathname.startsWith('/api/auth') ||
|
|
pathname.startsWith('/_next') ||
|
|
pathname.startsWith('/favicon') ||
|
|
pathname === '/manifest.json'
|
|
) {
|
|
return NextResponse.next()
|
|
}
|
|
|
|
const token = request.cookies.get('auth_token')?.value
|
|
const pin = process.env.APP_PIN || '1234'
|
|
const secret = process.env.APP_SECRET || 'smart-home-default-secret-change-me'
|
|
const expectedToken = crypto.createHmac('sha256', secret).update(pin).digest('hex')
|
|
|
|
if (token !== expectedToken) {
|
|
// For API routes, return 401
|
|
if (pathname.startsWith('/api/')) {
|
|
return NextResponse.json({ error: 'unauthorized' }, { status: 401 })
|
|
}
|
|
|
|
// For page requests, rewrite to show login (handled client-side)
|
|
const url = request.nextUrl.clone()
|
|
url.searchParams.set('locked', '1')
|
|
return NextResponse.rewrite(url)
|
|
}
|
|
|
|
return NextResponse.next()
|
|
}
|
|
|
|
export const config = {
|
|
matcher: ['/((?!_next/static|_next/image|favicon.ico|manifest.json).*)'],
|
|
}
|