Secure your code as it's written. Use Snyk Code to scan source code in minutes - no build needed - and fix issues immediately.
export default async(options: Options): Promise=> {
try {
const tokenExtractor = options.extractTokenFromRequest || extractTokenFromRequest;
const token: any = tokenExtractor({req: options.req});
const secret = options.secretOrKey || config.jwt.secret;
const {data}: any = jwt.verify(token, secret);
const user: any = await options.service.getUserById({id: data.id});
const permissions: any[] = await options.service.getUserPermissions({userId: user.id});
return Promise.resolve({user, permissions});
} catch (err) {
if (err instanceof jwt.JsonWebTokenError) {
throw new InvalidJwtTokenError();
} else if (err instanceof jwt.NotBeforeError) {
new InvalidJwtTokenError();
} else if (err instanceof jwt.TokenExpiredError) {
new ExpiredJwtTokenError();
}
throw err;
}
}
'use strict';
const _ = require('lodash');
const Promise = require('bluebird');
const jwt = require('jsonwebtoken');
const signAsync = Promise.promisify(jwt.sign);
const verifyAsync = Promise.promisify(jwt.verify);
exports.JsonWebTokenError = jwt.JsonWebTokenError;
exports.NotBeforeError = jwt.NotBeforeError;
exports.TokenExpiredError = jwt.TokenExpiredError;
exports.decode = jwt.decode;
exports.sign = function sign(payload, secretOrPrivateKey, options) {
return signAsync(payload, secretOrPrivateKey, _.defaults({}, options));
};
exports.verify = function verify(jwtString, secretOrPublicKey, options) {
return verifyAsync(jwtString, secretOrPublicKey, _.defaults({}, options, {
clockTolerance: 10
}));
};
if (!token) return errorUtil.ERROR({ error: 'Not Found Token' });
let tokenWithoutBearer = token;
if (token.slice(0, 6) === 'Bearer') {
tokenWithoutBearer = token.slice(7);
} else {
return errorUtil.ERROR({ error: 'Header include incorrect Bearer prefix' });
}
let payload;
try {
payload = jwt.verify(tokenWithoutBearer, this.configService.JWT_SECRET_KEY) as IJwtPayload | undefined;
} catch (error) {
if (error instanceof jwt.NotBeforeError) return errorUtil.ERROR({ error: 'Your Token Has Not Before' });
if (error instanceof jwt.TokenExpiredError) return errorUtil.ERROR({ error: 'Your Token Has Expired' });
if (error instanceof jwt.JsonWebTokenError) return errorUtil.ERROR({ error: 'Your Token Has Error' });
}
return payload || errorUtil.ERROR({ error: 'Your Token Verify Faild' });
}