finish implementing draft features in blog

This commit is contained in:
2025-04-02 01:30:34 +02:00
parent ac420f1419
commit 59422c5f67
11 changed files with 179 additions and 36 deletions

49
src/components/auth.ts Normal file
View File

@ -0,0 +1,49 @@
"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: "/",
});
}