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-18 11:13:44 +01:00
|
|
|
const { _id, id } = await strapi.plugins['users-permissions'].services.jwt.getToken(ctx);
|
2018-02-28 18:10:30 +01:00
|
|
|
|
|
|
|
if ((id || _id) === undefined) {
|
|
|
|
throw new Error('Invalid token: Token did not contain required fields');
|
|
|
|
}
|
2017-12-14 16:12:39 +01:00
|
|
|
|
2018-02-28 10:35:28 -05:00
|
|
|
ctx.state.user = await strapi.query('user', 'users-permissions').findOne({ _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-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-03-12 16:37:20 +01:00
|
|
|
// Retrieve `public` role.
|
2018-01-17 18:50:12 +01:00
|
|
|
if (!role) {
|
2018-03-12 16:37:20 +01:00
|
|
|
role = await strapi.query('role', 'users-permissions').findOne({ type: 'public' }, []);
|
2018-01-17 18:50:12 +01:00
|
|
|
}
|
2018-01-24 11:52:09 +01:00
|
|
|
|
2018-01-17 18:50:12 +01:00
|
|
|
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-05-24 17:20:32 +02:00
|
|
|
if (ctx.request.graphql === null) {
|
|
|
|
return ctx.request.graphql = strapi.errors.forbidden();
|
|
|
|
}
|
2018-04-10 11:47:01 +02:00
|
|
|
|
2018-05-24 17:20:32 +02:00
|
|
|
ctx.forbidden();
|
2017-11-27 17:45:21 +01:00
|
|
|
}
|
|
|
|
|
2018-01-17 18:50:12 +01:00
|
|
|
// Execute the policies.
|
|
|
|
if (permission.policy) {
|
2018-01-24 19:00:12 +01:00
|
|
|
return 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
|
|
|
};
|