Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Update DeleteUser to remove roles first prior to full deletion #213

Open
wants to merge 4 commits into
base: dev
Choose a base branch
from
Open
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
14 changes: 8 additions & 6 deletions packages/api/src/components/AppContextProvider.ts
Original file line number Diff line number Diff line change
Expand Up @@ -32,7 +32,7 @@ import { InitiatePasswordResetInteractor } from '~interactors/InitiatePasswordRe
import { ResetUserPasswordInteractor } from '~interactors/ResetUserPasswordInteractor'
import { SetUserPasswordInteractor } from '~interactors/SetUserPasswordInteractor'
import { CreateNewUserInteractor } from '~interactors/CreateNewUserInteractor'
import { DeleteUserInteractor } from '~interactors/DeleteUserInteractor'
import { RemoveUserFromOrganizationInteractor } from '~interactors/RemoveUserFromOrganizationInteractor'
import { UpdateUserInteractor } from '~interactors/UpdateUserInteractor'
import { UpdateUserFCMTokenInteractor } from '~interactors/UpdateUserFCMTokenInteractor'
import { MarkMentionSeenInteractor } from '~interactors/MarkMentionSeenInteractor'
Expand Down Expand Up @@ -69,8 +69,7 @@ import {
InputEntityToOrgIdStrategy,
InputServiceAnswerEntityToOrgIdStrategy,
OrganizationSrcStrategy,
OrgIdArgStrategy,
UserWithinOrgStrategy
OrgIdArgStrategy
} from './orgAuthStrategies'

const logger = createLogger('app-context-provider')
Expand Down Expand Up @@ -112,8 +111,7 @@ export class AppContextProvider implements AsyncProvider<BuiltAppContext> {
new OrgIdArgStrategy(authenticator),
new EntityIdToOrgIdStrategy(authenticator),
new InputEntityToOrgIdStrategy(authenticator),
new InputServiceAnswerEntityToOrgIdStrategy(authenticator),
new UserWithinOrgStrategy(authenticator)
new InputServiceAnswerEntityToOrgIdStrategy(authenticator)
]

return {
Expand Down Expand Up @@ -214,7 +212,11 @@ export class AppContextProvider implements AsyncProvider<BuiltAppContext> {
),
setUserPassword: new SetUserPasswordInteractor(localization, userCollection),
createNewUser: new CreateNewUserInteractor(localization, mailer, userCollection, config),
deleteUser: new DeleteUserInteractor(localization, userCollection, engagementCollection),
removeUserFromOrganization: new RemoveUserFromOrganizationInteractor(
localization,
userCollection,
engagementCollection
),
updateUser: new UpdateUserInteractor(localization, userCollection),
updateUserFCMToken: new UpdateUserFCMTokenInteractor(localization, userCollection),
markMentionSeen: new MarkMentionSeenInteractor(localization, userCollection),
Expand Down
2 changes: 1 addition & 1 deletion packages/api/src/components/orgAuthStrategies.ts
Original file line number Diff line number Diff line change
Expand Up @@ -200,7 +200,7 @@ export class UserWithinOrgStrategy
if (user) {
const userOrgs = new Set<string>(user.roles.map((r) => r.org_id) ?? empty)
for (const orgId of userOrgs) {
// only admins can take actions on user entities in their org
// only admins can take actions on user entities in their org (e.g. resetPassword)
if (this.authenticator.isAuthorized(requestCtx.identity, orgId, RoleType.Admin)) {
return true
}
Expand Down
4 changes: 1 addition & 3 deletions packages/api/src/interactors/CreateNewUserInteractor.ts
Original file line number Diff line number Diff line change
Expand Up @@ -24,9 +24,7 @@ export class CreateNewUserInteractor
) {}

public async execute({ user }: MutationCreateNewUserArgs): Promise<UserResponse> {
const checkUser = await this.users.count({
email: user.email
})
const checkUser = await this.users.count({ email: user.email })

if (checkUser !== 0) {
return new FailedResponse(this.localization.t('mutation.createNewUser.emailExist'))
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -2,67 +2,69 @@
* Copyright (c) Microsoft. All rights reserved.
* Licensed under the MIT license. See LICENSE file in the project.
*/
import { MutationDeleteUserArgs, VoidResponse } from '@cbosuite/schema/dist/provider-types'
import {
MutationRemoveUserFromOrganizationArgs,
VoidResponse
} from '@cbosuite/schema/dist/provider-types'
import { Localization } from '~components'
import { EngagementCollection, UserCollection } from '~db'
import { Interactor, RequestContext } from '~types'
import { FailedResponse, SuccessVoidResponse } from '~utils/response'

export class DeleteUserInteractor implements Interactor<MutationDeleteUserArgs, VoidResponse> {
export class RemoveUserFromOrganizationInteractor
implements Interactor<MutationRemoveUserFromOrganizationArgs, VoidResponse>
{
public constructor(
private readonly localization: Localization,
private readonly users: UserCollection,
private readonly engagements: EngagementCollection
) {}

public async execute(
{ userId }: MutationDeleteUserArgs,
{ userId, orgId }: MutationRemoveUserFromOrganizationArgs,
{ identity }: RequestContext
): Promise<VoidResponse> {
// Delete user
try {
await this.users.deleteItem({ id: userId })
} catch (error) {
const { item: user } = await this.users.itemById(userId)
if (!user) {
return new FailedResponse(this.localization.t('mutation.deleteUser.fail'))
}

// Remove all engagements with user
// Remove org permissinos
const newRoles = user.roles.filter((r) => r.org_id !== orgId)
try {
if (newRoles.length === 0) {
await this.users.deleteItem({ id: userId })
} else {
await this.users.updateItem({ id: userId }, { $set: { roles: newRoles } })
}

// Remove all engagements with user
await this.engagements.deleteItems({ user_id: userId })
} catch (error) {
return new FailedResponse(this.localization.t('mutation.deleteUser.fail'))
}

// Remove all remaining engagement actions with user
try {
const remainingEngagementsOnOrg = await this.engagements.items(
{},
{ org_id: identity?.roles[0]?.org_id }
)
if (remainingEngagementsOnOrg.items) {
for (const engagement of remainingEngagementsOnOrg.items) {
// Remove all remaining engagement actions with user
const { items: remainingEngagements } = await this.engagements.items({}, { org_id: orgId })
if (remainingEngagements) {
for (const engagement of remainingEngagements) {
const newActions = []
let removedUser = false
let isUpdated = false

for (const action of engagement.actions) {
// If action was created by user, do not added it to the newActions list
if (action.user_id === userId) {
removedUser = true
isUpdated = true
continue
}

// If action tags the user, remove the tag
if (action.tagged_user_id === userId) {
action.tagged_user_id = undefined
removedUser = true
isUpdated = true
}

// Add the action back to the engagment actions
newActions.push(action)
}

// Only update the engagement actions if a user was removed
if (removedUser) {
if (isUpdated) {
await this.engagements.updateItem(
{ id: engagement.id },
{
Expand All @@ -78,6 +80,16 @@ export class DeleteUserInteractor implements Interactor<MutationDeleteUserArgs,
return new FailedResponse(this.localization.t('mutation.deleteUser.fail'))
}

try {
} catch (error) {
return new FailedResponse(this.localization.t('mutation.deleteUser.fail'))
Copy link
Collaborator Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Why did we decide to revert to using FailedResponse instead of using the Error responses that Apollo provides?

}

try {
} catch (error) {
return new FailedResponse(this.localization.t('mutation.deleteUser.fail'))
}

// Return success
return new SuccessVoidResponse(this.localization.t('mutation.deleteUser.success'))
}
Expand Down
7 changes: 5 additions & 2 deletions packages/api/src/resolvers/resolvers.ts
Original file line number Diff line number Diff line change
Expand Up @@ -87,8 +87,11 @@ export const resolvers: Resolvers<AppContext> & IResolvers<any, AppContext> = {
updateUser: async (_, args, { requestCtx, interactors: { updateUser } }) =>
updateUser.execute(args, requestCtx),

deleteUser: async (_, args, { requestCtx, interactors: { deleteUser } }) =>
deleteUser.execute(args, requestCtx),
removeUserFromOrganization: async (
_,
args,
{ requestCtx, interactors: { removeUserFromOrganization } }
) => removeUserFromOrganization.execute(args, requestCtx),

updateUserFCMToken: async (_, args, { requestCtx, interactors: { updateUserFCMToken } }) =>
updateUserFCMToken.execute(args, requestCtx),
Expand Down
4 changes: 2 additions & 2 deletions packages/api/src/types.ts
Original file line number Diff line number Diff line change
Expand Up @@ -23,7 +23,7 @@ import {
QueryServicesArgs,
QueryUserArgs,
MutationResetUserPasswordArgs,
MutationDeleteUserArgs,
MutationRemoveUserFromOrganizationArgs,
MutationArchiveContactArgs,
QueryContactArgs,
QueryContactsArgs,
Expand Down Expand Up @@ -139,7 +139,7 @@ export interface BuiltAppContext {
resetUserPassword: Interactor<MutationResetUserPasswordArgs, UserResponse>
setUserPassword: Interactor<MutationSetUserPasswordArgs, UserResponse>
createNewUser: Interactor<MutationCreateNewUserArgs, UserResponse>
deleteUser: Interactor<MutationDeleteUserArgs, VoidResponse>
removeUserFromOrganization: Interactor<MutationRemoveUserFromOrganizationArgs, VoidResponse>
updateUser: Interactor<MutationUpdateUserArgs, UserResponse>
updateUserFCMToken: Interactor<MutationUpdateUserFcmTokenArgs, VoidResponse>
markMentionSeen: Interactor<MutationMarkMentionSeenArgs, UserResponse>
Expand Down
3 changes: 2 additions & 1 deletion packages/schema/schema.gql
Original file line number Diff line number Diff line change
Expand Up @@ -113,7 +113,8 @@ type Mutation {
#
# Delete user
#
deleteUser(userId: String!): VoidResponse @orgAuth(requires: ADMIN)
removeUserFromOrganization(userId: String!, orgId: String!): VoidResponse
@orgAuth(requires: ADMIN)

#
# Update user FCM Token
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -110,7 +110,7 @@ export const EditSpecialistForm: StandardFC<EditSpecialistFormProps> = wrap(
}

const handleDeleteSpecialist = async (sid: string) => {
await deleteSpecialist(sid)
await deleteSpecialist(orgId, sid)
setShowModal(false)
closeForm()
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -7,7 +7,7 @@ import {
VoidResponse,
Organization,
StatusType,
MutationDeleteUserArgs
MutationRemoveUserFromOrganizationArgs
} from '@cbosuite/schema/dist/client-types'
import { MessageResponse } from '../types'
import { useToasts } from '~hooks/useToasts'
Expand All @@ -17,29 +17,29 @@ import { organizationState } from '~store'
import { useCallback } from 'react'

const DELETE_SPECIALIST = gql`
mutation deleteUser($userId: String!) {
deleteUser(userId: $userId) {
mutation removeUserFromOrganization($orgId: String!, $userId: String!) {
removeUserFromOrganization(orgId: $orgId, userId: $userId) {
message
status
}
}
`

export type DeleteSpecialistCallback = (userId: string) => Promise<MessageResponse>
export type DeleteSpecialistCallback = (orgId: string, userId: string) => Promise<MessageResponse>

export function useDeleteSpecialistCallback(): DeleteSpecialistCallback {
const { c } = useTranslation()
const { success, failure } = useToasts()
const [deleteUser] = useMutation<any, MutationDeleteUserArgs>(DELETE_SPECIALIST)
const [deleteUser] = useMutation<any, MutationRemoveUserFromOrganizationArgs>(DELETE_SPECIALIST)
const [organization, setOrg] = useRecoilState<Organization | null>(organizationState)

return useCallback(
async (userId) => {
async (orgId: string, userId: string) => {
const result: MessageResponse = { status: StatusType.Failed }

try {
await deleteUser({
variables: { userId },
variables: { userId, orgId },
update(cache, { data }) {
const updateUserResp = data.deleteUser as VoidResponse

Expand Down
Loading