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
9 changes: 9 additions & 0 deletions api/v1/controllers/users.mjs
Original file line number Diff line number Diff line change
Expand Up @@ -363,6 +363,15 @@ export async function remove (req, res, next) {
return
}

// Check there is no API key associated with the user
const apiKey = await DB.apikeys.findFirst({
where: { userid }
})
if (apiKey) {
res.status(R.UNPROCESSABLE_ENTITY).send(R.ko('User has associated API keys'))
return
}

// Delete user
await DB.$transaction(async (tx) => {
// Delete user groups
Expand Down
49 changes: 48 additions & 1 deletion test/users.spec.cjs
Original file line number Diff line number Diff line change
Expand Up @@ -40,7 +40,7 @@ describe('Users', function () {
assert.strictEqual(res1.status, 400)
})

it('Delete unexistent user', async () => {
it('Delete nonexistent user', async () => {
const res1 = await agent
.delete(`${global.host}/api/v1/users/000`)
.set('Authorization', `Bearer ${global.adminJWT}`)
Expand All @@ -49,6 +49,53 @@ describe('Users', function () {
assert.strictEqual(res1.status, 404)
})

it('Delete user, API key exists', async () => {
const data = { ...global.userCreateDataApiKey }
const rnd = global.rnd()
data.login = `${data.login}_${rnd}`

// Create user
const res1 = await agent
.post(`${global.host}/api/v1/users`)
.set('Authorization', `Bearer ${global.adminJWT}`)
.send(data)
.catch(v => v)

assert.strictEqual(res1.status, 201)

// Create API key
const res2 = await agent
.post(`${global.host}/api/v1/apikeys`)
.set('Authorization', `Bearer ${global.adminJWT}`)
.send({ description: 'test api key', userid: res1.body.data.id, expiresat: '2050-01-01', active: true })
.catch(v => v)

assert.strictEqual(res2.status, 201)

// Try to delete user
const res3 = await agent
.delete(`${global.host}/api/v1/users/${res1.body.data.id}`)
.set('Authorization', `Bearer ${global.adminJWT}`)
.catch(v => v)

assert.strictEqual(res3.status, 422)

// Cleanup API key and user
const res4 = await agent
.delete(`${global.host}/api/v1/apikeys/${res2.body.data.id}`)
.set('Authorization', `Bearer ${global.adminJWT}`)
.catch(v => v)

assert.strictEqual(res4.status, 200)

const res5 = await agent
.delete(`${global.host}/api/v1/users/${res1.body.data.id}`)
.set('Authorization', `Bearer ${global.adminJWT}`)
.catch(v => v)

assert.strictEqual(res5.status, 200)
})

it('Delete user', async () => {
const data = { ...global.userCreateData }
const rnd = global.rnd()
Expand Down