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

Fix deadlock 2: the bug knight returns #1795

Merged
merged 1 commit into from
Nov 4, 2024
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
20 changes: 20 additions & 0 deletions __tests__/schema/user/add-role.ts
Original file line number Diff line number Diff line change
Expand Up @@ -127,6 +127,26 @@ test('updates the cache', async () => {
})
})

test('Is successful even when user has already role', async () => {
await uuidQuery.shouldReturnData({
uuid: {
roles: {
nodes: [{ role: Role.Login, scope: Scope.Serlo }],
},
},
})
await mutation
.withInput({ username: regularUser.username, role: Role.Login })
.execute()
await uuidQuery.shouldReturnData({
uuid: {
roles: {
nodes: [{ role: Role.Login, scope: Scope.Serlo }],
},
},
})
})

test('fails when user is not authenticated', async () => {
await mutation.forUnauthenticatedUser().shouldFailWithError('UNAUTHENTICATED')
})
Expand Down
23 changes: 16 additions & 7 deletions packages/server/src/schema/uuid/user/resolvers.ts
Original file line number Diff line number Diff line change
Expand Up @@ -321,20 +321,29 @@ export const resolvers: Resolvers = {
throw new UserInputError('no user with given username')
}

const userHasAlreadyRole = await database.fetchOptional(
`
SELECT 1
FROM role_user
WHERE user_id = ?
AND role_id = ( SELECT id
FROM role
WHERE name = ?)`,
[id, generateRole(role, instance)],
)

if (userHasAlreadyRole) {
return { success: true, query: {} }
}

await database.mutate(
`
INSERT INTO role_user (user_id, role_id)
SELECT ?, role.id
FROM role
WHERE role.name = ?
AND NOT EXISTS (
SELECT 1
FROM role_user
WHERE role_user.user_id = ?
AND role_user.role_id = role.id
)
`,
[id, generateRole(role, instance), id],
[id, generateRole(role, instance)],
)

await UuidResolver.removeCacheEntry({ id }, context)
Expand Down