75 lines
2.3 KiB
TypeScript
75 lines
2.3 KiB
TypeScript
import { NextResponse } from "next/server"
|
|
import { z } from "zod"
|
|
import { createMachineSession } from "@/server/machines-session"
|
|
import { applyCorsHeaders, createCorsPreflight, jsonWithCors } from "@/server/cors"
|
|
|
|
const sessionSchema = z.object({
|
|
machineToken: z.string().min(1),
|
|
rememberMe: z.boolean().optional(),
|
|
})
|
|
|
|
const CORS_METHODS = "POST, OPTIONS"
|
|
|
|
export async function OPTIONS(request: Request) {
|
|
return createCorsPreflight(request.headers.get("origin"), CORS_METHODS)
|
|
}
|
|
|
|
export async function POST(request: Request) {
|
|
if (request.method !== "POST") {
|
|
return jsonWithCors({ error: "Método não permitido" }, 405, request.headers.get("origin"), CORS_METHODS)
|
|
}
|
|
|
|
let payload
|
|
try {
|
|
const raw = await request.json()
|
|
payload = sessionSchema.parse(raw)
|
|
} catch (error) {
|
|
return jsonWithCors(
|
|
{ error: "Payload inválido", details: error instanceof Error ? error.message : String(error) },
|
|
400,
|
|
request.headers.get("origin"),
|
|
CORS_METHODS
|
|
)
|
|
}
|
|
|
|
try {
|
|
const session = await createMachineSession(payload.machineToken, payload.rememberMe ?? true)
|
|
const response = NextResponse.json(
|
|
{
|
|
ok: true,
|
|
machine: session.machine,
|
|
session: session.response,
|
|
},
|
|
{ status: 200 }
|
|
)
|
|
|
|
session.headers.forEach((value, key) => {
|
|
response.headers.set(key, value)
|
|
})
|
|
|
|
const machineCookiePayload = {
|
|
machineId: session.machine.id,
|
|
persona: session.machine.persona,
|
|
assignedUserId: session.machine.assignedUserId,
|
|
assignedUserEmail: session.machine.assignedUserEmail,
|
|
assignedUserName: session.machine.assignedUserName,
|
|
assignedUserRole: session.machine.assignedUserRole,
|
|
}
|
|
response.cookies.set({
|
|
name: "machine_ctx",
|
|
value: Buffer.from(JSON.stringify(machineCookiePayload)).toString("base64url"),
|
|
httpOnly: true,
|
|
sameSite: "lax",
|
|
secure: true,
|
|
path: "/",
|
|
maxAge: 60 * 60 * 24 * 30,
|
|
})
|
|
|
|
applyCorsHeaders(response, request.headers.get("origin"), CORS_METHODS)
|
|
|
|
return response
|
|
} catch (error) {
|
|
console.error("[machines.sessions] Falha ao criar sessão", error)
|
|
return jsonWithCors({ error: "Falha ao autenticar máquina" }, 500, request.headers.get("origin"), CORS_METHODS)
|
|
}
|
|
}
|