2017-11-27 16:47:16 +01:00
|
|
|
module.exports = async (ctx, next) => {
|
2018-01-17 18:50:12 +01:00
|
|
|
let role;
|
2017-11-27 16:47:16 +01:00
|
|
|
|
|
|
|
if (ctx.request && ctx.request.header && ctx.request.header.authorization) {
|
|
|
|
try {
|
2018-01-17 18:50:12 +01:00
|
|
|
const token = await strapi.plugins['users-permissions'].services.jwt.getToken(ctx);
|
2017-12-14 16:12:39 +01:00
|
|
|
|
2018-01-17 19:22:35 +01:00
|
|
|
ctx.state.user = await strapi.query('user', 'users-permissions').findOne({ _id, id } = token, ['role'])
|
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-17 18:50:12 +01:00
|
|
|
return ctx.unauthorized(`User Not Found.`);
|
2018-01-09 13:53:52 +01:00
|
|
|
}
|
|
|
|
|
|
|
|
role = ctx.state.user.role;
|
|
|
|
|
2018-01-17 18:50:12 +01:00
|
|
|
if (role.type === 'root') {
|
2018-01-09 13:53:52 +01:00
|
|
|
return await next();
|
|
|
|
}
|
2017-11-27 16:47:16 +01:00
|
|
|
}
|
|
|
|
|
2018-01-17 18:50:12 +01:00
|
|
|
// Retrieve `guest` role.
|
|
|
|
if (!role) {
|
|
|
|
role = await strapi.query('role', 'users-permissions').findOne({ type: 'guest' }, []);
|
|
|
|
}
|
|
|
|
|
|
|
|
const route = ctx.request.route;
|
|
|
|
const permission = await strapi.query('permission', 'users-permissions').findOne({
|
|
|
|
role: role._id || role.id,
|
|
|
|
type: route.plugin || 'application',
|
|
|
|
controller: route.controller,
|
|
|
|
action: route.action,
|
|
|
|
enabled: true
|
|
|
|
}, []);
|
2017-11-27 16:47:16 +01:00
|
|
|
|
2017-11-27 17:45:21 +01:00
|
|
|
if (!permission) {
|
2018-01-17 18:50:12 +01:00
|
|
|
return ctx.unauthorized();
|
2017-11-27 17:45:21 +01:00
|
|
|
}
|
|
|
|
|
2018-01-17 18:50:12 +01:00
|
|
|
// Execute the policies.
|
|
|
|
if (permission.policy) {
|
|
|
|
await strapi.plugins['users-permissions'].config.policies[permission.policy](ctx, next);
|
2017-11-27 16:47:16 +01:00
|
|
|
}
|
2018-01-17 18:50:12 +01:00
|
|
|
|
|
|
|
// Execute the action.
|
|
|
|
await next();
|
2017-11-27 16:47:16 +01:00
|
|
|
};
|