48 lines
1.2 KiB
TypeScript
48 lines
1.2 KiB
TypeScript
import { jwtVerify } from "jose";
|
|
|
|
// Secret key for JWT verification (must match the one used for signing)
|
|
const JWT_SECRET = new TextEncoder().encode(process.env.JWT_SECRET);
|
|
|
|
export interface JWTPayload {
|
|
email: string;
|
|
role: string;
|
|
iat: number;
|
|
exp: number;
|
|
}
|
|
|
|
/**
|
|
* Validates a JWT token and returns the payload if valid
|
|
*/
|
|
export async function validateToken(token: string): Promise<JWTPayload | null> {
|
|
try {
|
|
const { payload } = await jwtVerify(token, JWT_SECRET);
|
|
return payload as unknown as JWTPayload;
|
|
} catch (error) {
|
|
console.error("Token validation error:", error);
|
|
return null;
|
|
}
|
|
}
|
|
|
|
/**
|
|
* Checks if a token is expired
|
|
*/
|
|
export function isTokenExpired(payload: JWTPayload): boolean {
|
|
const currentTime = Math.floor(Date.now() / 1000);
|
|
return payload.exp < currentTime;
|
|
}
|
|
|
|
/**
|
|
* Gets token expiration time in a human-readable format
|
|
*/
|
|
export function getTokenExpirationTime(payload: JWTPayload): Date {
|
|
return new Date(payload.exp * 1000);
|
|
}
|
|
|
|
/**
|
|
* Gets time until token expires in seconds
|
|
*/
|
|
export function getTimeUntilExpiration(payload: JWTPayload): number {
|
|
const currentTime = Math.floor(Date.now() / 1000);
|
|
return Math.max(0, payload.exp - currentTime);
|
|
}
|