121 lines
2.7 KiB
JavaScript
Raw Normal View History

2018-08-08 17:57:02 +02:00
const _ = require('lodash');
module.exports = async (ctx, next) => {
let role;
if (ctx.request && ctx.request.header && ctx.request.header.authorization) {
try {
const { id, isAdmin = false } = await strapi.plugins[
'users-permissions'
].services.jwt.getToken(ctx);
if (id === undefined) {
throw new Error('Invalid token: Token did not contain required fields');
}
2017-12-14 16:12:39 +01:00
if (isAdmin) {
ctx.state.admin = await strapi
.query('administrator', 'admin')
.findOne({ id });
} else {
ctx.state.user = await strapi
.query('user', 'users-permissions')
.findOne({ id });
}
} catch (err) {
return handleErrors(ctx, err, 'unauthorized');
}
if (ctx.state.admin) {
if (ctx.state.admin.blocked === true) {
return handleErrors(
ctx,
'Your account has been blocked by the administrator.',
2019-04-25 12:34:55 +02:00
'unauthorized'
);
}
ctx.state.user = ctx.state.admin;
return await next();
}
if (!ctx.state.user) {
return handleErrors(ctx, 'User Not Found', 'unauthorized');
}
role = ctx.state.user.role;
if (role.type === 'root') {
return await next();
}
2018-08-08 17:57:02 +02:00
const store = await strapi.store({
environment: '',
type: 'plugin',
name: 'users-permissions',
2018-08-08 17:57:02 +02:00
});
if (
_.get(await store.get({ key: 'advanced' }), 'email_confirmation') &&
!ctx.state.user.confirmed
) {
return handleErrors(
ctx,
'Your account email is not confirmed.',
2019-04-25 12:34:55 +02:00
'unauthorized'
);
2018-08-08 17:57:02 +02:00
}
2018-10-31 17:20:09 +01:00
2019-02-28 19:22:01 +02:00
if (ctx.state.user.blocked) {
return handleErrors(
ctx,
'Your account has been blocked by the administrator.',
2019-04-25 12:34:55 +02:00
'unauthorized'
);
2018-08-06 17:46:58 +02:00
}
}
2018-03-12 16:37:20 +01:00
// Retrieve `public` role.
if (!role) {
role = await strapi
.query('role', 'users-permissions')
.findOne({ type: 'public' }, []);
}
const route = ctx.request.route;
const permission = await strapi
.query('permission', 'users-permissions')
.findOne(
{
role: role.id,
type: route.plugin || 'application',
controller: route.controller,
action: route.action,
enabled: true,
},
2019-04-25 12:34:55 +02:00
[]
);
if (!permission) {
return handleErrors(ctx, undefined, 'forbidden');
}
// Execute the policies.
if (permission.policy) {
return await strapi.plugins['users-permissions'].config.policies[
permission.policy
](ctx, next);
}
// Execute the action.
await next();
};
const handleErrors = (ctx, err = undefined, type) => {
if (ctx.request.graphql === null) {
return (ctx.request.graphql = strapi.errors[type](err));
}
return ctx[type](err);
2019-02-28 19:22:01 +02:00
};