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