finish implementing draft features in blog
This commit is contained in:
49
src/components/auth.ts
Normal file
49
src/components/auth.ts
Normal 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: "/",
|
||||
});
|
||||
}
|
Reference in New Issue
Block a user