2014-02-12 07:40:39 +04:00
|
|
|
var _ = require('lodash'),
|
2016-05-25 10:34:46 +03:00
|
|
|
Promise = require('bluebird'),
|
2014-02-12 07:40:39 +04:00
|
|
|
Models = require('../models'),
|
2014-09-10 08:06:24 +04:00
|
|
|
errors = require('../errors'),
|
2016-05-25 10:34:46 +03:00
|
|
|
i18n = require('../i18n'),
|
2014-09-10 08:06:24 +04:00
|
|
|
effective;
|
2014-02-12 07:40:39 +04:00
|
|
|
|
2014-09-10 08:06:24 +04:00
|
|
|
effective = {
|
2014-02-12 07:40:39 +04:00
|
|
|
user: function (id) {
|
2014-09-10 08:06:24 +04:00
|
|
|
return Models.User.findOne({id: id, status: 'all'}, {include: ['permissions', 'roles', 'roles.permissions']})
|
2014-02-12 07:40:39 +04:00
|
|
|
.then(function (foundUser) {
|
2016-05-25 10:34:46 +03:00
|
|
|
// CASE: {context: {user: id}} where the id is not in our database
|
|
|
|
if (!foundUser) {
|
2016-10-06 15:27:35 +03:00
|
|
|
return Promise.reject(new errors.NotFoundError({message: i18n.t('errors.models.user.userNotFound')}));
|
2016-05-25 10:34:46 +03:00
|
|
|
}
|
|
|
|
|
2014-02-12 07:40:39 +04:00
|
|
|
var seenPerms = {},
|
|
|
|
rolePerms = _.map(foundUser.related('roles').models, function (role) {
|
|
|
|
return role.related('permissions').models;
|
|
|
|
}),
|
2014-07-09 15:34:38 +04:00
|
|
|
allPerms = [],
|
|
|
|
user = foundUser.toJSON();
|
|
|
|
|
2014-02-12 07:40:39 +04: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;
|
|
|
|
});
|
|
|
|
});
|
|
|
|
|
2014-07-23 22:17:29 +04:00
|
|
|
return {permissions: allPerms, roles: user.roles};
|
2016-10-04 18:33:43 +03:00
|
|
|
});
|
2014-02-12 07:40:39 +04:00
|
|
|
},
|
|
|
|
|
|
|
|
app: function (appName) {
|
2014-09-10 08:06:24 +04:00
|
|
|
return Models.App.findOne({name: appName}, {withRelated: ['permissions']})
|
2014-02-12 07:40:39 +04:00
|
|
|
.then(function (foundApp) {
|
|
|
|
if (!foundApp) {
|
|
|
|
return [];
|
|
|
|
}
|
|
|
|
|
2014-07-23 22:17:29 +04:00
|
|
|
return {permissions: foundApp.related('permissions').models};
|
2016-10-04 18:33:43 +03:00
|
|
|
});
|
2014-02-12 07:40:39 +04:00
|
|
|
}
|
|
|
|
};
|
|
|
|
|
2014-09-10 08:06:24 +04:00
|
|
|
module.exports = effective;
|