2014-02-11 21:40:39 -06:00
|
|
|
var _ = require('lodash'),
|
2016-05-25 09:34:46 +02:00
|
|
|
Promise = require('bluebird'),
|
2017-12-14 03:01:23 +01:00
|
|
|
models = require('../../models'),
|
|
|
|
common = require('../../lib/common');
|
2014-02-11 21:40:39 -06:00
|
|
|
|
2017-10-05 20:01:34 +01:00
|
|
|
module.exports = {
|
2014-02-11 21:40:39 -06:00
|
|
|
user: function (id) {
|
2020-03-05 12:22:50 +02:00
|
|
|
return models.User.findOne({id: id, status: 'active'}, {withRelated: ['permissions', 'roles', 'roles.permissions']})
|
2014-02-11 21:40:39 -06:00
|
|
|
.then(function (foundUser) {
|
2016-05-25 09:34:46 +02:00
|
|
|
// CASE: {context: {user: id}} where the id is not in our database
|
|
|
|
if (!foundUser) {
|
2017-12-11 22:47:46 +01:00
|
|
|
return Promise.reject(new common.errors.NotFoundError({
|
|
|
|
message: common.i18n.t('errors.models.user.userNotFound')
|
|
|
|
}));
|
2016-05-25 09:34:46 +02:00
|
|
|
}
|
|
|
|
|
2014-02-11 21:40:39 -06:00
|
|
|
var seenPerms = {},
|
|
|
|
rolePerms = _.map(foundUser.related('roles').models, function (role) {
|
|
|
|
return role.related('permissions').models;
|
|
|
|
}),
|
2014-07-09 13:34:38 +02:00
|
|
|
allPerms = [],
|
|
|
|
user = foundUser.toJSON();
|
|
|
|
|
2014-02-11 21:40:39 -06:00
|
|
|
rolePerms.push(foundUser.related('permissions').models);
|
|
|
|
|
|
|
|
_.each(rolePerms, function (rolePermGroup) {
|
|
|
|
_.each(rolePermGroup, function (perm) {
|
|
|
|
var key = perm.get('action_type') + '-' + perm.get('object_type') + '-' + perm.get('object_id');
|
|
|
|
|
|
|
|
// Only add perms once
|
|
|
|
if (seenPerms[key]) {
|
|
|
|
return;
|
|
|
|
}
|
|
|
|
|
|
|
|
allPerms.push(perm);
|
|
|
|
seenPerms[key] = true;
|
|
|
|
});
|
|
|
|
});
|
|
|
|
|
2017-09-25 10:17:06 +01:00
|
|
|
// @TODO fix this!
|
|
|
|
// Permissions is an array of models
|
|
|
|
// Roles is a JSON array
|
2014-07-23 19:17:29 +01:00
|
|
|
return {permissions: allPerms, roles: user.roles};
|
2016-10-04 17:33:43 +02:00
|
|
|
});
|
2014-02-11 21:40:39 -06:00
|
|
|
},
|
|
|
|
|
2019-01-18 12:17:12 +01:00
|
|
|
apiKey(id) {
|
|
|
|
return models.ApiKey.findOne({id}, {withRelated: ['role', 'role.permissions']})
|
|
|
|
.then((foundApiKey) => {
|
|
|
|
if (!foundApiKey) {
|
|
|
|
throw new common.errors.NotFoundError({
|
|
|
|
message: common.i18n.t('errors.models.api_key.apiKeyNotFound')
|
|
|
|
});
|
|
|
|
}
|
|
|
|
|
|
|
|
// api keys have a belongs_to relationship to a role and no individual permissions
|
|
|
|
// so there's no need for permission deduplication
|
|
|
|
const permissions = foundApiKey.related('role').related('permissions').models;
|
|
|
|
const roles = [foundApiKey.toJSON().role];
|
|
|
|
|
|
|
|
return {permissions, roles};
|
|
|
|
});
|
2014-02-11 21:40:39 -06:00
|
|
|
}
|
|
|
|
};
|