nest-phylax
Version:
Security library for NestJS
42 lines • 1.83 kB
JavaScript
;
Object.defineProperty(exports, "__esModule", { value: true });
exports.JwtUtil = void 0;
const jsonwebtoken_1 = require("jsonwebtoken");
const common_1 = require("@nestjs/common");
const jwt_auth_constants_1 = require("./jwt.auth.constants");
class JwtUtil {
generateToken({ user, claims, secretKey, signOptions, }) {
const secretKeyExists = !!secretKey;
if (!secretKeyExists) {
throw new Error('JWT_SECRET_KEY is not set');
}
return (0, jsonwebtoken_1.sign)({
sub: user.id,
role: claims === null || claims === void 0 ? void 0 : claims.role,
}, secretKey || process.env.JWT_SECRET_KEY, Object.assign(Object.assign({}, signOptions), { expiresIn: (signOptions === null || signOptions === void 0 ? void 0 : signOptions.expiresIn) || '1h' }));
}
verifyJwt(token, secretKey) {
try {
const decoded = (0, jsonwebtoken_1.verify)(token, secretKey);
return decoded;
}
catch (error) {
switch (error.name) {
case 'JsonWebTokenError':
throw new common_1.UnauthorizedException({
message: jwt_auth_constants_1.INVALID_TOKEN_SIGNATURE_ERROR_MESSAGE,
});
case 'TokenExpiredError':
throw new common_1.UnauthorizedException({
message: jwt_auth_constants_1.TOKEN_EXPIRED_ERROR_MESSAGE,
});
default:
throw new common_1.UnauthorizedException({
message: jwt_auth_constants_1.FAILED_TO_DECODE_TOKEN_ERROR_MESSAGE,
});
}
}
}
}
exports.JwtUtil = JwtUtil;
//# sourceMappingURL=jwt.util.js.map