"use strict";
Object.defineProperty(exports, "__esModule", {
    value: true
});
function _export(target, all) {
    for(var name in all)Object.defineProperty(target, name, {
        enumerable: true,
        get: Object.getOwnPropertyDescriptor(all, name).get
    });
}
_export(exports, {
    get getAbilityForUser () {
        return getAbilityForUser;
    },
    get getPermissionsForRoles () {
        return getPermissionsForRoles;
    },
    get queryPermissionsForRoles () {
        return queryPermissionsForRoles;
    },
    get setHardcodedPermissionsUseForTestsOnly () {
        return setHardcodedPermissionsUseForTestsOnly;
    },
    get unsetUseHardcodedPermissionsUseForTestsOnly () {
        return unsetUseHardcodedPermissionsUseForTestsOnly;
    }
});
const _config = /*#__PURE__*/ _interop_require_default(require("config"));
const _buildAbility = require("./buildAbility");
const _roles = /*#__PURE__*/ _interop_require_wildcard(require("../roles"));
function _interop_require_default(obj) {
    return obj && obj.__esModule ? obj : {
        default: obj
    };
}
function _getRequireWildcardCache(nodeInterop) {
    if (typeof WeakMap !== "function") return null;
    var cacheBabelInterop = new WeakMap();
    var cacheNodeInterop = new WeakMap();
    return (_getRequireWildcardCache = function(nodeInterop) {
        return nodeInterop ? cacheNodeInterop : cacheBabelInterop;
    })(nodeInterop);
}
function _interop_require_wildcard(obj, nodeInterop) {
    if (!nodeInterop && obj && obj.__esModule) {
        return obj;
    }
    if (obj === null || typeof obj !== "object" && typeof obj !== "function") {
        return {
            default: obj
        };
    }
    var cache = _getRequireWildcardCache(nodeInterop);
    if (cache && cache.has(obj)) {
        return cache.get(obj);
    }
    var newObj = {
        __proto__: null
    };
    var hasPropertyDescriptor = Object.defineProperty && Object.getOwnPropertyDescriptor;
    for(var key in obj){
        if (key !== "default" && Object.prototype.hasOwnProperty.call(obj, key)) {
            var desc = hasPropertyDescriptor ? Object.getOwnPropertyDescriptor(obj, key) : null;
            if (desc && (desc.get || desc.set)) {
                Object.defineProperty(newObj, key, desc);
            } else {
                newObj[key] = obj[key];
            }
        }
    }
    newObj.default = obj;
    if (cache) {
        cache.set(obj, newObj);
    }
    return newObj;
}
function getHardcodedPermissions(roleIds) {
    const permissions = _roles[roleIds];
    if (!permissions) {
        throw new Error(`Invalid role: ${roleIds}`);
    }
    return permissions;
}
//---------------------------------------------------------
const commaSplit = (s)=>s.split(',').map((x)=>x.trim()).filter((x)=>x);
async function queryPermissionsForRoles({ Permission }, roleString) {
    const roleIds = commaSplit(roleString);
    const result = await Permission.sequelize.query(`
    SELECT *
      FROM permissions
      WHERE permissions.role_id IN (:roleIds)
      AND permissions.deleted_at IS NULL
  `, {
        model: Permission,
        mapToModel: true,
        replacements: {
            roleIds
        }
    });
    return result.map((r)=>r.forResponse());
}
// these functions allow testing permissions in isolation
// they should ONLY be used in tests
let useHardcodedPermissions = Boolean(_config.default?.auth?.useHardcodedPermissions);
function setHardcodedPermissionsUseForTestsOnly(val) {
    useHardcodedPermissions = Boolean(val);
}
function unsetUseHardcodedPermissionsUseForTestsOnly() {
    useHardcodedPermissions = _config.default.auth.useHardcodedPermissions;
}
async function getPermissionsForRoles(models, roleString) {
    if (useHardcodedPermissions) {
        return getHardcodedPermissions(roleString);
    }
    // don't await this -- we want to store the promise, not the result
    // so that quick consecutive requests can benefit from it
    const permissions = queryPermissionsForRoles(models, roleString);
    return permissions;
}
async function getAbilityForUser(models, user, { impersonateRoleId } = {}) {
    if (!user) {
        return (0, _buildAbility.buildAbility)([]);
    }
    if (impersonateRoleId) {
        if (user.role !== 'admin') {
            throw new Error('Only admin users can impersonate roles');
        }
        const permissions = await getPermissionsForRoles(models, impersonateRoleId);
        // When impersonating, admins retain ability to read/write their own User record
        // so they can access user settings and stop impersonation
        return (0, _buildAbility.buildAbility)([
            ...permissions,
            {
                verb: 'read',
                noun: 'User',
                objectId: user.id
            },
            {
                verb: 'write',
                noun: 'User',
                objectId: user.id
            }
        ]);
    }
    const permissions = await getPermissionsForRoles(models, user.role);
    const ability = (0, _buildAbility.buildAbilityForUser)(user, permissions);
    return ability;
}

//# sourceMappingURL=rolesToPermissions.js.map