-
Notifications
You must be signed in to change notification settings - Fork 335
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
feat: implement deleteUsers
mutation
#10498
Closed
Closed
Changes from all commits
Commits
Show all changes
9 commits
Select commit
Hold shift + click to select a range
f710b79
feat: implement mass user deletion
tianrunhe 6682778
Add check for number of users to delete at once
tianrunhe 81cfc07
Merge branch 'master' into feat/massUserDeletion
tianrunhe 9bf8587
Minor fixes
tianrunhe 0374609
Add domain ownership check
tianrunhe e039f51
Better error message
tianrunhe 6955d22
Fix unit test
tianrunhe baf5ba1
Modify success return type and fix unit tests
tianrunhe 5f3771c
Remove team level permission
tianrunhe File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,36 @@ | ||
import graphql from 'babel-plugin-relay/macro' | ||
import {commitMutation} from 'react-relay' | ||
import {DeleteUsersMutation as TDeleteUsersMutation} from '../__generated__/DeleteUsersMutation.graphql' | ||
import {StandardMutation} from '../types/relayMutations' | ||
|
||
graphql` | ||
fragment DeleteUsersMutation_users on DeleteUsersSuccess { | ||
deletedUsers { | ||
id | ||
isRemoved | ||
} | ||
} | ||
` | ||
|
||
const mutation = graphql` | ||
mutation DeleteUsersMutation($emails: [Email!]!) { | ||
deleteUsers(emails: $emails) { | ||
... on ErrorPayload { | ||
error { | ||
message | ||
} | ||
} | ||
...DeleteUsersMutation_users @relay(mask: false) | ||
} | ||
} | ||
` | ||
|
||
const DeleteUsersMutation: StandardMutation<TDeleteUsersMutation> = (atmosphere, variables) => { | ||
return commitMutation<TDeleteUsersMutation>(atmosphere, { | ||
mutation, | ||
variables | ||
}) | ||
} | ||
|
||
export default DeleteUsersMutation |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,63 @@ | ||
import {sendIntranet, signUp} from './common' | ||
|
||
test('Delete users by email', async () => { | ||
const user1 = await signUp() | ||
const user2 = await signUp() | ||
const emails = [user1.email, user2.email] | ||
const userIds = [user1.userId, user2.userId] | ||
|
||
const deleteUsers = await sendIntranet({ | ||
query: ` | ||
mutation DeleteUsers($emails: [Email!]!) { | ||
deleteUsers(emails: $emails) { | ||
... on ErrorPayload { | ||
error { | ||
message | ||
} | ||
} | ||
... on DeleteUsersSuccess { | ||
deletedUsers { | ||
id | ||
isRemoved | ||
} | ||
} | ||
} | ||
} | ||
`, | ||
variables: { | ||
emails | ||
} | ||
}) | ||
|
||
expect(deleteUsers.data.deleteUsers.deletedUsers).toHaveLength(2) | ||
|
||
// Verify both users were deleted | ||
for (const userId of userIds) { | ||
const user = await sendIntranet({ | ||
query: ` | ||
query User($userId: ID!) { | ||
user(userId: $userId) { | ||
id | ||
isRemoved | ||
} | ||
} | ||
`, | ||
variables: { | ||
userId | ||
}, | ||
isPrivate: true | ||
}) | ||
|
||
expect(user).toMatchObject({ | ||
data: { | ||
user: { | ||
id: userId, | ||
isRemoved: true, | ||
email: expect.not.stringMatching(emails[userIds.indexOf(userId)] || '') | ||
} | ||
} | ||
}) | ||
} | ||
}, 40000) |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
100 changes: 100 additions & 0 deletions
100
packages/server/graphql/public/mutations/deleteUsers.ts
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,100 @@ | ||
import {USER_BATCH_DELETE_LIMIT} from '../../../postgres/constants' | ||
import {getUsersByEmails} from '../../../postgres/queries/getUsersByEmails' | ||
import {getUserById} from '../../../postgres/queries/getUsersByIds' | ||
import { | ||
getUserId, | ||
isSuperUser, | ||
isUserBillingLeader, | ||
isUserOrgAdmin | ||
} from '../../../utils/authorization' | ||
import getDomainFromEmail from '../../../utils/getDomainFromEmail' | ||
import {GQLContext} from '../../graphql' | ||
import {markUserSoftDeleted} from '../../mutations/deleteUser' | ||
import softDeleteUser from '../../mutations/helpers/softDeleteUser' | ||
import {MutationResolvers} from '../resolverTypes' | ||
|
||
const deleteUsers: MutationResolvers['deleteUsers'] = async ( | ||
_source, | ||
{emails}: {emails: string[]}, | ||
{authToken, dataLoader}: GQLContext | ||
) => { | ||
if (emails.length === 0) { | ||
return {error: {message: 'No emails provided'}} | ||
} | ||
|
||
if (emails.length > USER_BATCH_DELETE_LIMIT) { | ||
return {error: {message: `Cannot delete more than ${USER_BATCH_DELETE_LIMIT} users at once`}} | ||
} | ||
|
||
const su = isSuperUser(authToken) | ||
const viewerId = getUserId(authToken) | ||
const viewer = await getUserById(viewerId) | ||
if (!viewer) return {error: {message: 'Invalid viewer'}} | ||
|
||
const usersToDelete = await getUsersByEmails(emails) | ||
if (usersToDelete.length === 0) { | ||
return {error: {message: 'No valid users found to delete'}} | ||
} else if (usersToDelete.length !== emails.length) { | ||
const missingEmails = emails.filter( | ||
(email) => !usersToDelete.some((user) => user.email === email) | ||
) | ||
return {error: {message: `Some users were not found: ${missingEmails.join(', ')}`}} | ||
} | ||
|
||
// First check all permissions before making any changes | ||
const viewerOrgUsers = await dataLoader.get('organizationUsersByUserId').load(viewerId) | ||
const permissionChecks = await Promise.all( | ||
usersToDelete.map(async (userToDelete) => { | ||
// Super users can delete anyone | ||
if (su) return {userId: userToDelete.id, hasPermission: true} | ||
|
||
const orgUsers = await dataLoader.get('organizationUsersByUserId').load(userToDelete.id) | ||
|
||
// Check permissions for each org the user belongs to | ||
const hasOrgPermission = await Promise.all( | ||
orgUsers.map(async ({orgId}) => { | ||
const viewerOrgUser = viewerOrgUsers.find((vu) => vu.orgId === orgId) | ||
if (!viewerOrgUser) return false | ||
|
||
const [isOrgAdmin, isBillingLeader] = await Promise.all([ | ||
isUserOrgAdmin(viewerId, orgId, dataLoader), | ||
isUserBillingLeader(viewerId, orgId, dataLoader) | ||
]) | ||
|
||
if (!(isOrgAdmin || isBillingLeader)) return false | ||
|
||
const organization = await dataLoader.get('organizations').loadNonNull(orgId) | ||
return organization.activeDomain === getDomainFromEmail(userToDelete.email) | ||
}) | ||
) | ||
|
||
return { | ||
userId: userToDelete.id, | ||
hasPermission: hasOrgPermission.some(Boolean) | ||
} | ||
}) | ||
) | ||
|
||
// Check if we have permission to delete ALL users | ||
const unauthorizedUsers = usersToDelete.filter((_, idx) => !permissionChecks[idx]!.hasPermission) | ||
if (unauthorizedUsers.length > 0) { | ||
return { | ||
error: { | ||
message: `You don't have permission to remove the following users: ${unauthorizedUsers.map((user) => user.email).join(', ')}` | ||
} | ||
} | ||
} | ||
|
||
// If we have permission for all users, perform the deletions | ||
const deletedUserIds = await Promise.all( | ||
permissionChecks.map(async ({userId}) => { | ||
const deletedUserEmail = await softDeleteUser(userId, dataLoader) | ||
await markUserSoftDeleted(userId, deletedUserEmail, 'Mass user deletion') | ||
return userId | ||
}) | ||
) | ||
|
||
return {deletedUserIds} | ||
} | ||
|
||
export default deleteUsers |
1 change: 1 addition & 0 deletions
1
packages/server/graphql/public/typeDefs/DeleteUsersPayload.graphql
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1 @@ | ||
union DeleteUsersPayload = ErrorPayload | DeleteUsersSuccess |
11 changes: 11 additions & 0 deletions
11
packages/server/graphql/public/typeDefs/DeleteUsersSuccess.graphql
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,11 @@ | ||
type DeleteUsersSuccess { | ||
""" | ||
the ids of the deleted users | ||
""" | ||
deletedUserIds: [ID!] | ||
|
||
""" | ||
the deleted users | ||
""" | ||
deletedUsers: [User!] | ||
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
15 changes: 15 additions & 0 deletions
15
packages/server/graphql/public/types/DeleteUsersSuccess.ts
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,15 @@ | ||
import isValid from '../../isValid' | ||
import {DeleteUsersSuccessResolvers} from '../resolverTypes' | ||
|
||
export type DeleteUsersSuccessSource = { | ||
deletedUserIds: string[] | ||
} | ||
|
||
const DeleteUsersSuccess: DeleteUsersSuccessResolvers = { | ||
deletedUsers: async ({deletedUserIds}, _args, {dataLoader}) => { | ||
const users = (await dataLoader.get('users').loadMany(deletedUserIds)).filter(isValid) | ||
return users | ||
} | ||
} | ||
|
||
export default DeleteUsersSuccess |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Oops, something went wrong.
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
-1 This is not enough for owning a domain. We can only allow to delete users fully for organizations with verified domains. This usually means just enterprise orgs with SAML, but we can manually verify domains for them without them using SAML.