gh_UserManager/apps/web/app/api/auth/logout/route.ts
bermooda-company 54d5891edf user
2026-08-23 23:59:14 +03:30

33 lines
1.2 KiB
TypeScript

import { NextRequest, NextResponse } from "next/server";
import { djangoUrl, clearAuthCookies, setAuthCookies } from "../proxy";
export async function POST(req: NextRequest) {
const cookieRefresh = req.cookies.get("refresh_token")?.value;
const cookieSession = req.cookies.get("session_id")?.value;
const body = await req.text().catch(() => "");
let parsed: any = {};
try {
parsed = body ? JSON.parse(body) : {};
} catch {
parsed = {};
}
const upstream = await fetch(djangoUrl("auth/logout/"), {
method: "POST",
headers: { "Content-Type": "application/json" },
body: JSON.stringify({
refresh: parsed.refresh || cookieRefresh || "",
session_id: parsed.session_id || cookieSession || "",
logout_type: parsed.logout_type || "global",
}),
});
const data = await upstream.json().catch(() => ({}));
const res = NextResponse.json(data, { status: upstream.status });
// Always clear local cookies; the upstream may also rotate the session.
clearAuthCookies(res);
if (upstream.ok && data) {
// Preserve any refreshed tokens returned by the server, if applicable.
setAuthCookies(res, data);
}
return res;
}