Secure your code as it's written. Use Snyk Code to scan source code in minutes - no build needed - and fix issues immediately.
.use(async (ctx: Koa.Context, next: () => Promise) => {
try {
await next();
// Catch Koa's stadard 404 response and throw our own error
if (ctx.response.status === 404) throw new NotFoundError();
} catch (err) {
if (err instanceof ObjectionValidationError) {
const e = new ValidationError();
e.errors = err.data;
ctx.body = e;
ctx.status = e.status;
} else if (err instanceof jwt.JsonWebTokenError || err instanceof jwt.TokenExpiredError) {
const e = new AuthenticationError(err.message);
ctx.body = e;
ctx.status = e.status;
} else {
ctx.status = err.status || err.statusCode || 500;
ctx.body = err;
}
// tslint:disable-next-line
if (config.DEBUG) console.log(err.stack);
}
})
.use(WebHookMiddleware);
.use(async (ctx, next) => {
try {
await next();
// Catch Koa's stadard 404 response and throw our own error
if (ctx.response.status === 404)
throw new NotFoundError_1.default();
}
catch (err) {
if (err instanceof objection_1.ValidationError) {
const e = new ValidationError_1.default();
e.errors = err.data;
ctx.body = e;
ctx.status = e.status;
}
else if (err instanceof jwt.JsonWebTokenError || err instanceof jwt.TokenExpiredError) {
const e = new AuthenticationError_1.default(err.message);
ctx.body = e;
ctx.status = e.status;
}
else {
ctx.status = err.status || err.statusCode || 500;
ctx.body = err;
}
// tslint:disable-next-line
if (config_1.default.DEBUG)
console.log(err.stack);
}
})
.use(middleware_2.default);
if (token === null) {
return Bluebird.resolve(this.anonymous());
}
let decoded = null;
try {
decoded = jwt.verify(token, this.kuzzle.config.security.jwt.secret);
// probably forged token => throw without providing any information
if (!decoded._id) {
throw new jwt.JsonWebTokenError('Invalid token');
}
}
catch (err) {
if (err instanceof jwt.TokenExpiredError) {
return securityError.reject('expired');
}
if (err instanceof jwt.JsonWebTokenError) {
return securityError.reject('invalid');
}
return securityError.rejectFrom(err, 'verification_error', err.message);
}
return this.loadForUser(decoded._id, token)
.then(userToken => {
if (userToken === null) {
securityError.throw('invalid');
}
'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
}));
};
jwt.verify(token, PEMkey, options, function (err, token) {
if (err) {
if (err instanceof jwt.TokenExpiredError) {
log.warn("Access token expired");
done(null, false, 'The access token expired');
}
else if (err instanceof jwt.JsonWebTokenError) {
log.warn("An error was received validating the token", err.message);
done(null, false, util.format('Invalid token (%s)', err.message));
}
else {
done(err, false);
}
}
else {
log.info(token, 'was token going out of verification');
if (options.passReqToCallback) {
log.info("We did pass Req back to Callback")
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' });
}
app.post('/refresh', (req, res) => {
if (!req.body.token) {
res.status(400);
res.json({
message: 'Missing Authorization token'
}).end();
return;
}
let requestToken = req.body.token;
try {
verifyJWT(requestToken);
} catch (err) {
if (err instanceof jwt.TokenExpiredError) {
res.status(403);
res.json({
message: 'Access token expired'
}).end();
return;
}
if (err instanceof jwt.JsonWebTokenError) {
res.status(403);
res.json({
message: 'Invalid access token'
}).end();
return;
}
}
token = generateJWT();
res.status(200);
const verifyToken = token => {
try {
jwt.verify(token, conf.jwt_secret)
return true
} catch (error) {
if (error instanceof jwt.TokenExpiredError
&& error.message.startsWith('jwt expired')
&& jwt.decode(token).iat + 30 * 24 * 60 * 60 > Date.now() / 1000) {
return true
}
}
return false
}
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;
}
}
jwt.verify(token, PEMkey, this.options, (verifyError, verifiedToken) => {
if (verifyError) {
if (verifyError instanceof jwt.TokenExpiredError) {
log.warn('Access token expired');
done(verifyError);
} else if (verifyError instanceof jwt.JsonWebTokenError) {
log.warn('An error was received validating the token', verifyError.message);
done(verifyError);
} else {
done(verifyError);
}
} else {
log.info(verifiedToken, 'was token going out of verification');
done(verifiedToken);
}
});
};