Skip to content
Merged
35 changes: 35 additions & 0 deletions src/database/queries/users.js
Original file line number Diff line number Diff line change
Expand Up @@ -234,3 +234,38 @@ exports.listUsersFromView = async (roleId, organization_id, page, limit, search,
throw error
}
}

exports.changeOrganization = async (id, currentOrgId, newOrgId, updateBody = {}) => {
const transaction = await Sequelize.transaction()
try {
const existingUserRow = await database.User.findOne({
where: { id, organization_id: currentOrgId },
raw: true,
transaction,
})

if (!existingUserRow) throw new Error('User not found')

await database.User.destroy({
where: { id, organization_id: currentOrgId },
force: true,
transaction,
})

const newUserRow = await database.User.create(
{
...existingUserRow,
...updateBody,
organization_id: newOrgId,
id,
},
{ transaction }
)

await transaction.commit()
return newUserRow
} catch (error) {
await transaction.rollback()
throw error
}
}
2 changes: 2 additions & 0 deletions src/middlewares/authenticator.js
Original file line number Diff line number Diff line change
Expand Up @@ -22,6 +22,8 @@ module.exports = async function (req, res, next) {

common.internalAccessUrls.map(function (path) {
if (req.path.includes(path)) {
console.log('REQUEST PATH: ', req.path)
console.log('INTERNAL ACCESS PATH: ', path)
if (
req.headers.internal_access_token &&
process.env.INTERNAL_ACCESS_TOKEN == req.headers.internal_access_token
Expand Down
26 changes: 18 additions & 8 deletions src/services/admin.js
Original file line number Diff line number Diff line change
Expand Up @@ -229,6 +229,7 @@ module.exports = class AdminHelper {
responseCode: 'CLIENT_ERROR',
})
}

const user = await userQueries.findOne({
id: userCredentials.user_id,
organization_id: userCredentials.organization_id,
Expand All @@ -240,7 +241,7 @@ module.exports = class AdminHelper {
responseCode: 'CLIENT_ERROR',
})
}
userId = user.id
userId = user.id //un-necessary

let organization = await organizationQueries.findByPk(organizationId)
if (!organization?.id) {
Expand All @@ -260,6 +261,9 @@ module.exports = class AdminHelper {
})
}

// Create a unique array of organization administrators (orgAdmins) by combining the existing
// organization admins (organization.org_admin) with the userId. The lodash uniq function ensures
// that the resulting array contains only unique values.
const orgAdmins = _.uniq([...(organization.org_admin || []), userId])

const orgRowsAffected = await organizationQueries.update(
Expand Down Expand Up @@ -288,10 +292,6 @@ module.exports = class AdminHelper {

const roles = _.uniq([...(user.roles || []), role.id])

let updateObj = {
roles,
}

if (userOrg.code != process.env.DEFAULT_ORGANISATION_CODE && userOrg.id != organizationId) {
return common.failureResponse({
message: 'FAILED_TO_ASSIGN_AS_ADMIN',
Expand All @@ -300,9 +300,19 @@ module.exports = class AdminHelper {
})
}

updateObj.organization_id = organizationId
//update organization
if (userOrg.id != organizationId) {
await userQueries.changeOrganization(userId, userOrg.id, organizationId, {
//organization_id: organizationId,
roles: roles,
})
} else {
await userQueries.updateUser(
{ id: userId, organization_id: userCredentials.organization_id },
{ roles: roles }
)
}

await userQueries.updateUser({ id: userId, organization_id: userCredentials.organization_id }, updateObj)
await UserCredentialQueries.updateUser(
{
email: userCredentials.email,
Expand All @@ -322,7 +332,7 @@ module.exports = class AdminHelper {
}
)

//update organization in mentoring
// update organization in mentoring
eventBroadcaster('updateOrganization', {
requestBody: {
user_id: userId,
Expand Down
1 change: 1 addition & 0 deletions src/services/organization.js
Original file line number Diff line number Diff line change
Expand Up @@ -99,6 +99,7 @@ module.exports = class OrganizationsHelper {
role: common.ORG_ADMIN_ROLE,
orgName: bodyData.name,
appName: process.env.APP_NAME,
portalURL: process.env.PORTAL_URL,
}),
},
}
Expand Down
33 changes: 19 additions & 14 deletions src/services/userInvite.js
Original file line number Diff line number Diff line change
Expand Up @@ -155,10 +155,7 @@ module.exports = class UserInviteHelper {
static async createUserInvites(csvData, user, fileUploadId) {
try {
const outputFileName = utils.generateFileName(common.inviteeOutputFile, common.csvExtension)

// get the role data from db
const allRoles = _.uniq(_.map(csvData, 'roles').map((role) => role.toLowerCase()))

const roleList = await roleQueries.findAll({ title: allRoles })
const roleTitlesToIds = {}
roleList.forEach((role) => {
Expand All @@ -167,22 +164,19 @@ module.exports = class UserInviteHelper {

//get all existing user
const emailArray = _.uniq(_.map(csvData, 'email'))

const userCredentials = await UserCredentialQueries.findAll(
{ email: { [Op.in]: emailArray } },
{
attributes: ['user_id'],
}
)
const userIds = _.map(userCredentials, 'user_id')

const existingUsers = await userQueries.findAll(
{ id: userIds },
{
attributes: ['id', 'email', 'organization_id', 'roles'],
}
)

const existingEmailsMap = new Map(existingUsers.map((eachUser) => [eachUser.email, eachUser]))

//find default org id
Expand All @@ -191,6 +185,7 @@ module.exports = class UserInviteHelper {

let input = []
let isErrorOccured = false
let isOrgUpdate = false

//fetch email template
const mentorTemplateCode = process.env.MENTOR_INVITATION_EMAIL_TEMPLATE_CODE || null
Expand Down Expand Up @@ -237,6 +232,7 @@ module.exports = class UserInviteHelper {

//update user details if the user exist and in default org
const existingUser = existingEmailsMap.get(invitee.email)

if (existingUser) {
invitee.statusOrUserId = 'USER_ALREADY_EXISTS'
isErrorOccured = true
Expand All @@ -246,8 +242,17 @@ module.exports = class UserInviteHelper {
existingUser.organization_id === user.organization_id
if (isOrganizationMatch) {
let userUpdateData = {}

if (existingUser.organization_id != user.organization_id) {
userUpdateData.organization_id = user.organization_id
await userQueries.changeOrganization(
existingUser.id,
existingUser.organization_id,
user.organization_id,
{
organization_id: user.organization_id,
}
)
isOrgUpdate = true
userUpdateData.refresh_tokens = []
}
const areAllElementsInArray = _.every(roleTitlesToIds[invitee.roles], (element) =>
Expand All @@ -258,26 +263,26 @@ module.exports = class UserInviteHelper {
userUpdateData.refresh_tokens = []
}

if (userUpdateData.organization_id || userUpdateData.roles) {
if (isOrgUpdate || userUpdateData.roles) {
const userCredentials = await UserCredentialQueries.findOne({
email: invitee.email.toLowerCase(),
email: invitee.email,
})

await userQueries.updateUser({ id: userCredentials.user_id }, userUpdateData)

await UserCredentialQueries.updateUser(
{
email: invitee.email.toLowerCase(),
email: invitee.email,
},
{ organization_id: userUpdateData.organization_id }
{ organization_id: user.organization_id }
)

const userRoles = await roleQueries.findAll({ id: existingUser.roles })
//call event to update in mentoring
if (!userUpdateData?.roles) {
eventBroadcaster('updateOrganization', {
requestBody: {
user_id: existingUser.id,
organization_id: existingUser.organization_id,
organization_id: user.organization_id,
roles: _.map(userRoles, 'title'),
},
})
Expand All @@ -287,7 +292,7 @@ module.exports = class UserInviteHelper {
new_roles: [invitee.roles],
current_roles: _.map(userRoles, 'title'),
}
if (userUpdateData.organization_id) requestBody.organization_id = user.organization_id
if (isOrgUpdate) requestBody.organization_id = user.organization_id
eventBroadcaster('roleChange', {
requestBody,
})
Expand Down