{"size": 1095, "ext": "js", "max_stars_repo_path": "api/policies/isResearchEntityOwner.js", "max_stars_repo_name": "scientilla/scientilla", "max_stars_repo_stars_event_min_datetime": "2015-02-20T21:48:49.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-25T13:02:32.000Z", "max_issues_repo_path": "api/policies/isResearchEntityOwner.js", "max_issues_repo_name": "scientilla/scientilla", "max_issues_repo_issues_event_min_datetime": "2016-02-08T10:32:15.000Z", "max_issues_repo_issues_event_max_datetime": "2022-03-29T16:19:30.000Z", "max_forks_repo_path": "api/policies/isResearchEntityOwner.js", "max_forks_repo_name": "scientilla/scientilla", "max_forks_repo_forks_event_min_datetime": "2015-06-10T12:36:56.000Z", "max_forks_repo_forks_event_max_datetime": "2020-03-04T10:11:39.000Z"}
{"max_stars_count": 96, "max_issues_count": 33, "max_forks_count": 13, "avg_line_length": 33.1818181818, "max_line_length": 112, "alphanum_fraction": 0.598173516}
/* global ResearchEntity, User*/
'use strict';

module.exports = function (req, res, next) {
    waterlock.validator.validateTokenRequest(req, async function (err, user) {
        if (err) {
            return res.forbidden(err);
        }
        if (user.role === 'administrator')
            return next();

        const researchEntityId = +req.params.researchEntityId;
        const researchEntity = await ResearchEntity.findOne({id: researchEntityId}).populate(['user', 'group']);


        if (researchEntity && researchEntity.type === 'user')
            if (researchEntity.user[0].id === user.id)
                return next();

        if (researchEntity && researchEntity.type === 'group') {
            const u = await User.findOne({id: user.id}).populate('administratedGroups');
            const administratedGroupIds = u.administratedGroups.map(g => g.id);
            if (administratedGroupIds.includes(researchEntity.group[0].id))
                return next();
        }


        sails.log.debug('access forbidden ' + req.path);
        return res.forbidden(err);

    });
};
