Initial commit
This commit is contained in:
38
lib/auth/jwt.ts
Normal file
38
lib/auth/jwt.ts
Normal file
@@ -0,0 +1,38 @@
|
||||
import { SignJWT, jwtVerify } from "jose";
|
||||
import { loadSystemConfig } from "../system-config";
|
||||
|
||||
export type SessionToken = {
|
||||
sub: string; // userId
|
||||
role: "ADMIN" | "USER";
|
||||
email: string;
|
||||
forcePasswordReset: boolean;
|
||||
};
|
||||
|
||||
async function getSecret() {
|
||||
const cfg = await loadSystemConfig();
|
||||
const s = cfg.auth?.jwtSecret || process.env.JWT_SECRET;
|
||||
if (!s) return null;
|
||||
return new TextEncoder().encode(s);
|
||||
}
|
||||
|
||||
export async function signSession(payload: SessionToken) {
|
||||
const secret = await getSecret();
|
||||
if (!secret) throw new Error("JWT secret not configured");
|
||||
const token = await new SignJWT(payload)
|
||||
.setProtectedHeader({ alg: "HS256" })
|
||||
.setIssuedAt()
|
||||
.setExpirationTime("7d")
|
||||
.sign(secret);
|
||||
return token;
|
||||
}
|
||||
|
||||
export async function verifySession(token: string) {
|
||||
const secret = await getSecret();
|
||||
if (!secret) return null;
|
||||
try {
|
||||
const { payload } = await jwtVerify(token, secret);
|
||||
return payload as any as SessionToken;
|
||||
} catch {
|
||||
return null;
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user