Skip to content
Snippets Groups Projects
process.js 21.91 KiB
import("system.util");
import("system.db");
import("Sql_lib");

/**
 * Provides functions to work with permissions.
 * Don't instanciate this!
 * 
 * @class
 */
function PermissionUtil () {}

{ //block where variables declared with let are available to avoid unexpected side-effects

    let alias = SqlUtils.getSystemAlias();

    /**
 * Returns the ids of all subordinated permission sets of a given parent permission set.
 * 
 * @param {String} pSetId id of the parent permission set
 * 
 * @result {String[]} array with the ids of every subordinated permission set. The result can never be null.
 */
    PermissionUtil.getChildSetsOfSet = function (pSetId) 
    {   
        return db.array(db.COLUMN, SqlCondition.begin()
            .and("ASYS_PERMISSIONSET_ID = '" + pSetId + "'")
            .buildSql("select ASYS_PERMISSIONSETID from ASYS_PERMISSIONSET")
            , alias);
    }

    /**
 * Returns all subordinated permission actions of a given permission set.
 * 
 * @param {String} pSetId id of the parent permission set
 * 
 * @result {String[]} array with the ids of every subordinated permission action. The result can never be null.
 */
    PermissionUtil.getActionsOfSet = function (pSetId)
    {
        return db.array(db.COLUMN, SqlCondition.begin()
            .and("ASYS_PERMISSION.ASYS_PERMISSIONSET_ID = '" + pSetId + "'")
            .buildSql("select ASYS_PERMISSIONACTION.ASYS_PERMISSIONACTIONID from ASYS_PERMISSIONACTION"
                + " join ASYS_PERMISSION on ASYS_PERMISSION.ASYS_PERMISSIONID = ASYS_PERMISSIONACTION.ASYS_PERMISSION_ID")
            , alias);
    }
    
    /**
 * Returns all permission actions of the given permissions.
 * 
 * @param {String[]} pPermIds the ids of the permissions
 * 
 * @result {String[]} returns ids of all permission actions. The result can never be null.
 */
    PermissionUtil.getActions = function(pPermIds) {
        return db.table("select ASYS_PERMISSIONACTIONID from ASYS_PERMISSIONACTION where ASYS_PERMISSIONACTION.ASYS_PERMISSION_ID in ('" + pPermIds.join("','") + "')", alias);
    }

    /**
 * Returns the action a given permission action id.
 * 
 * @param {String} pActionId id of the action
 * 
 * @result {String} title of action as readable string of the given action id. Never 'null', empty string if there is no result.
 */
    PermissionUtil.resolveActionId = function (pActionId)
    {
        return db.cell(SqlCondition.begin()
            .and("ASYS_PERMISSIONACTIONID = '" + pActionId + "'")
            .buildSql("select ASYS_PERMISSIONACTION.ACTION from ASYS_PERMISSIONACTION")
            , alias);
    }

    /**
 * Converts a given array to an object with properties permissionid, entity, role, field, cond, action, accesstype. 
 * 
 * @param {String[]} pArr the array which should be converted to an object.
 * 
 * @result {{}} converted object
 */
    PermissionUtil.convertArrToObj = function(pArr) {
        var ret = pArr.map(function(x) {
            return {    
                "permissionid": x[0],
                "entity": x[1],
                "role": x[2],
                "field": x[3],
                "cond": x[4],
                "action": x[5],
                "accesstype": x[6],
                "condtype": x[7]
            }
        });
        return ret;
    }

    /**
 * Returns the first index at which a given permissionid can be found in an array, or -1 if it is not present.
 * 
 * @param {String[]} pPermTable permission table
 *  
 * @param {String} pPermId id of the permission
 *
 * @result {int} returns position (index) of the searched permission in the table, otherwise returns -1 if not found
 */
    PermissionUtil.indexOfPermId = function(pPermTable, pPermId) {
        var notFound = -1;
        for (var i = 0; i < pPermTable.length; i++) {
            if(pPermTable[i].permissionid == pPermId)
                return i;
        }
        return notFound;
    }

    /**
 * Checks a permission if the given actions are different to the actions in the database.
 * 
 * @param {String} pPermId permission id to which the actions are linked to
 * 
 * @param {String[]} pActionNew array of strings of new actions
 * 
 * @result {String[]} returns the different elements
 */
    PermissionUtil.getActionDiff = function(pPermId, pActionNew) {
        var sqlStr = "select ACTION from ASYS_PERMISSIONACTION where ASYS_PERMISSION_ID = '" + pPermId + "'";
        var actionOld = db.array(db.COLUMN, sqlStr, alias);
    
        return arrDiff(actionOld, pActionNew);
    }

    /**
 * Checks if the given string is different to the string of a column in the given database table.
 * 
 * @param {String} pId id of DB entry
 * 
 * @param {String} pString string which has to be checked if different
 * 
 * @param {String} pDbCol column to which the string is compared
 * 
 * @param {String} pDbTable database table
 * 
 * @result {Boolean} returns true if different, otherwise false
 */
    PermissionUtil.isDiff = function(pId, pString, pDbCol, pDbTable) {
        var sqlStr = "select " + pDbCol + " from " + pDbTable + " where " + pDbTable + "ID = '" + pId + "'";
        var stringDb = db.cell(sqlStr, alias);
        return stringDb != pString ? true : false;
    }

    /**
 * Updates the value of the column in table if the values are different.
 * 
 * @param {String} pId id of DB entry
 * 
 * @param {String} pValue string which gets checked if different
 * 
 * @param {String} pDbCol column to which the string is compared
 * 
 * @param {String} pDbTable database table
 * 
 * @result {Integer} number of records that were updated
 */
    PermissionUtil.updateIfDiff = function(pId, pValue, pDbCol, pDbTable) {
        if (PermissionUtil.isDiff(pId, pValue, pDbCol, pDbTable)) {
            var cols = [pDbCol];
            var vals = [pValue];
            var cond = SqlCondition.begin().and(pDbTable + "ID = '" + pId + "'").build();
            return db.updateData(pDbTable, cols, null, vals, cond, alias);
        }
        return 0;
    }

    /**
 * Gets the number of permissions which are linked to the given entity.
 * 
 * @param {String} pEntityName name of the entity
 * 
 * @result {Integer} returns number of permissions linked to the entity.
 */
    PermissionUtil.getNumberOfPermissions = function(pEntityName) {
        var table = "ASYS_PERMISSIONSET";
        var sqlStr = "select COUNT(*) from " + table + " where ENTITY_ID = '" + pEntityName + "'";
        return db.cell(sqlStr, alias);
    }

    /**
 * Gets the default permission of the root permission set.
 * 
 * @param {String} pPermId id of the permission
 * 
 * @result {String} returns id of the default permission of the root permission set. Never 'null', empty string if there is no result.
 */
    PermissionUtil.getPermissionRoot = function(pPermId) {
        var parentSet = [PermissionUtil.getParentSet(pPermId)];

        while (parentSet[0] != "") {
            let sqlStr = "select ASYS_PERMISSIONSET_ID, ASYS_PERMISSIONSETID from ASYS_PERMISSIONSET where ASYS_PERMISSIONSETID = '" + parentSet[0] + "'";
            parentSet = db.array(db.ROW, sqlStr, alias);
        }
    
        return PermissionUtil.getPermissionWithoutCond(parentSet[1]);
    }

    /**
 * Gets the default permission of a given permission set.
 * 
 * @param {String} pSetId id of the permission set
 * 
 * @result {String} returns id of default permission of given set. Never 'null', empty string if there is no result.
 */
    PermissionUtil.getPermissionWithoutCond = function(pSetId) {
        var sqlStr = "select ENTITY_ID from ASYS_PERMISSIONSET where ASYS_PERMISSIONSETID = '" + pSetId + "'";
        var entityName = db.cell(sqlStr, alias);
        var noCond = "{\"entity\":\"" + entityName + "\",\"filter\":{\"type\":\"group\",\"operator\":\"AND\",\"childs\":[]}}";
    
        sqlStr = "select ASYS_PERMISSIONID from ASYS_PERMISSION"
        + " where ASYS_PERMISSIONSET_ID = '" + pSetId + "'"
        + " and (COND is null or COND like '%" + noCond + "%')";
        return db.cell(sqlStr, alias);
    }

    /**
 * Gets the permissions with conditions of a given permission set.
 * 
 * @param {String} pSetId the id of the permission set
 * 
 * @result {String[]} returns the ids of permissions with conditions of a given permission set. The result can never be null.
 */
    PermissionUtil.getPermissionWithCond = function(pSetId) {
        var sqlStr = "select ENTITY_ID from ASYS_PERMISSIONSET where ASYS_PERMISSIONSETID = '" + pSetId + "'";
        var entityName = db.cell(sqlStr, alias);
        var noCond = "{\"entity\":\"" + entityName + "\",\"filter\":{\"type\":\"group\",\"operator\":\"AND\",\"childs\":[]}}";
    
        sqlStr = "select ASYS_PERMISSIONID from ASYS_PERMISSION"
        + " where ASYS_PERMISSIONSET_ID = '" + pSetId + "'"
        + " and COND is not null and COND not like '" + noCond + "'";
        return db.table(sqlStr, alias);
    }

    /**
 * Gets the permission set id of a given role-entity-accesstype-combination.
 * 
 * @param {String} pRole name of the role
 * 
 * @param {String} pEntity name of the entity
 * 
 * @param {String} pAccessType name of the access type (E,R,F)
 * 
 * @param {String} pField name of the field
 * 
 * @result {String} returns id of the matching permission set. The result can never be null.
 */
    PermissionUtil.getSet = function(pRole, pEntity, pAccessType, pField) {
        var sqlStr = "select ASYS_PERMISSIONSETID from ASYS_PERMISSIONSET"
        + " where ROLE_ID = '" + pRole + "' and ENTITY_ID = '" + pEntity + "' and ACCESSTYPE = '" + pAccessType + "'";
        if (pField != null && pField != "" && pField != undefined) {
            sqlStr += " and FIELD_ID = '" + pField + "'";
        }
        return db.cell(sqlStr, alias);
    }

    /**
 * Gets the root permission set of a entity-role-combination.
 * 
 * @param {String} pRole id of a role
 * 
 * @param {String} pEntity id of an entity
 * 
 * @result {String} returns id of the root permission set of the given entity-role-combination. Never 'null', empty string if there is no result.
 */
    PermissionUtil.getSetRoot = function(pRole, pEntity) {
        var sqlStr = "select ASYS_PERMISSIONSETID from ASYS_PERMISSIONSET"
        + " where ROLE_ID = '" + pRole + "' and ENTITY_ID = '" + pEntity +"' and ACCESSTYPE = 'E'";
        return db.cell(sqlStr, alias);
    }

    /**
 * Gets the parent permission set of a permission.
 * 
 * @param {String} pPermId id of the permission
 * 
 * @result {String} returns id of the parent set of the given permission. Never 'null', empty string if there is no result.
 */
    PermissionUtil.getParentSet = function(pPermId) {
        var sqlStr = "select ASYS_PERMISSIONSET_ID from ASYS_PERMISSION"
        + " where ASYS_PERMISSIONID = '" + pPermId + "'";
        return db.cell(sqlStr, alias);
    }
    
    /**
 * Gets the parent permission set of a set.
 * 
 * @param {String} pSetId id of the permission set
 * 
 * @result {String} returns id of the parent permission set of the given set. Never 'null', empty string if there is no result.
 */
    PermissionUtil.getParentSetOfSet = function(pSetId) {
        var sqlStr = "select ASYS_PERMISSIONSET_ID from ASYS_PERMISSIONSET"
        + " where ASYS_PERMISSIONSETID = '" + pSetId + "'";
        return db.cell(sqlStr, alias);
    }

    /**
 * Checks if the given permission set has any children left.
 * 
 * @param {String} pSetId id of the permission set
 * 
 * @result {Boolean} returns true if permission set has no children, otherwise false
 */
    PermissionUtil.setIsEmpty = function(pSetId) {
        var subSets = PermissionUtil.getChildSetsOfSet(pSetId);
        var subPerms = PermissionUtil.getPermissions([pSetId]);
        var subActions = PermissionUtil.getActionsOfSet(pSetId);
    
        if (subActions.length == 0 && subPerms.length == 0 && subSets.length == 0) 
            return true;
        return false;
    }

    /**
 * Returns all subordinated permissions of the given permission sets.
 * 
 * @param {String[]} pSetIds ids of the permission sets
 * 
 * @result {String[]} array with ids of all subordinated permissions. The result can never be null.
 */
    PermissionUtil.getPermissions = function(pSetIds) {
        return db.table("select ASYS_PERMISSIONID from ASYS_PERMISSION where ASYS_PERMISSION.ASYS_PERMISSIONSET_ID in ('" + pSetIds.join("','") + "')", alias);
    }

    /**
 * Returns the condition type of the given permissions.
 * 
 * @param {String} pPermId the id of the permission
 * 
 * @result {String} returns the value of condition type (true or false). Never 'null', empty string if there is no result.
 */
    PermissionUtil.getPermissionCondType = function(pPermId) {
        return db.cell("select CONDTYPE from ASYS_PERMISSION where ASYS_PERMISSION.ASYS_PERMISSIONID = '" + pPermId + "'", alias);
    }
    
    /**
 * Inserts a new instance of a permission set into ASYS_PERMISSIONSET.
 * 
 * @param {String} pParentPermSetId parent permission set, empty if root node
 * 
 * @param {String} pEntity entity to which the PermissionSet is linked, mandatory
 * 
 * @param {String} pRole Role to which the PermissionSet is linked, mandatory
 * 
 * @param {String} pField Field to which the PermissionSet is linked, empty if no field permission
 * 
 * @param {String} pAccessType Entity, Record or Field (E, R, F), mandatory
 * 
 * @result {Integer} returns id of the inserted permission set
 */
    PermissionUtil.insertSet = function(pParentPermSetId, pEntity, pRole, pField, pAccessType) {
        var table = "ASYS_PERMISSIONSET";
        var cols = db.getColumns(table, alias);
        var setId = util.getNewUUID();
        var vals = [pAccessType, setId, pParentPermSetId, pEntity, pField, pRole];
        db.insertData(table, cols, null, vals, alias);
        return setId;
    }

    /**
 * Inserts a new instance of a permission into ASYS_PERMISSION.
 * 
 * @param {String} pParentSetId parent permission set, mandatory
 * 
 * @param {String} pCond condition of the permission, empty if no condition
 * 
 * @param {String} pCondType condition Type of the permission, should nearly always be "true"
 * 
 * @param {String} pPermId id of the new permission (can be empty/null)
 * 
 * @result {Integer} returns id of the inserted permission
 */
    PermissionUtil.insertPermission = function(pParentSetId, pCond, pCondType, pPermId) {
        var table = "ASYS_PERMISSION";
        var cols = db.getColumns(table, alias);
        var permId;
        if (pPermId != null && pPermId != "" && pPermId != undefined) {
            permId = pPermId;
        } else {
            permId = util.getNewUUID(); 
        }
        var vals = [permId, pParentSetId, pCond, pCondType];
        db.insertData(table, cols, null, vals, alias);  
        return permId;
    }

    /**
 * Inserts a new instance of a permission action into ASYS_PERMISSIONACTION.
 * 
 * @param {String} pParentPermId parent permission, mandatory
 * 
 * @param {String} pAction title of action (view, create,...), mandatory
 * 
 * @param {String} pActionId id of the new permission action
 * 
 * @result {Integer} returns id of the inserted permission action, returns null if insert was not possible
 */
    PermissionUtil.insertAction = function(pParentPermId, pAction, pActionId) {
        var table = "ASYS_PERMISSIONACTION";
        var cols = db.getColumns(table, alias);
        var actionId;
        var sqlStr = "select ASYS_PERMISSIONACTIONID from ASYS_PERMISSIONACTION where ASYS_PERMISSIONACTIONID = '" + pActionId + "'";

        if (pActionId != null & pActionId != "" && pActionId != undefined && db.cell(sqlStr, alias) == "") {
            actionId = pActionId;
        } else {
            actionId = util.getNewUUID(); // if same id is already in db -> create new UID
        }
        var vals = [pAction, actionId, pParentPermId];
        if (db.insertData(table, cols, null, vals, alias) == 0) {
            return null;
        }
        return actionId;
    }

    /**
     * Returns the cond type of a permission.
     * 
     * @param {String} pPermId id of the permission which condition type should be returned, mandatory
     * 
     * @result {Integer} returns the cond type of a permission
     */
    PermissionUtil.getCondType = function(pPermId) {
        var table = "ASYS_PERMISSION";
        var sqlStr = "select CONDTYPE from " + table + " where ASYS_PERMISSIONID = '" + pPermId + "'";
        return db.cell(sqlStr, alias);
    }
    
    /**
     * Returns the condition of a permission.
     * 
     * @param {String} pPermId id of the permission which condition should be returned, mandatory
     * 
     * @result {String} returns the condition of a permission
     */
    PermissionUtil.getCond = function(pPermId) {
        var table = "ASYS_PERMISSION";
        var sqlStr = "select COND from " + table + " where ASYS_PERMISSIONID = '" + pPermId + "'";
        return db.cell(sqlStr, alias);
    }

    /**
     * Returns true if the permission exists, otherwise false.
     * 
     * @param {String} pPermId The permission id
     * 
     * @result {Boolean} true if permission exists, otherwise false
     */
    PermissionUtil.permissionExists = function(pPermId) {
        var table = "ASYS_PERMISSION";
        var sqlStr = "select COUNT(*) from " + table + " where ASYS_PERMISSIONID = '" + pPermId + "'";
        if (db.cell(sqlStr, alias) != "0") {
            return true;
        }
        return false;
    }
    
    /**
     * Returns true if the action exists, otherwise false.
     * 
     * @param {String} pActionId The id of the action
     * 
     * @result {Boolean} true if action exists, otherwise false
     */
    PermissionUtil.actionExists = function(pActionId) {
        var table = "ASYS_PERMISSIONACTION";
        var sqlStr = "select COUNT(*) from " + table + " where ASYS_PERMISSION_ID = '" + pActionId + "'";
        if (db.cell(sqlStr, alias) != "0") {
            return true;
        }
        return false;
    }

    /**
     * Returns true if the action exists, otherwise false.
     * 
     * @param {String} pAction The title of the action (e.g. view, create, read, update, delete)
     * 
     * @param {String} pPermId The ID of the permission to which the action is linked
     * 
     * @result {Boolean} true if action exists, otherwise false
     */
    PermissionUtil.actionExists = function(pAction, pPermId) {
        var table = "ASYS_PERMISSIONACTION";
        var sqlStr = "select COUNT(*) from " + table + " where ACTION = '" + pAction + "' and ASYS_PERMISSION_ID = '" + pPermId + "'";
        if (db.cell(sqlStr, alias) != "0") {
            return true;
        }
        return false;
    }

    /**
     * Returns permissionid of the permission with fitting parameters, otherwise returns empty string
     * 
     * @param {String} pRole name of the role
     * 
     * @param {String} pEntity name of the entity
     * 
     * @param {String} pField name of the field
     * 
     * @param {String} pAccesstype accesstype (E,F,R)
     * 
     * @param {String} pCondition condition (Filter in JSON-format)
     * 
     * @param {String} pCondtype type of the condition (true/false)
     * 
     * @result {String} Returns the id of the permission with fitting parameters, otherwise returns empty string, can never be null
     *
     */
    PermissionUtil.getPermission = function(pRole, pEntity, pField, pAccesstype, pCondition, pCondtype) {
        var sqlStr = "";
        var sqlExt = "";
        var noCond = "{\"entity\":\"" + pEntity + "\",\"filter\":{\"type\":\"group\",\"operator\":\"AND\",\"childs\":[]}}";
    
        if (checkInput([pCondition])) {
            if (pCondition == noCond) {
                sqlExt += " and (COND like '%" + pCondition + "%' or COND is null)";
            } else {
                sqlExt += " and COND like '%" + pCondition + "%'";
            }
        }
    
        if (checkInput([pField])) {
            sqlExt += " and FIELD_ID = '" + pField + "'";
        }
    
        if (checkInput([pCondtype])) {
            sqlExt += " and CONDTYPE = '" + pCondtype + "'";
        }
    
        sqlStr = "select ASYS_PERMISSION.ASYS_PERMISSIONID from ASYS_PERMISSIONSET"
        + " join ASYS_PERMISSION on ASYS_PERMISSION.ASYS_PERMISSIONSET_ID = ASYS_PERMISSIONSET.ASYS_PERMISSIONSETID"
        + " where ENTITY_ID = '" + pEntity + "' and ROLE_ID = '" + pRole + "'"
        + " and ACCESSTYPE = '" + pAccesstype + "'" + sqlExt;
        var permId = db.cell(sqlStr, alias);
        return permId;
    }

    /**
     * Deletes a permission action from ASYS_PERMISSIONACTION.
     * 
     * @param {String} pActionId permission action id which should be deleted, mandatory
     * 
     * @result {Integer} returns number of deleted records
     */
    PermissionUtil.deleteAction = function(pActionId) {
        var table = "ASYS_PERMISSIONACTION";
        var cond = " ASYS_PERMISSIONACTIONID = '" + pActionId + "'";
        return db.deleteData(table, cond, alias);
    }

} //end of block

// arrDiff calculates different elements of two arrays and returns them as array, otherwise empty array
function arrDiff (arr1, arr2) {
    var helperArr = [], diff = [];

    for (let i = 0; i < arr1.length; i++) {
        helperArr[arr1[i]] = true;
    }

    for (let i = 0; i < arr2.length; i++) {
        if (helperArr[arr2[i]]) {
            delete helperArr[arr2[i]];
        } 
        else {
            helperArr[arr2[i]] = true;
        }
    }

    for (var k in helperArr) {
        diff.push(k);
    }

    return diff;
}

// checks input array if each element is a valid input, returns true if valid, otherwise false
function checkInput(pInputArr) {
    for each (var input in pInputArr) {
        if (input == undefined || input == null || input == "")
            return false;
    }
    return true;
}