Secure your code as it's written. Use Snyk Code to scan source code in minutes - no build needed - and fix issues immediately.
const { params, type, method } = context;
const currentPermissions = await Promise.resolve(typeof permissions === 'function' ? permissions(context) : permissions);
if (type !== 'before') {
throw new Error('The feathers-permissions hook should only be used as a \'before\' hook.');
}
debug('Running checkPermissions hook with options:', { entityName, field, roles: permissions });
const entity = context.params[entityName];
if (!entity) {
debug(`hook.params.${entityName} does not exist. If you were expecting it to be defined check your hook order and your idField options in your auth config.`);
if (params.provider) {
throw new Forbidden('You do not have the correct permissions (invalid permission entity).');
}
return context;
}
// Normalize permissions. They can either be a comma separated string or an array.
const value = get(entity, field, []);
const permissionList = typeof value === 'string'
? value.split(',').map(current => current.trim()) : value;
const requiredPermissions = [
'*',
`*:${method}`
];
currentPermissions.forEach(permission => requiredPermissions.push(
`${permission}`,
hook.service.get(hook.id, params).then(data => {
if (data.toJSON) {
data = data.toJSON();
} else if (data.toObject) {
data = data.toObject();
}
let field = get(data, options.ownerField);
// Handle nested Sequelize or Mongoose models
if (isPlainObject(field)) {
field = field[options.idField];
}
if (field === undefined || field.toString() !== id.toString()) {
reject(new errors.Forbidden('You do not have the permissions to access this.'));
}
resolve(hook);
}).catch(reject);
});
if (!hook.params.provider) {
return hook;
}
if (!hook.params.user) {
// TODO (EK): Add a debugger call to remind the dev to check their hook chain
// as they probably don't have the right hooks in the right order.
throw new errors.NotAuthenticated();
}
options = Object.assign({}, defaults, hook.app.get('authentication'), options);
let authorized = false;
let roles = get(hook.params.user, options.fieldName);
const id = get(hook.params.user, options.idField);
const error = new errors.Forbidden('You do not have valid permissions to access this.');
if (id === undefined) {
throw new Error(`'${options.idField} is missing from current user.'`);
}
// If the user doesn't even have a `fieldName` field and we're not checking
// to see if they own the requested resource return Forbidden error
if (!options.owner && roles === undefined) {
throw error;
}
// If the roles is not an array, normalize it
if (!Array.isArray(roles)) {
roles = [roles];
}
throw new errors.Forbidden('no used id found');
}
// 2. get system settings for max invite count
let settings = await this.app.service('settings').find({query: {key: 'system'}});
settings = settings.pop();
// do cancel of the settings prohibit it
if (!settings || !settings.invites || !settings.invites.userCanInvite || !settings.invites.maxInvitesByUser) {
throw new errors.Forbidden('system settings not valid');
}
// 3. get user invite count
const maxInvitesByUser = settings.invites.maxInvitesByUser;
// 4. check if the user has still free invites
const myInvites = await this.find(Object.assign(params, {query: { $limit: -1 }}));
let remainingInvites = maxInvitesByUser - myInvites.total;
if (remainingInvites <= 0) {
throw new errors.Forbidden('no invites left');
}
// 5. generate one remaining free invites
let output = [];
while (remainingInvites--) {
const res = await this.app.service('invites').create({
email: uuid(),
code: genInviteCode(),
invitedByUserId: params.user._id,
role: 'user'
});
output.push(res);
}
return output;
}
if (error.statusCode) {
switch (error.statusCode) {
case 400:
feathersError = new errors.BadRequest(error);
break;
case 401:
feathersError = new errors.NotAuthenticated(error);
break;
case 402:
feathersError = new errors.PaymentError(error);
break;
case 403:
feathersError = new errors.Forbidden(error);
break;
case 404:
feathersError = new errors.NotFound(error);
break;
case 405:
feathersError = new errors.MethodNotAllowed(error);
break;
case 406:
feathersError = new errors.NotAcceptable(error);
break;
case 408:
feathersError = new errors.Timeout(error);
module.exports = () => hook => {
if(!hook.params || !hook.params.user || hook.params.user.role !== 'admin') {
throw new errors.Forbidden('You don\'t have admin rights.');
}
return hook;
};
const { name, message } = error;
if (name.startsWith('Sequelize')) {
switch (name) {
case 'SequelizeValidationError':
case 'SequelizeUniqueConstraintError':
case 'SequelizeExclusionConstraintError':
case 'SequelizeForeignKeyConstraintError':
case 'SequelizeInvalidConnectionError':
throw wrap(new errors.BadRequest(message, { errors: error.errors }), error);
case 'SequelizeTimeoutError':
case 'SequelizeConnectionTimedOutError':
throw wrap(new errors.Timeout(message), error);
case 'SequelizeConnectionRefusedError':
case 'SequelizeAccessDeniedError':
throw wrap(new errors.Forbidden(message), error);
case 'SequelizeHostNotReachableError':
throw wrap(new errors.Unavailable(message), error);
case 'SequelizeHostNotFoundError':
throw wrap(new errors.NotFound(message), error);
default:
throw wrap(new errors.GeneralError(message), error);
}
}
throw error;
};
module.exports = () => hook => {
if(!hook.params || !hook.params.user || !['admin','moderator'].includes(hook.params.user.role)) {
throw new errors.Forbidden('You don\'t have moderator rights.');
}
return hook;
};
async find (params) {
if (!params.user._id) {
throw new errors.Forbidden('no user id found');
}
const res = await this.app.service('invites').find(Object.assign(params.query || {}, {
query: {
$limit: 30,
invitedByUserId: params.user._id
}
}));
return res;
}
try {
return await hook.app.service(service).remove(null, {query});
} catch (err) {
hook.app.error('ERROR ON SERVICE' + service);
throw new errors.GeneralError(err.message);
}
}
if (hook.method !== 'remove') {
hook.app.error('removeAllRelatedUserData hook works only on remove');
return hook;
}
const user = hook.params.user;
if (!user || !user._id) {
throw new errors.Forbidden('Forbidden');
}
const query = hook.params.query;
if (query.deleteContributions === true) {
await deleteData('contributions', {
userId: user._id,
type: 'post'
});
}
delete hook.params.query.deleteContributions;
if (query.deleteCandos === true) {
await deleteData('contributions', {
userId: user._id,
type: 'cando'