Secure your code as it's written. Use Snyk Code to scan source code in minutes - no build needed - and fix issues immediately.
delete ctx.state.appToken;
delete ctx.state.tokenType;
delete ctx.state.tokenScopes;
// get token sent by user
const token = retrieveToken(ctx);
// try to authenticate with token
const user = /[0-9a-f]{32,}/i.test(token.value) ?
await authenticateWithAppToken(ctx, token) : // app token?
await authenticateWithJwt(ctx, token); // otherwise, assume it's a JWT.
// log to sqreen
/* istanbul ignore if */
if (process.env.SQREEN_ENABLED) {
require('sqreen').identify(ctx.req, { email: user.email });
}
// update state
ctx.state.user = user;
ctx.response.set('X-User-Id', user.id);
} catch (err) {
if (err.isApiError) {
// update state with error if it's API-related
ctx.state.authError = err;
} else {
// otherwise, re-throw (this is unexpected)
/* istanbul ignore next */
throw err;
// check plan config if provided
if (_.isObject(planAttrs)) {
for (let key in planAttrs) {
if (planAttrs.hasOwnProperty(key)) {
let val = planAttrs[key];
if (user.planConfig[key] !== val) {
throw error('User <%s> with plan "%s" tried to access `%s` but was denied access due to missing plan configuration (%s is %s instead of %s).',
user.email, user._plan, req.url, key, val, user.planConfig[key]).display('Access denied').status(403).log();
}
}
}
}
// *** here we're still authenticated (token is valid and not expired). ***
if (config.vpdb.services.sqreen.enabled) {
require('sqreen').identify(req, { email: user.email });
}
// this will be useful for the rest of the stack
req.user = user;
// set dirty header if necessary
return redis.getAsync('dirty_user_' + user.id).then(result => {
if (result) {
logger.info('[ctrl|auth] User <%s> is dirty, telling him in header.', user.email);
res.setHeader('X-User-Dirty', result);
return redis.delAsync('dirty_user_' + user.id);
}
res.setHeader('X-User-Dirty', 0);
});
}).then(() => {