All files / backend/helpers account.mjs

92% Statements 69/75
100% Branches 39/39
68.42% Functions 13/19
100% Lines 64/64

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 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145                                      14x 14x     14x                 14x 28x 28x         28x 7x 7x     21x 21x   1x 1x       14x 15x 9x 9x     6x   6x 2x 2x   4x     14x 14x   14x 15x     14x 21x 15x     14x 15x 15x   15x 8x 7x 1x 6x 2x   4x     14x 30x     14x 9x     14x 90x 90x 90x   33x   50x   1x     6x       14x 15x 15x   15x 15x 15x 15x 15x     15x 15x   15x 15x   15x                    
/*
  Copyright (C) 2022 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 {getLoggerWithTag} from '@global/logger/v2/logger.mjs';
import {JSONPath} from 'jsonpath-plus';
 
const LOG_TAG =  'account';
const logger = getLoggerWithTag(LOG_TAG);
 
// Дефолтно, мапим на встроенные в keycloak поля
const defaultFieldMapping = {
    name:    'given_name',
    surname: 'family_name',
    email:   'email',
    roles:   'realm_access.roles',
    userId:  'sid',
    sub:     'sub'
};
 
const parseConfigEnv = (configEnvVar) => {
    const raw = process.env[configEnvVar];
    logger.trace(() => [
        `envName: ${configEnvVar}`,
        `raw Data: ${raw}`
    ]);
 
    if (!raw) {
        logger.error(() => `Environment variable ${configEnvVar} is not set`);
        return null;
    }
 
    try {
        return JSON.parse(raw);
    } catch (error) {
        logger.error(() => `Failed to parse JSON in ${configEnvVar}: ${error.message}`);
        return null;
    }
};
 
const getConfigForIssuer = (parsedConfig, issuer, configType) => {
    if (!Array.isArray(parsedConfig)) {
        logger.error(() => `${configType} configuration is not an array`);
        return null;
    }
 
    const providerConfig = parsedConfig.find((p) => p.iss === issuer);
 
    if (!providerConfig) {
        logger.error(() => `${configType} config not found for issuer "${issuer}"`);
        return null;
    }
    return providerConfig;
};
 
const VUE_APP_DOCHUB_AUTH_USER_CONFIG_PARSED = parseConfigEnv('VUE_APP_DOCHUB_AUTH_USER_CONFIG');
const VUE_APP_DOCHUB_ROLES_CONFIG_PARSED = parseConfigEnv('VUE_APP_DOCHUB_ROLES_CONFIG');
 
export const getUserConfigForIssuer = (issuer) => {
    return getConfigForIssuer(VUE_APP_DOCHUB_AUTH_USER_CONFIG_PARSED, issuer, 'User info');
};
 
const translateRole = (role) => {
    const roleMapping = VUE_APP_DOCHUB_ROLES_CONFIG_PARSED.find(r => r.role === role);
    return roleMapping ? toLowerCase(roleMapping.label) : null;
};
 
const computeInitials = (name, surname) => {
    const nameNorm = normalize(name);
    const surnameNorm = normalize(surname);
 
    if (nameNorm && surnameNorm) {
        return `${nameNorm[0]}${surnameNorm[0]}`.toUpperCase();
    } else if (nameNorm) {
        return nameNorm[0].toUpperCase();
    } else if (surnameNorm) {
        return surnameNorm[0].toUpperCase();
    }
    return null;
};
 
const normalize = (value) => {
    return typeof value === 'string' && value !== 'NULL' ? value : null;
};
 
const toLowerCase = (str) => {
    return str.toLowerCase();
};
 
const getJsonPathValue = (obj, pathExpr) => {
    try {
        const result = JSONPath({ path: pathExpr, json: obj });
        switch (result.length) {
            case 0:
                return '';
            case 1:
                return result[0];
            default:
                return result;
        }
    } catch (e) {
        return '';
    }
};
 
export const extractUserData = (payload) => {
        const config = getUserConfigForIssuer(payload?.iss) || defaultFieldMapping;
        logger.trace(() => `User data config: ${JSON.stringify(config)}`);
 
        const sub     = getJsonPathValue(payload, config.sub     || defaultFieldMapping.sub)
            , userId  = getJsonPathValue(payload, config.userId  || defaultFieldMapping.userId)
            , name    = getJsonPathValue(payload, config.name    || defaultFieldMapping.name)
            , surname = getJsonPathValue(payload, config.surname || defaultFieldMapping.surname)
            , email   = getJsonPathValue(payload, config.email   || defaultFieldMapping.email)
            ;
 
        let rawRoles = getJsonPathValue(payload, config.roles || defaultFieldMapping.roles);
        if (!Array.isArray(rawRoles)) rawRoles = [rawRoles].filter(Boolean);
 
        const roles = rawRoles.map(role => translateRole(role)).filter(label => label !== null);
        const initials = computeInitials(name, surname);
 
        return {
            sub,
            userId,
            name,
            surname,
            email,
            roles,
            initials
        };
};