45 lines
1.1 KiB
TypeScript
45 lines
1.1 KiB
TypeScript
import { NextResponse } from 'next/server'
|
|
import * as crypto from 'crypto'
|
|
|
|
const SECRET = process.env.APP_SECRET || 'smart-home-default-secret-change-me'
|
|
const PIN = process.env.APP_PIN || '1234'
|
|
|
|
function makeToken(pin: string): string {
|
|
return crypto.createHmac('sha256', SECRET).update(pin).digest('hex')
|
|
}
|
|
|
|
export async function GET(req: Request) {
|
|
const cookieHeader = req.headers.get('cookie') || ''
|
|
const match = cookieHeader.match(/auth_token=([^;]+)/)
|
|
const token = match ? match[1] : null
|
|
const expected = makeToken(PIN)
|
|
return NextResponse.json({ authenticated: token === expected })
|
|
}
|
|
|
|
export async function POST(req: Request) {
|
|
const { pin } = await req.json()
|
|
|
|
if (pin !== PIN) {
|
|
return NextResponse.json({ error: 'wrong_pin' }, { status: 401 })
|
|
}
|
|
|
|
const token = makeToken(PIN)
|
|
const res = NextResponse.json({ success: true })
|
|
|
|
res.cookies.set('auth_token', token, {
|
|
httpOnly: true,
|
|
secure: true,
|
|
sameSite: 'strict',
|
|
path: '/',
|
|
maxAge: 60 * 60 * 24 * 365,
|
|
})
|
|
|
|
return res
|
|
}
|
|
|
|
export async function DELETE() {
|
|
const res = NextResponse.json({ success: true })
|
|
res.cookies.delete('auth_token')
|
|
return res
|
|
}
|