32 lines
1.3 KiB
TypeScript
32 lines
1.3 KiB
TypeScript
// app/lib/auth-cookies.ts
|
|
import { NextResponse } from "next/server";
|
|
|
|
export const ACCESS_COOKIE = "ma_at";
|
|
export const REFRESH_COOKIE = "ma_rt";
|
|
export const USER_COOKIE = "ma_user"; // tiny JSON: {id, username, email?}
|
|
|
|
export function setAuthCookies(
|
|
res: NextResponse,
|
|
tokens: { access_token: string; refresh_token: string; expires?: number },
|
|
user: { id: string; username: string; email?: string | null },
|
|
) {
|
|
const maxAge = tokens.expires ? Math.max(0, Math.floor((tokens.expires - Date.now()) / 1000)) : 60 * 60; // default 1h
|
|
res.cookies.set(ACCESS_COOKIE, tokens.access_token, {
|
|
httpOnly: true, sameSite: "lax", secure: true, path: "/", maxAge,
|
|
});
|
|
// keep refresh longer (7d)
|
|
res.cookies.set(REFRESH_COOKIE, tokens.refresh_token, {
|
|
httpOnly: true, sameSite: "lax", secure: true, path: "/", maxAge: 60 * 60 * 24 * 7,
|
|
});
|
|
res.cookies.set(USER_COOKIE, JSON.stringify(user), {
|
|
httpOnly: false, sameSite: "lax", secure: true, path: "/", maxAge,
|
|
});
|
|
return res;
|
|
}
|
|
|
|
export function clearAuthCookies(res: NextResponse) {
|
|
res.cookies.set(ACCESS_COOKIE, "", { path: "/", maxAge: 0 });
|
|
res.cookies.set(REFRESH_COOKIE, "", { path: "/", maxAge: 0 });
|
|
res.cookies.set(USER_COOKIE, "", { path: "/", maxAge: 0 });
|
|
return res;
|
|
}
|