2017-11-27 16:47:16 +01:00
|
|
|
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']));
|
|
|
|
|
2017-11-27 16:47:16 +01:00
|
|
|
} catch (err) {
|
2017-11-27 16:59:53 +01:00
|
|
|
return ctx.unauthorized(err);
|
2017-11-27 16:47:16 +01:00
|
|
|
}
|
2018-01-09 13:53:52 +01:00
|
|
|
|
|
|
|
if (!ctx.state.user) {
|
2018-01-10 13:39:42 +01:00
|
|
|
return ctx.unauthorized('This user doesn\'t exit.');
|
2018-01-09 13:53:52 +01:00
|
|
|
}
|
|
|
|
|
|
|
|
role = ctx.state.user.role;
|
|
|
|
|
|
|
|
if (role.toString() === '0') {
|
|
|
|
return await next();
|
|
|
|
}
|
2017-11-27 16:47:16 +01:00
|
|
|
}
|
|
|
|
|
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]);
|
2017-11-27 16:47:16 +01:00
|
|
|
|
2017-11-27 17:45:21 +01:00
|
|
|
if (!permission) {
|
|
|
|
return await next();
|
|
|
|
}
|
|
|
|
|
2017-11-27 16:47:16 +01:00
|
|
|
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);
|
2017-11-27 16:47:16 +01:00
|
|
|
} catch (err) {
|
|
|
|
ctx.unauthorized(err);
|
|
|
|
}
|
|
|
|
} else if (permission.enabled) {
|
|
|
|
await next();
|
|
|
|
} else {
|
|
|
|
ctx.unauthorized('Access restricted for this action.');
|
|
|
|
}
|
|
|
|
};
|