diff --git a/modules/account/back/models/specs/samba-config.spec.js b/modules/account/back/models/specs/samba-config.spec.js index 732c86c34..a1d780a6c 100644 --- a/modules/account/back/models/specs/samba-config.spec.js +++ b/modules/account/back/models/specs/samba-config.spec.js @@ -1,277 +1,6 @@ -// const execFile = require('child_process').execFile; -const app = require('vn-loopback/server/server'); -const SAMBA_TOOL = 'samba-tool'; + xdescribe('Samba config', () => { it('SyncRoles', async() => { - await syncRoles(); + }); }); -async function sambaTool(command, args = []) { - // const allArgs = [command].concat( - // args - // ); - switch (command) { - case 'user': - if (args[0] === 'list') - return ['user1', 'user2']; - break; - case 'group': - if (args[0] === 'list') - return ['employee', 'customer', 'agency', 'group1']; - else if (['listmembers'].includes(args[0])) { - return new Promise(resolve => { - resolve(['user1']); - }); - } else if (['delete', 'add'].includes(args[0])) { - return new Promise(resolve => { - resolve(`${SAMBA_TOOL} ${command} ${args[0]} ${args[1]}`); - }); - } else if (['addmembers', 'removemembers'].includes(args[0])) { - return new Promise(resolve => { - resolve(`${SAMBA_TOOL} ${command} ${args[0]} ${args[1]} ${args[2]}`); - }); - } else if (args[0] === 'modify') { - return new Promise(resolve => { - // samba-tool group modify group_name --description description - resolve(`${SAMBA_TOOL} ${command} ${args[0]} ${args[1]} ${args[2]} ${args[3]}`); - }); - } - break; - - default: - break; - } -} -async function syncRoles() { - let $ = app.models; - // let { - // client, - // accountConfig - // } = this; - - // Prepare data - try { - // OBTENER ROLES - let roles = (await $.VnRole.find({ - fields: ['id', 'name', 'description'], - limit: 5 - })); - let rolesMap = roles.map(role => role.name); - expect(rolesMap.length).toEqual(5); - // OBTENER SAMBA ROLES - let sambaCurrentRoles = await sambaTool('group', ['list']); - expect(sambaCurrentRoles.length).toEqual(4); - - // Encontrar elementos para eliminados - const rolesToDelete = differences(sambaCurrentRoles, rolesMap); - // const rolesToDelete = sambaCurrentRoles.filter(item => !rolesMap.includes(item)); - expect(rolesToDelete.length).toEqual(1); - - // Encontrar elementos insertar - const rolesToInsert = differences(rolesMap, sambaCurrentRoles); - // const rolesToInsert = rolesMap.filter(item => !sambaCurrentRoles.includes(item)); - expect(rolesToInsert.length).toEqual(2); - - // Encontrar elementos actualizar - const rolesToUpdate = differences(rolesMap, [...rolesToDelete, ...rolesToInsert]); - // const rolesToInsert = rolesMap.filter(item => !sambaCurrentRoles.includes(item)); - expect(rolesToUpdate.length).toEqual(3); - - // OBTENER USUARIOS Y SUS ROLES - if ( - rolesToDelete.length > 0 || - rolesToInsert.length > 0 || - rolesToUpdate.length > 0) { - let users = await $.VnUser.find({ - include: { - relation: 'role', - scope: {fields: ['name'], - where: {'name': {nin: rolesToDelete}} - } - }, - fields: ['name', 'roleFk'], - // where: {'active': true} - }); - /* let accounts = await $.Account.find({ - fields: ['id'], - include: { - relation: 'user', - scope: { - include: { - relation: 'role', - scope: {fields: ['name'], - where: {'name': {inq: rolesToInsert}} - } - }, - fields: ['name', 'roleFk'], - where: {'active': true} - } - } - });*/ - let usersMap = toMap(users, user => { - let role = user.role(); - if (!role) { - console.info(`User ${user.name} has not valid role`); - return; - } - return {key: role.name, val: user.name}; - }); - usersMap.set('group1', ['employee']); - // console.log(usersMap); - // const sumOfLengths = [...usersMap.values()].reduce((accumulator, currentArray) => { - // return accumulator + currentArray.length; - // }, 0); - // console.assert(sumOfLengths === users.length+1); - /* toMap(accounts, e => { - let user = e.user(); - if (!user) return; - let role = user.role(); - if (!role) return; - return {key: role.name, val: user.name}; - });*/ - // for (const [key, value] of accountMap) { - // value.forEach(v => { - // console.log(v); - // }); - // console.log(`${key} = ${value}`); - // } - - if (rolesToDelete.length > 0) { - // PROCEDIMIENTO PARA ELIMINAR USUARIOS ASOCIADOS AL ROL - let usersToDelete = rolesToDelete.flatMap(role => { - const exist = usersMap.get(role); - - if (exist) { - return usersMap.get(role)?.map( - a => sambaTool('group', ['removemembers', role, a]) - ); - } else return []; - } - ); - const resultsUserDelete = await Promise.all(usersToDelete); - expect(resultsUserDelete.length).toEqual(1); - expect(resultsUserDelete[0]).toEqual('samba-tool group removemembers group1 employee'); - // PROCEDIMIENTO PARA ELIMINAR ROLES - const resultsRoleDelete = await Promise.all( - rolesToDelete.map(role => sambaTool('group', ['delete', role])) - ); - expect(resultsRoleDelete.length).toEqual(1); - expect(resultsRoleDelete[0]).toEqual('samba-tool group delete group1'); - } - - if (rolesToInsert.length > 0) { - // PROCEDIMIENTO PARA INSERTAR ROLES - const resultsRoleInsert = await Promise.all( - rolesToInsert.map(role => sambaTool('group', ['add', role])), - ); - expect(resultsRoleInsert.length).toEqual(2); - expect(resultsRoleInsert[0]).toEqual('samba-tool group add administrative'); - expect(resultsRoleInsert[1]).toEqual('samba-tool group add guest'); - const rolesToUpdate = await Promise.all( - rolesToInsert.map( - role => - sambaTool('group', - ['modify', role, '--description', `"${roles.find(r => r.name === role).description}"`] - ) - ) - ); - expect(rolesToUpdate.length).toEqual(2); - expect(rolesToUpdate[0]).toEqual('samba-tool group modify administrative --description "Tareas relacionadas con la contabilidad"'); - expect(rolesToUpdate[1]).toEqual('samba-tool group modify guest --description "Privilegios para usuarios sin cuenta"'); - - // PROCEDIMIENTO PARA AÑADIR DESCRIPCION AL ROLE - - let usersToInsert = rolesToInsert.flatMap(role => - usersMap.get(role).map( - a => sambaTool('group', ['addmembers', role, a]) - ) - ); - // PROCEDIMIENTO PARA INSERTAR USUARIOS ASOCIADOS AL ROL - const resultsUserInsert = await Promise.all(usersToInsert); - expect(resultsUserInsert.length).toEqual(2); - expect(resultsUserInsert[0]).toEqual('samba-tool group addmembers administrative administrative'); - expect(resultsUserInsert[1]).toEqual('samba-tool group addmembers guest guest'); - } - - if (rolesToUpdate.length > 0) { - let promises = []; - for await (const role of rolesToUpdate) { - const users = await sambaTool('group', ['listmembers', role]); - const usersToDelete = differences(users, usersMap.get(role)); - promises.push(usersToDelete.map(user => sambaTool('group', ['removemembers', role, user]))); - const usersToInsert = differences(usersMap.get(role), users); - promises.push(...usersToInsert.map(user => sambaTool('group', ['addmembers', role, user]))); - - const result = await Promise.all(promises); - console.log(result); - } - } - } - // let roleRoles = await $.RoleRole.find({ - // fields: ['role', 'inheritsFrom'] - // }); - // let roleMap = toMap(roleRoles, e => { - // return {key: e.inheritsFrom, val: e.role}; - // }); - - console.log('Elementos eliminados:', rolesToDelete); - console.log('Elementos para insertar:', rolesToInsert); - } catch (error) { - console.error(error); - } -} - -function toMap(array, fn) { - let map = new Map(); - for (let item of array) { - let keyVal = fn(item); - if (!keyVal) continue; - let key = keyVal.key; - if (!map.has(key)) map.set(key, []); - map.get(key).push(keyVal.val); - } - return map; -} -function binarySearch(array, value) { - let first = 0; - - let last = array.length - 1; - - while (first <= last) { - const index = Math.floor((first + last) / 2); - - const middle = array[index]; - - if (middle === value) - return index; // Elemento encontrado, devuelve la posición. - - if (middle < value) - first = index + 1; - else - last = index - 1; - } - - return -1; // Elemento no encontrado. -} - -function differences(array1, array2) { - const differences = []; - - // Ordena ambos arrays - - const sortedArray1 = array1.slice().sort(); - const sortedArray2 = array2.slice().sort(); - - for (const value of sortedArray1) { - // Busca el elemento en el array ordenado utilizando búsqueda binaria - - const result = binarySearch(sortedArray2, value); - - // Si el elemento no se encuentra, agrégalo a la lista de diferencias - - if (result === -1) - differences.push(value); - } - - return differences; -}