44 lines
1.6 KiB
TypeScript
44 lines
1.6 KiB
TypeScript
|
|
/**
|
|||
|
|
* Users Routes – Admin user management
|
|||
|
|
*/
|
|||
|
|
import type { FastifyInstance } from 'fastify';
|
|||
|
|
import type { DatabaseInterface, DBUser } from '../database/DatabaseInterface.js';
|
|||
|
|
import type { AuthService } from '../auth/AuthService.js';
|
|||
|
|
|
|||
|
|
export function registerUserRoutes(fastify: FastifyInstance, db: DatabaseInterface, authService: AuthService) {
|
|||
|
|
// List all users (admin only — TODO: add role check middleware)
|
|||
|
|
fastify.get('/api/users', async () => {
|
|||
|
|
const users = db.listUsers();
|
|||
|
|
return users.map(({ password_hash, ...safe }) => safe);
|
|||
|
|
});
|
|||
|
|
|
|||
|
|
// Get single user
|
|||
|
|
fastify.get('/api/users/:id', async (request, reply) => {
|
|||
|
|
const { id } = request.params as { id: string };
|
|||
|
|
const user = db.getUser(id);
|
|||
|
|
if (!user) return reply.code(404).send({ error: 'User not found' });
|
|||
|
|
const { password_hash, ...safe } = user;
|
|||
|
|
return safe;
|
|||
|
|
});
|
|||
|
|
|
|||
|
|
// Update user (name, role, email)
|
|||
|
|
fastify.patch('/api/users/:id', async (request, reply) => {
|
|||
|
|
const { id } = request.params as { id: string };
|
|||
|
|
const body = request.body as Partial<DBUser>;
|
|||
|
|
// Prevent password update via this endpoint
|
|||
|
|
delete body.password_hash;
|
|||
|
|
const updated = db.updateUser(id, body);
|
|||
|
|
if (!updated) return reply.code(404).send({ error: 'User not found' });
|
|||
|
|
const { password_hash, ...safe } = updated;
|
|||
|
|
return safe;
|
|||
|
|
});
|
|||
|
|
|
|||
|
|
// Delete user
|
|||
|
|
fastify.delete('/api/users/:id', async (request, reply) => {
|
|||
|
|
const { id } = request.params as { id: string };
|
|||
|
|
const ok = db.deleteUser(id);
|
|||
|
|
if (!ok) return reply.code(404).send({ error: 'User not found' });
|
|||
|
|
return reply.code(204).send();
|
|||
|
|
});
|
|||
|
|
}
|