All files / node-activedirectory/lib/services service.isUserMemberOf.js

10.34% Statements 3/29
0% Branches 0/26
0% Functions 0/4
10.34% Lines 3/29

Press n or j to go to the next uncovered block, b, p or k for the previous block.

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 581x 1x                                                                                                               1x
const _     = require('underscore');
let log     = require('./internal/service.log');
/**
 * Checks to see if the specified user is a member of the specified group.
 *
 * @param {Object} [opts] Optional LDAP query string parameters to execute. { scope: '', filter: '', attributes: [ '', '', ... ], sizeLimit: 0, timelimit: 0 }
 * @param {String} username The username to check for membership.
 * @param {String} groupName The group to check for membership.
 * @param {Function} callback The callback to execute when completed. callback(err: {Object}, result: {Boolean})
 */
function isUserMemberOf(opts, username, groupName, callback) {
    var self = this;
 
    return new Promise((resolve, reject) => {
        if (typeof (groupName) === 'function') {
            callback = groupName;
            groupName = username;
            username = opts;
            opts = undefined;
        }
        log.trace('isUserMemberOf(%j,%s,%s)', opts, username, groupName);
    
        opts = _.defaults(_.omit(opts || {}, 'attributes'), {
            attributes: ['cn', 'dn']
        });
        self.getGroupMembershipForUser(opts, username, function (err, groups) {
            if (err) {
                if(callback){
                    callback(err);
                }                
                return reject(err);
            }
            if ((!groups) || (groups.length === 0)) {
                log.info('"%s" IS NOT a member of "%s". No groups found for user.', username, groupName);
                if(callback){
                    callback(null, false);
                }
                return resolve(false);
            }
    
            // Check to see if the group.distinguishedName or group.cn matches the list of
            // retrieved groups.
            var lowerCaseGroupName = (groupName || '').toLowerCase();
            var result = _.any(groups, function (item) {
                return (((item.dn || '').toLowerCase() === lowerCaseGroupName) ||
                    ((item.cn || '').toLowerCase() === lowerCaseGroupName));
            });
            log.info('"%s" %s a member of "%s"', username, result ? 'IS' : 'IS NOT', groupName);
            if(callback){
                callback(null, result);
            }
            return resolve(result);            
        });
    });
    
};
 
module.exports = isUserMemberOf;