All files / backend/utils roles.mjs

89.65% Statements 52/58
96.77% Branches 30/31
62.5% Functions 10/16
100% Lines 47/47

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 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117                                      17x 17x         7x 1x   6x 6x 6x 6x 6x       8x 8x 5x 1x         1x   4x       8x   7x 7x   7x 9x 16x 6x       7x     34x 80x   55x 22x 22x   33x       17x 14x           146x 146x         44x   44x 85x 19x 19x     25x 25x       47x 47x 29x 3x 3x     44x 44x            
/*
  Copyright (C) 2023 Sber
 
  Licensed under the Apache License, Version 2.0 (the "License");
  you may not use this file except in compliance with the License.
  You may obtain a copy of the License at
 
          http://www.apache.org/licenses/LICENSE-2.0
 
  Unless required by applicable law or agreed to in writing, software
  distributed under the License is distributed on an "AS IS" BASIS,
  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  See the License for the specific language governing permissions and
  limitations under the License.
*/
 
import cache from '../storage/cache.mjs';
import {getLoggerWithTag} from '@global/logger/v2/logger.mjs';
 
const logger = getLoggerWithTag('b/u/roles.mjs');
export const DEFAULT_ROLE = 'default';
 
let roleManifest;
 
export async function retrieveRolesManifest() {
    if (roleManifest) {
        return roleManifest;
    }
    const { URI } = global.$roles;
    const url = new URL(URI);
    logger.debug(() => `load role manifest from url ${url.toString()}`);
    roleManifest = await loader(url);
    return roleManifest;
}
 
export async function getCurrentRoleId(roles) {
    const ids = await getCurrentRoles(roles);
    if(ids.length === 0) return DEFAULT_ROLE;
    if(ids.length > 1){
        logger.info(() => [
            'A user must be assigned only one role in a project. A user can have multiple roles, but only one role can match the role in the role manifest (in a project)',
            {title: 'user roles', obj: roles},
            {title: 'user project roles', obj: ids}
        ]);
        throw Error('User must be assigned by only one role');
    }
    return ids[0];
}
 
async function getCurrentRoles(roles) {
    if(roles.length === 0) return [];
 
    const result = [];
    const manifest = await retrieveRolesManifest();
 
    for(let role in roles) {
        for(let nRole in manifest?.roles) {
            if(roles[role] === nRole) {
                result.push(nRole);
            }
        }
    }
    return result;
}
 
export const newManifest = (obj, exclude, filters)=> Object.entries(obj)
    .filter(([key, value]) => (typeof value != 'object' || Array.isArray(value) || matchExclude(key, exclude)) || matchRegex(key, filters))
    .reduce((acc, [key, value]) => {
        if(value != null && typeof value === 'object' && !Array.isArray(value)) {
            acc[key] = newManifest(value, exclude, filters);
            return acc;
        }
        return Array.isArray(obj) ?  [...acc, ...obj] : ({...acc, [key]: obj[key]});
    }, {});
 
export async function loader(uri) {
    const response = await cache.request(uri, '/');
    return response && (typeof response.data === 'object'
        ? response.data
        : JSON.parse(response.data));
}
 
export function isRolesMode() {
    const {MODE} =  global.$roles;
    return (MODE || 'N').toUpperCase() === 'Y';
}
 
function matchRegex(string, filters){
 
    const len = filters.length;
 
    for (let i = 0; i < len; i++) {
        if (string.match(filters[i])) {
            logger.trace(() => `[matchRegex] build menu element [${string}] = TRUE by filter [${filters[i]}]`);
            return true;
        }
    }
    logger.trace(() => `[matchRegex] build menu element [${string}] = FALSE`);
    return false;
}
 
function matchExclude(string, exclude) {
    const len = exclude.length;
    for (let i = 0; i < len; i++) {
        if (string === exclude[i]) {
            logger.trace(() => `[matchExclude] build menu element [${string}] = TRUE by filter exclude [${exclude[i]}]`);
            return true;
        }
    }
    logger.trace(() => `[matchExclude] build menu element [${string}] = FALSE`);
    return false;
}