const asyncHandler = require('express-async-handler'); const AuthTokens = require('../../authtokens'); module.exports = (repository, router) => { router.get('/users', asyncHandler(async (req, res) => { if (!req.user.hasAuth(AuthTokens.ManageUsers)) { res.sendStatus(403); return; } var users = await repository.users.list(); res.send(users); })); router.get('/users/:id', asyncHandler(async (req, res) => { if (req.params.id !== req.user.id && !req.user.hasAuth(AuthTokens.ManageUsers)) { res.sendStatus(404); return; } var user = await repository.users.get(req.params.id); if (user === null) { res.sendStatus(404); return; } res.send(user); })); router.post('/users', asyncHandler(async (req, res) => { var postedUser = req.body; if (postedUser.id) { if (postedUser.id !== req.user.id && !req.user.hasAuth(AuthTokens.ManageUsers)) { res.sendStatus(403); return; } await repository.users.update({ id: postedUser.id, username: postedUser.username, name: postedUser.name, password: postedUser.password, email: postedUser.email, auth: postedUser.auth, active: postedUser.active }); res.sendStatus(200); } else { if (!req.user.hasAuth(AuthTokens.ManageUsers)) { res.sendStatus(403); return; } var userId = await repository.users.insert({ username: postedUser.username, name: postedUser.name, password: postedUser.password, email: postedUser.email, auth: postedUser.auth, active: postedUser.active, createdByUserId: postedUser.createdByUserId }); } res.send(userId); })); router.delete('/users/:id', asyncHandler(async (req, res) => { if (!req.user.hasAuth(AuthTokens.ManageUsers)) { res.sendStatus(403); return; } repository.users.delete(req.params.id); res.sendStatus(200); })); }