You can not select more than 25 topics
Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
41 lines
1.0 KiB
41 lines
1.0 KiB
import jwt from "jsonwebtoken";
|
|
import type { H3Event } from "h3";
|
|
|
|
const JWT_SECRET = process.env.JWT_SECRET as string;
|
|
if (!JWT_SECRET) {
|
|
throw new Error("JWT_SECRET is not defined in environment variables");
|
|
}
|
|
const JWT_EXPIRES_IN = "7d";
|
|
|
|
export interface JwtPayload {
|
|
userId: number;
|
|
username: string;
|
|
}
|
|
|
|
export function signToken(payload: JwtPayload): string {
|
|
return jwt.sign(payload, JWT_SECRET, { expiresIn: JWT_EXPIRES_IN });
|
|
}
|
|
|
|
export function verifyToken(token: string): JwtPayload {
|
|
return jwt.verify(token, JWT_SECRET) as JwtPayload;
|
|
}
|
|
|
|
export function getTokenFromEvent(event: H3Event): string | null {
|
|
const header = getHeader(event, "Authorization");
|
|
if (header && header.startsWith("Bearer ")) {
|
|
return header.slice(7);
|
|
}
|
|
const cookie = getCookie(event, "token");
|
|
if (cookie) return cookie;
|
|
return null;
|
|
}
|
|
|
|
export function getUserFromEvent(event: H3Event): JwtPayload | null {
|
|
const token = getTokenFromEvent(event);
|
|
if (!token) return null;
|
|
try {
|
|
return verifyToken(token);
|
|
} catch {
|
|
return null;
|
|
}
|
|
}
|
|
|