"use server"; import { jwtVerify, SignJWT } from "jose"; import { cookies } from "next/headers"; const SECRET_KEY = process.env.SESSION_SECRET; const encodedKey = new TextEncoder().encode(SECRET_KEY); export type SessionPayload = { admin: true }; export async function encrypt(payload: SessionPayload) { return new SignJWT(payload) .setProtectedHeader({ alg: "HS256" }) .setIssuedAt() .setExpirationTime("7d") .sign(encodedKey); } export async function decrypt( token: string | undefined = "" ): Promise { try { const { payload } = await jwtVerify(token, encodedKey, { algorithms: ["HS256"], }); return payload as SessionPayload; } catch { return null; } } export async function isLoggedIn(): Promise { const cookieStore = (await cookies()).get("session")?.value; const session = await decrypt(cookieStore); if (session != null && session.admin) { return true; } return false; } export async function setSession(): Promise { const expiresAt = new Date(Date.now() + 7 * 24 * 60 * 60 * 1000); (await cookies()).set("session", await encrypt({ admin: true }), { httpOnly: true, secure: true, expires: expiresAt, sameSite: "lax", path: "/", }); }