feat: logout
This commit is contained in:
@@ -0,0 +1,42 @@
|
||||
import { SignJWT, jwtVerify } from "jose";
|
||||
import { cookies } from "next/headers";
|
||||
import { cookieConfig } from "@/lib/cookieConfig";
|
||||
|
||||
const secret = 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(secret);
|
||||
}
|
||||
|
||||
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, secret);
|
||||
return payload.sub ?? null;
|
||||
} catch {
|
||||
return null;
|
||||
}
|
||||
}
|
||||
|
||||
export async function deleteSession() {
|
||||
const store = await cookies();
|
||||
store.delete("session");
|
||||
}
|
||||
Reference in New Issue
Block a user