Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 1 addition & 1 deletion src/generics/constants/api-responses.js
Original file line number Diff line number Diff line change
Expand Up @@ -73,5 +73,5 @@ module.exports = {
KEYS_ALREADY_INDEXED_SUCCESSFULL: 'KEYS_ALREADY_INDEXED_SUCCESSFULL',
NOT_VALID_ID_AND_EXTERNALID: 'NOT_VALID_ID_AND_EXTERNALID',
TENANT_ID_MISSING_CODE: 'ERR_TENANT_ID_MISSING',
TENANT_ID_MISSING_MESSAGE: 'Require tenantId in body',
TENANT_ID_MISSING_MESSAGE: 'Require tenantId in header',
}
2 changes: 1 addition & 1 deletion src/generics/constants/common.js
Original file line number Diff line number Diff line change
Expand Up @@ -44,5 +44,5 @@ module.exports = {
ORG_ADMIN: 'org_admin',
TENANT_ADMIN: 'tenant_admin',
SERVER_TIME_OUT: 5000,
GUEST_URLS: ['/entities/details'],
GUEST_URLS: ['/entities/details', '/entities/entityListBasedOnEntityType', 'entities/subEntityList'],
}
111 changes: 97 additions & 14 deletions src/generics/middleware/authenticator.js
Original file line number Diff line number Diff line change
Expand Up @@ -58,14 +58,27 @@ module.exports = async function (req, res, next, token = '') {
})
)

if (guestAccess == true && !req.body['tenantId']) {
rspObj.errCode = CONSTANTS.apiResponses.TENANT_ID_MISSING_CODE
rspObj.errMsg = CONSTANTS.apiResponses.TENANT_ID_MISSING_MESSAGE
rspObj.responseCode = HTTP_STATUS_CODE['unauthorized'].status
return res.status(HTTP_STATUS_CODE['unauthorized'].status).send(respUtil(rspObj))
}
// if (guestAccess == true && !req.body['tenantId']) {
// rspObj.errCode = CONSTANTS.apiResponses.TENANT_ID_MISSING_CODE
// rspObj.errMsg = CONSTANTS.apiResponses.TENANT_ID_MISSING_MESSAGE
// rspObj.responseCode = HTTP_STATUS_CODE['unauthorized'].status
// return res.status(HTTP_STATUS_CODE['unauthorized'].status).send(respUtil(rspObj))
// }

if (guestAccess == true && !token) {
if (!req.headers['tenantid']) {
rspObj.errCode = CONSTANTS.apiResponses.TENANT_ID_MISSING_CODE
rspObj.errMsg = CONSTANTS.apiResponses.TENANT_ID_MISSING_MESSAGE
rspObj.responseCode = HTTP_STATUS_CODE['unauthorized'].status
return res.status(HTTP_STATUS_CODE['unauthorized'].status).send(respUtil(rspObj))
}
req.userDetails = {
userInformation: {
tenantId: req.headers['tenantid'],
organizationId: req.headers['orgid'] || null,
},
}

next()
return
}
Expand Down Expand Up @@ -97,7 +110,6 @@ module.exports = async function (req, res, next, token = '') {
return
}
}

if (!token) {
rspObj.errCode = CONSTANTS.apiResponses.TOKEN_MISSING_CODE
rspObj.errMsg = CONSTANTS.apiResponses.TOKEN_MISSING_MESSAGE
Expand Down Expand Up @@ -200,7 +212,7 @@ module.exports = async function (req, res, next, token = '') {
}

// Path to config.json
const configFilePath = path.resolve(__dirname, '../../../config.json')
const configFilePath = path.resolve(__dirname, '../../config.json')
// Initialize variables
let configData = {}
let defaultTokenExtraction = false
Expand All @@ -223,10 +235,13 @@ module.exports = async function (req, res, next, token = '') {
defaultTokenExtraction = true
}

let organizationKey = 'organization_id'

// Create user details to request
req.userDetails = {
userToken: token,
}

// performing default token data extraction
if (defaultTokenExtraction) {
if (!decodedToken.data.organization_ids || !decodedToken.data.tenant_id) {
Expand Down Expand Up @@ -255,16 +270,37 @@ module.exports = async function (req, res, next, token = '') {
tenantId: decodedToken.data.tenant_id.toString(),
}
} else {
// Iterate through each key in the config object
for (let key in configData) {
let stringTypeKeys = ['userId', 'tenantId', 'organizationId']
if (configData.hasOwnProperty(key)) {
let keyValue = getNestedValue(decodedToken, configData[key])
if (stringTypeKeys.includes(key)) {
keyValue = keyValue.toString()
if (key == 'userId') {
keyValue = keyValue?.toString()
}
if (key === organizationKey) {
let value = getOrgId(req.headers, decodedToken, configData[key])
userInformation[`organizationId`] = value.toString()
decodedToken.data[key] = value
continue
}
if (key === 'roles') {
let orgId = getOrgId(req.headers, decodedToken, configData[organizationKey])
// Now extract roles using fully dynamic path
const rolePathTemplate = configData['roles']
decodedToken.data[organizationKey] = orgId
const resolvedRolePath = resolvePathTemplate(rolePathTemplate, decodedToken.data)
const roles = getNestedValue(decodedToken, resolvedRolePath) || []
userInformation[`${key}`] = roles
decodedToken.data[key] = roles
continue
}

// For each key in config, assign the corresponding value from decodedToken
userInformation[`${key}`] = keyValue
decodedToken.data[key] = keyValue
if (key == 'tenant_id') {
userInformation[`tenantId`] = keyValue.toString()
} else {
userInformation[`${key}`] = keyValue
}
}
}
if (userInformation.roles && Array.isArray(userInformation.roles) && userInformation.roles.length) {
Expand Down Expand Up @@ -495,9 +531,56 @@ module.exports = async function (req, res, next, token = '') {
if (decodedToken.data.tenantAndOrgInfo) {
req.userDetails.tenantAndOrgInfo = decodedToken.data.tenantAndOrgInfo
}

// Helper function to access nested properties
function getOrgId(headers, decodedToken, orgConfigData) {
if (headers['organization_id']) {
return (orgId = headers['organization_id'].toString())
} else {
const orgIdPath = orgConfigData
return (orgId = getNestedValue(decodedToken, orgIdPath)?.toString())
}
}

function getNestedValue(obj, path) {
return path.split('.').reduce((acc, part) => acc && acc[part], obj)
const parts = path.split('.')
let current = obj

for (const part of parts) {
if (!current) return undefined

// Conditional match: key[?field=value]
const conditionalMatch = part.match(/^(\w+)\[\?(\w+)=([^\]]+)\]$/)
if (conditionalMatch) {
const [, arrayKey, field, expected] = conditionalMatch
const array = current[arrayKey]
if (!Array.isArray(array)) return undefined
const found = array.find((item) => String(item[field]) === String(expected))
if (!found) return undefined
current = found
continue
}

// Index match: key[0]
const indexMatch = part.match(/^(\w+)\[(\d+)\]$/)
if (indexMatch) {
const [, key, index] = indexMatch
const array = current[key]
if (!Array.isArray(array)) return undefined
current = array[parseInt(index, 10)]
continue
}

current = current[part]
}
return current
}

function resolvePathTemplate(template, contextObject) {
return template.replace(/\{\{(.*?)\}\}/g, (_, path) => {
const value = getNestedValue(contextObject, path.trim())
return value?.toString?.() ?? ''
})
}
next()
}
108 changes: 54 additions & 54 deletions src/module/entities/helper.js
Original file line number Diff line number Diff line change
Expand Up @@ -252,60 +252,60 @@ module.exports = class UserProjectsHelper {
}

// Modify data properties (e.g., 'label') of retrieved entities if necessary
if (result.data && result.data.length > 0) {
// fetch the entity ids to look for parent hierarchy
const entityIds = _.map(result.data, (item) => ObjectId(item._id))
// dynamically set the entityType to search inside the group
const key = ['groups', type]
// create filter for fetching the parent data using group
let entityFilter = {}
entityFilter[key.join('.')] = {
$in: entityIds,
}

entityFilter['tenantId'] = tenantId

// Retrieve all the entity documents with the entity ids in their gropu
const entityDocuments = await entitiesQueries.entityDocuments(entityFilter, [
'entityType',
'metaInformation.name',
'childHierarchyPath',
key.join('.'),
])
// find out the state of the passed entityId
const stateEntity = entityDocuments.find((entity) => entity.entityType == 'state')
// fetch the child hierarchy path of the state
const stateChildHierarchy = stateEntity.childHierarchyPath
let upperLevelsOfType = type != 'state' ? ['state'] : [] // add state as default if type != state
// fetch all the upper levels of the type from state hierarchy
upperLevelsOfType = [
...upperLevelsOfType,
...stateChildHierarchy.slice(0, stateChildHierarchy.indexOf(type)),
]
result.data = result.data.map((data) => {
let cloneData = { ...data }
cloneData[cloneData.entityType] = cloneData.name
// if we have upper levels to fetch
if (upperLevelsOfType.length > 0) {
// iterate through the data fetched to fetch the parent entity names
entityDocuments.forEach((eachEntity) => {
eachEntity[key[0]][key[1]].forEach((eachEntityGroup) => {
if (
ObjectId(eachEntityGroup).equals(cloneData._id) &&
upperLevelsOfType.includes(eachEntity.entityType)
) {
if (eachEntity?.entityType !== 'state') {
cloneData[eachEntity?.entityType] = eachEntity?.metaInformation?.name
}
}
})
})
}
cloneData['label'] = cloneData.name
cloneData['value'] = cloneData._id
return cloneData
})
}
// if (result.data && result.data.length > 0) {
// // fetch the entity ids to look for parent hierarchy
// const entityIds = _.map(result.data, (item) => ObjectId(item._id))
// // dynamically set the entityType to search inside the group
// const key = ['groups', type]
// // create filter for fetching the parent data using group
// let entityFilter = {}
// entityFilter[key.join('.')] = {
// $in: entityIds,
// }

// entityFilter['tenantId'] = tenantId

// // Retrieve all the entity documents with the entity ids in their gropu
// const entityDocuments = await entitiesQueries.entityDocuments(entityFilter, [
// 'entityType',
// 'metaInformation.name',
// 'childHierarchyPath',
// key.join('.'),
// ])
// // find out the state of the passed entityId
// const stateEntity = entityDocuments.find((entity) => entity.entityType == 'state')
// // fetch the child hierarchy path of the state
// const stateChildHierarchy = stateEntity.childHierarchyPath
// let upperLevelsOfType = type != 'state' ? ['state'] : [] // add state as default if type != state
// // fetch all the upper levels of the type from state hierarchy
// upperLevelsOfType = [
// ...upperLevelsOfType,
// ...stateChildHierarchy.slice(0, stateChildHierarchy.indexOf(type)),
// ]
// result.data = result.data.map((data) => {
// let cloneData = { ...data }
// cloneData[cloneData.entityType] = cloneData.name
// // if we have upper levels to fetch
// if (upperLevelsOfType.length > 0) {
// // iterate through the data fetched to fetch the parent entity names
// entityDocuments.forEach((eachEntity) => {
// eachEntity[key[0]][key[1]].forEach((eachEntityGroup) => {
// if (
// ObjectId(eachEntityGroup).equals(cloneData._id) &&
// upperLevelsOfType.includes(eachEntity.entityType)
// ) {
// if (eachEntity?.entityType !== 'state') {
// cloneData[eachEntity?.entityType] = eachEntity?.metaInformation?.name
// }
// }
// })
// })
// }
// cloneData['label'] = cloneData.name
// cloneData['value'] = cloneData._id
// return cloneData
// })
// }

resolve({
message: CONSTANTS.apiResponses.ENTITIES_FETCHED,
Expand Down