@the-node-forge/jwt-utils
Version:
A flexible, lightweight Node.js JWT library for generating, verifying, and managing JSON Web Tokens (JWTs). Supports access and refresh tokens with customizable secrets for authentication and role-based access control. Includes middleware for Express, Fas
75 lines (74 loc) • 2.63 kB
JavaScript
;
/* eslint-disable @typescript-eslint/no-require-imports, @typescript-eslint/no-unused-vars */
Object.defineProperty(exports, "__esModule", { value: true });
exports.authenticateToken = authenticateToken;
exports.authenticateRefreshToken = authenticateRefreshToken;
let hapi;
let verifyToken;
let verifyRefreshToken;
function authenticateToken(accessSecret) {
if (!hapi) {
try {
hapi = require('@hapi/hapi');
}
catch (error) {
throw new Error("Hapi middleware is being used, but '@hapi/hapi' is not installed. Please install it as a peer dependency.");
}
}
if (!verifyToken) {
({ verifyToken } = require('../jwt'));
}
return async (request, h) => {
const authHeader = request.headers.authorization;
if (!authHeader?.startsWith('Bearer ')) {
return h
.response({ message: 'Unauthorized: No token provided or invalid format' })
.code(401);
}
const [, token] = authHeader.split(' ');
if (!token) {
return h.response({ message: 'Unauthorized: Missing token' }).code(401);
}
const decoded = verifyToken(token, accessSecret);
if (!decoded) {
return h
.response({ message: 'Forbidden: Invalid or expired token' })
.code(403);
}
request.app.user = decoded;
return h.continue;
};
}
function authenticateRefreshToken(refreshSecret) {
if (!hapi) {
try {
hapi = require('@hapi/hapi');
}
catch (error) {
throw new Error("Hapi middleware is being used, but '@hapi/hapi' is not installed. Please install it as a peer dependency.");
}
}
if (!verifyRefreshToken) {
({ verifyRefreshToken } = require('../jwt'));
}
return async (request, h) => {
const authHeader = request.headers.authorization;
if (!authHeader?.startsWith('Bearer ')) {
return h
.response({ message: 'Unauthorized: No token provided or invalid format' })
.code(401);
}
const [, token] = authHeader.split(' ');
if (!token) {
return h.response({ message: 'Unauthorized: Missing token' }).code(401);
}
const decoded = verifyRefreshToken(token, refreshSecret);
if (!decoded) {
return h
.response({ message: 'Forbidden: Invalid or expired refresh token' })
.code(403);
}
request.app.user = decoded;
return h.continue;
};
}