44 lines
1.1 KiB
TypeScript
44 lines
1.1 KiB
TypeScript
import { SignJWT, jwtVerify } from "jose";
|
|
import { cookies } from "next/headers";
|
|
import { cookieConfig } from "@/lib/cookieConfig";
|
|
|
|
function getSecret() {
|
|
return new TextEncoder().encode(process.env.JWT_SECRET!);
|
|
}
|
|
|
|
async function signJwt(userId: string) {
|
|
return await new SignJWT({})
|
|
.setProtectedHeader({ alg: "HS256" })
|
|
.setSubject(userId)
|
|
.setIssuedAt()
|
|
.setExpirationTime(`${process.env.SESSION_MAX_AGE}s`)
|
|
.sign(getSecret());
|
|
}
|
|
|
|
export async function createSession(userId: string) {
|
|
const token = await signJwt(userId);
|
|
const store = await cookies();
|
|
store.set("session", token, {
|
|
...cookieConfig,
|
|
path: "/",
|
|
maxAge: parseInt(process.env.SESSION_MAX_AGE!),
|
|
});
|
|
}
|
|
|
|
export async function getSessionUserId(): Promise<string | null> {
|
|
const store = await cookies();
|
|
const token = store.get("session")?.value;
|
|
if (!token) return null;
|
|
|
|
try {
|
|
const { payload } = await jwtVerify(token, getSecret());
|
|
return payload.sub ?? null;
|
|
} catch {
|
|
return null;
|
|
}
|
|
}
|
|
|
|
export async function deleteSession() {
|
|
const store = await cookies();
|
|
store.delete("session");
|
|
} |