diff options
| author | Pinapelz <yukais@pinapelz.com> | 2025-11-09 20:33:00 -0800 |
|---|---|---|
| committer | Pinapelz <yukais@pinapelz.com> | 2025-11-09 20:33:11 -0800 |
| commit | 9608610b0fef717c8f2d87ab518a077f4e0763cb (patch) | |
| tree | 8f07ba97fbf782634c1818676660a93a2ac1360d /backend/src/routes/admin.ts | |
| parent | f0e80463fa23a6a52623b7507d6959d19af6ae07 (diff) | |
admin: implement user deletion
Diffstat (limited to 'backend/src/routes/admin.ts')
| -rw-r--r-- | backend/src/routes/admin.ts | 60 |
1 files changed, 60 insertions, 0 deletions
diff --git a/backend/src/routes/admin.ts b/backend/src/routes/admin.ts index 63d6ccf..0fe35bd 100644 --- a/backend/src/routes/admin.ts +++ b/backend/src/routes/admin.ts @@ -48,3 +48,63 @@ export const handleCreateGame = async (req: express.Request, res: express.Respon res.status(500).json({ error: 'Internal server error' }); } } + +export const handleDeleteUser = async (req: express.Request, res: express.Response) => { + try { + if (!req.session.userId) { + return res.status(401).json({ error: 'Authentication required' }); + } + + const user = await prisma.user.findUnique({ + where: { id: req.session.userId }, + select: { id: true, username: true, isAdmin: true } + }); + + if (!user) { + req.session.destroy((err) => { + if (err) console.error('Session destroy error:', err); + }); + return res.status(401).json({ error: 'Invalid session' }); + } + + if (user.id !== 1 && !user.isAdmin) { + return res.status(403).json({ error: 'Unauthorized. You are not an admin of this instance' }); + } + + const { userId } = req.params; + if (!userId) { + return res.status(400).json({ error: 'User ID is required' }); + } + + const targetUserId = parseInt(userId); + if (isNaN(targetUserId) || targetUserId <= 0) { + return res.status(400).json({ error: 'Invalid user ID' }); + } + if (targetUserId === user.id) { + return res.status(400).json({ error: 'Cannot delete your own account' }); + } + const targetUser = await prisma.user.findUnique({ + where: { id: targetUserId }, + select: { id: true, username: true, isAdmin: true } + }); + + if (!targetUser) { + return res.status(404).json({ error: 'User not found' }); + } + await prisma.user.delete({ + where: { id: targetUserId } + }); + + return res.status(200).json({ + message: 'User deleted successfully', + deletedUser: { + id: targetUser.id, + username: targetUser.username + } + }); + + } catch (error) { + console.error('User deletion error:', error); + res.status(500).json({ error: 'Internal server error' }); + } +} |
