2022-12-28 00:18:58 +01:00
|
|
|
import { canCreateUser, canViewUsers } from 'lib/auth';
|
|
|
|
import { ROLES } from 'lib/constants';
|
2022-11-20 09:48:13 +01:00
|
|
|
import { uuid } from 'lib/crypto';
|
|
|
|
import { useAuth } from 'lib/middleware';
|
2023-03-03 07:48:30 +01:00
|
|
|
import { NextApiRequestQueryBody, Roles, User } from 'lib/types';
|
2022-11-15 22:21:14 +01:00
|
|
|
import { NextApiResponse } from 'next';
|
2022-11-20 09:48:13 +01:00
|
|
|
import { badRequest, hashPassword, methodNotAllowed, ok, unauthorized } from 'next-basics';
|
2023-03-01 20:40:34 +01:00
|
|
|
import { createUser, getUser, getUsers } from 'queries';
|
2022-11-15 22:21:14 +01:00
|
|
|
|
|
|
|
export interface UsersRequestBody {
|
|
|
|
username: string;
|
|
|
|
password: string;
|
|
|
|
id: string;
|
2023-03-03 07:48:30 +01:00
|
|
|
role?: Roles;
|
2022-11-15 22:21:14 +01:00
|
|
|
}
|
|
|
|
|
|
|
|
export default async (
|
2022-11-18 09:27:42 +01:00
|
|
|
req: NextApiRequestQueryBody<any, UsersRequestBody>,
|
2022-11-15 22:21:14 +01:00
|
|
|
res: NextApiResponse<User[] | User>,
|
|
|
|
) => {
|
2020-08-12 07:24:41 +02:00
|
|
|
await useAuth(req, res);
|
|
|
|
|
2020-09-16 22:13:50 +02:00
|
|
|
if (req.method === 'GET') {
|
2022-12-28 00:18:58 +01:00
|
|
|
if (!(await canViewUsers(req.auth))) {
|
2022-12-02 05:53:37 +01:00
|
|
|
return unauthorized(res);
|
|
|
|
}
|
|
|
|
|
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-12-28 00:18:58 +01:00
|
|
|
if (!(await canCreateUser(req.auth))) {
|
2022-12-02 05:53:37 +01:00
|
|
|
return unauthorized(res);
|
|
|
|
}
|
|
|
|
|
2023-03-03 07:48:30 +01:00
|
|
|
const { username, password, role, id } = req.body;
|
2022-10-04 02:17:53 +02:00
|
|
|
|
2023-02-28 01:01:34 +01:00
|
|
|
const existingUser = await getUser({ username }, { showDeleted: true });
|
2022-10-04 02:17:53 +02:00
|
|
|
|
2022-12-07 03:36:41 +01:00
|
|
|
if (existingUser) {
|
2022-11-01 07:42:37 +01:00
|
|
|
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),
|
2023-03-03 07:48:30 +01:00
|
|
|
role: role ?? ROLES.user,
|
2022-10-04 02:17:53 +02:00
|
|
|
});
|
|
|
|
|
|
|
|
return ok(res, created);
|
|
|
|
}
|
|
|
|
|
2020-08-12 07:24:41 +02:00
|
|
|
return methodNotAllowed(res);
|
|
|
|
};
|