From 6f51da97ae60000b26e18300363e1955cccdc9e1 Mon Sep 17 00:00:00 2001 From: m5r Date: Thu, 4 Apr 2024 16:23:42 +0200 Subject: [PATCH] reduce cognitive complexity --- api/src/controllers/users.js | 57 +++++++++++++----------- shared-libs/user-management/src/users.js | 2 +- 2 files changed, 31 insertions(+), 28 deletions(-) diff --git a/api/src/controllers/users.js b/api/src/controllers/users.js index 3c6d4720c0b..f702ab9348c 100644 --- a/api/src/controllers/users.js +++ b/api/src/controllers/users.js @@ -136,6 +136,35 @@ const convertUserListToV1 = (users=[]) => { return users; }; +const getUserByUsername = async (req, res) => { + try { + const username = req.params.username; + const credentials = auth.basicAuthCredentials(req); + const [hasPermission, isGettingSelf] = await Promise.all([ + hasPermissions(req, 'can_view_users'), + isUpdatingSelf(req, credentials, username), + ]).catch(error => { + if (error.statusCode === 401) { + throw { code: 401, message: 'Not logged in', err: error }; + } + + throw error; + }); + + if (!hasPermission && !isGettingSelf) { + throw { + message: 'You do not have permissions to fetch this person', + code: 403, + }; + } + + const body = await users.getUser(username); + res.json(body); + } catch (error) { + serverUtils.error(error, req, res); + } +}; + module.exports = { get: (req, res) => { return getUserList(req) @@ -239,33 +268,7 @@ module.exports = { v2: { get: async (req, res) => { if (req.params?.username) { - try { - const username = req.params.username; - const credentials = auth.basicAuthCredentials(req); - const [hasPermission, isGettingSelf] = await Promise.all([ - hasPermissions(req, 'can_view_users'), - isUpdatingSelf(req, credentials, username), - ]).catch(error => { - if (error.statusCode === 401) { - throw { code: 401, message: 'Not logged in', err: error }; - } - - throw error; - }); - - if (!hasPermission && !isGettingSelf) { - throw { - message: 'You do not have permissions to fetch this person', - code: 403, - }; - } - - const body = await users.getUser(username); - res.json(body); - } catch (error) { - serverUtils.error(error, req, res); - } - return; + return getUserByUsername(req, res); } try { diff --git a/shared-libs/user-management/src/users.js b/shared-libs/user-management/src/users.js index 5d3dbdd509c..b4af6477532 100644 --- a/shared-libs/user-management/src/users.js +++ b/shared-libs/user-management/src/users.js @@ -796,7 +796,7 @@ module.exports = { getUser: async (username) => { const [user, setting] = await getUserDocsByName(username); const facilities = await facility.list([user], [setting]); - return mapUsers([user], [setting], facilities); + return mapUsers([user], [setting], facilities)[0]; }, getList: async (filters) => { let users;