50 lines
1.2 KiB
TypeScript
50 lines
1.2 KiB
TypeScript
"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<SessionPayload | null> {
|
|
try {
|
|
const { payload } = await jwtVerify(token, encodedKey, {
|
|
algorithms: ["HS256"],
|
|
});
|
|
return payload as SessionPayload;
|
|
} catch {
|
|
return null;
|
|
}
|
|
}
|
|
|
|
export async function isLoggedIn(): Promise<boolean> {
|
|
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<void> {
|
|
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: "/",
|
|
});
|
|
}
|