46 lines
1.2 KiB
JavaScript
Raw Normal View History

const _ = require('lodash');
module.exports = async (ctx, next) => {
const route = ctx.request.route;
let role = '1';
if (ctx.request && ctx.request.header && ctx.request.header.authorization) {
try {
2017-12-14 16:12:39 +01:00
const tokenUser = await strapi.plugins['users-permissions'].services.jwt.getToken(ctx);
ctx.state.user = await strapi.plugins['users-permissions'].services.user.fetch(_.pick(tokenUser, ['_id', 'id']));
} catch (err) {
2017-11-27 16:59:53 +01:00
return ctx.unauthorized(err);
}
if (!ctx.state.user) {
2018-01-10 13:39:42 +01:00
return ctx.unauthorized('This user doesn\'t exit.');
}
role = ctx.state.user.role;
if (role.toString() === '0') {
return await next();
}
}
2017-12-08 12:03:37 +01:00
const permission = _.get(strapi.plugins['users-permissions'].config, ['roles', role.toString(), 'permissions', route.plugin || 'application', 'controllers', route.controller, route.action]);
if (!permission) {
return await next();
}
if (permission.enabled && permission.policy) {
try {
2017-12-07 18:16:15 +01:00
await strapi.plugins['users-permissions'].config.policies[permission.policy](ctx, next);
} catch (err) {
ctx.unauthorized(err);
}
} else if (permission.enabled) {
await next();
} else {
ctx.unauthorized('Access restricted for this action.');
}
};