2025-09-26 11:46:01 -04:00
|
|
|
|
// app/lib/auth-cookies.ts
|
|
|
|
|
|
import { NextResponse } from "next/server";
|
|
|
|
|
|
|
2025-09-26 12:02:27 -04:00
|
|
|
|
export type TokenBundle = {
|
|
|
|
|
|
access_token: string;
|
|
|
|
|
|
refresh_token?: string;
|
|
|
|
|
|
/** Directus returns seconds-until-expiration */
|
|
|
|
|
|
expires?: number;
|
|
|
|
|
|
};
|
2025-09-26 11:46:01 -04:00
|
|
|
|
|
2025-09-26 12:02:27 -04:00
|
|
|
|
export type PublicUser = {
|
|
|
|
|
|
id: string;
|
|
|
|
|
|
email: string;
|
|
|
|
|
|
username: string;
|
|
|
|
|
|
};
|
|
|
|
|
|
|
2025-09-26 12:06:59 -04:00
|
|
|
|
export const ACCESS_COOKIE = "ma_access";
|
|
|
|
|
|
export const REFRESH_COOKIE = "ma_refresh";
|
|
|
|
|
|
|
2025-09-26 12:02:27 -04:00
|
|
|
|
/**
|
|
|
|
|
|
* Mutates `res` in-place to set auth cookies.
|
|
|
|
|
|
* Keeps tokens HttpOnly; sets SameSite=Lax; Secure for HTTPS.
|
|
|
|
|
|
*/
|
2025-09-26 11:46:01 -04:00
|
|
|
|
export function setAuthCookies(
|
|
|
|
|
|
res: NextResponse,
|
2025-09-26 12:02:27 -04:00
|
|
|
|
tokens: TokenBundle,
|
|
|
|
|
|
_user?: PublicUser
|
|
|
|
|
|
): void {
|
2025-09-26 12:06:59 -04:00
|
|
|
|
const maxAge =
|
|
|
|
|
|
typeof tokens.expires === "number" ? tokens.expires : 60 * 60 * 12; // 12h default
|
2025-09-26 12:02:27 -04:00
|
|
|
|
|
|
|
|
|
|
if (tokens.access_token) {
|
2025-09-26 12:06:59 -04:00
|
|
|
|
res.cookies.set(ACCESS_COOKIE, tokens.access_token, {
|
2025-09-26 12:02:27 -04:00
|
|
|
|
httpOnly: true,
|
|
|
|
|
|
sameSite: "lax",
|
|
|
|
|
|
secure: true,
|
|
|
|
|
|
path: "/",
|
|
|
|
|
|
maxAge,
|
|
|
|
|
|
});
|
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
|
|
if (tokens.refresh_token) {
|
2025-09-26 12:06:59 -04:00
|
|
|
|
// If Directus doesn’t give a separate TTL, just make it longer than access (fallback 30d)
|
2025-09-26 12:02:27 -04:00
|
|
|
|
const refreshMaxAge =
|
|
|
|
|
|
typeof tokens.expires === "number" ? tokens.expires * 4 : 60 * 60 * 24 * 30;
|
2025-09-26 11:46:01 -04:00
|
|
|
|
|
2025-09-26 12:06:59 -04:00
|
|
|
|
res.cookies.set(REFRESH_COOKIE, tokens.refresh_token, {
|
2025-09-26 12:02:27 -04:00
|
|
|
|
httpOnly: true,
|
|
|
|
|
|
sameSite: "lax",
|
|
|
|
|
|
secure: true,
|
|
|
|
|
|
path: "/",
|
|
|
|
|
|
maxAge: refreshMaxAge,
|
|
|
|
|
|
});
|
|
|
|
|
|
}
|
2025-09-26 11:46:01 -04:00
|
|
|
|
}
|
2025-09-26 12:06:59 -04:00
|
|
|
|
|
|
|
|
|
|
/** Mutates `res` in-place to clear both auth cookies. */
|
|
|
|
|
|
export function clearAuthCookies(res: NextResponse): void {
|
|
|
|
|
|
const opts = {
|
|
|
|
|
|
httpOnly: true,
|
|
|
|
|
|
sameSite: "lax" as const,
|
|
|
|
|
|
secure: true,
|
|
|
|
|
|
path: "/",
|
|
|
|
|
|
maxAge: 0, // expire immediately
|
|
|
|
|
|
};
|
|
|
|
|
|
res.cookies.set(ACCESS_COOKIE, "", opts);
|
|
|
|
|
|
res.cookies.set(REFRESH_COOKIE, "", opts);
|
|
|
|
|
|
}
|