2022-10-04 02:17:53 +02:00
|
|
|
import { ok, unauthorized, methodNotAllowed, badRequest, hashPassword } from 'next-basics';
|
2020-08-12 07:24:41 +02:00
|
|
|
import { useAuth } from 'lib/middleware';
|
2022-10-04 02:17:53 +02:00
|
|
|
import { uuid } from 'lib/crypto';
|
2022-11-01 07:42:37 +01:00
|
|
|
import { createUser, getUser, getUsers } from 'queries';
|
2020-08-12 07:24:41 +02:00
|
|
|
|
|
|
|
export default async (req, res) => {
|
|
|
|
await useAuth(req, res);
|
|
|
|
|
2022-11-09 19:15:21 +01:00
|
|
|
const { isAdmin } = req.auth.user;
|
2020-08-12 07:24:41 +02:00
|
|
|
|
2022-10-10 22:42:18 +02:00
|
|
|
if (!isAdmin) {
|
2020-09-16 22:13:50 +02:00
|
|
|
return unauthorized(res);
|
|
|
|
}
|
2020-08-12 07:24:41 +02:00
|
|
|
|
2020-09-16 22:13:50 +02:00
|
|
|
if (req.method === 'GET') {
|
2022-11-01 07:42:37 +01:00
|
|
|
const users = await getUsers();
|
2020-08-12 07:24:41 +02:00
|
|
|
|
2022-11-01 07:42:37 +01:00
|
|
|
return ok(res, users);
|
2020-08-12 07:24:41 +02:00
|
|
|
}
|
|
|
|
|
2022-10-04 02:17:53 +02:00
|
|
|
if (req.method === 'POST') {
|
2022-11-09 19:59:03 +01:00
|
|
|
const { username, password, id } = req.body;
|
2022-10-04 02:17:53 +02:00
|
|
|
|
2022-11-01 07:42:37 +01:00
|
|
|
const user = await getUser({ username });
|
2022-10-04 02:17:53 +02:00
|
|
|
|
2022-11-01 07:42:37 +01:00
|
|
|
if (user) {
|
|
|
|
return badRequest(res, 'User already exists');
|
2022-10-04 02:17:53 +02:00
|
|
|
}
|
|
|
|
|
2022-11-01 07:42:37 +01:00
|
|
|
const created = await createUser({
|
2022-11-09 19:59:03 +01:00
|
|
|
id: id || uuid(),
|
2022-10-04 02:17:53 +02:00
|
|
|
username,
|
|
|
|
password: hashPassword(password),
|
|
|
|
});
|
|
|
|
|
|
|
|
return ok(res, created);
|
|
|
|
}
|
|
|
|
|
2020-08-12 07:24:41 +02:00
|
|
|
return methodNotAllowed(res);
|
|
|
|
};
|