umami/src/pages/api/users/index.ts

67 lines
1.7 KiB
TypeScript
Raw Normal View History

2023-12-13 05:23:12 +00:00
import { canCreateUser } from 'lib/auth';
import { ROLES } from 'lib/constants';
2023-07-29 00:21:34 +00:00
import { uuid } from 'lib/crypto';
2023-08-20 05:23:15 +00:00
import { useAuth, useValidate } from 'lib/middleware';
import { NextApiRequestQueryBody, Role, SearchFilter, User } from 'lib/types';
2023-09-22 07:59:00 +00:00
import { pageInfo } from 'lib/schema';
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-12-13 05:23:12 +00:00
import { createUser, getUserByUsername } from 'queries';
import * as yup from 'yup';
2022-11-15 21:21:14 +00:00
export interface UsersRequestQuery extends SearchFilter {}
2022-11-15 21:21:14 +00:00
export interface UsersRequestBody {
username: string;
password: string;
id: string;
2023-08-26 23:35:43 +00:00
role: Role;
2022-11-15 21:21:14 +00:00
}
2023-08-20 05:23:15 +00:00
const schema = {
GET: yup.object().shape({
2023-09-22 07:59:00 +00:00
...pageInfo,
2023-08-20 05:23:15 +00:00
}),
POST: yup.object().shape({
username: yup.string().max(255).required(),
password: yup.string().required(),
id: yup.string().uuid(),
2023-08-26 23:33:22 +00:00
role: yup
.string()
.matches(/admin|user|view-only/i)
.required(),
2023-08-20 05:23:15 +00:00
}),
};
2022-11-15 21:21:14 +00:00
export default async (
2023-08-10 20:26:33 +00:00
req: NextApiRequestQueryBody<UsersRequestQuery, 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);
2023-09-30 03:24:48 +00:00
await useValidate(schema, req, res);
2023-08-20 05:23:15 +00:00
if (req.method === 'POST') {
if (!(await canCreateUser(req.auth))) {
return unauthorized(res);
}
2023-03-03 06:48:30 +00:00
const { username, password, role, id } = req.body;
2023-07-30 05:03:34 +00:00
const existingUser = await getUserByUsername(username, { showDeleted: true });
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-11-01 06:42:37 +00:00
const created = await createUser({
2022-11-09 18:59:03 +00:00
id: id || uuid(),
username,
password: hashPassword(password),
2023-03-03 06:48:30 +00:00
role: role ?? ROLES.user,
});
return ok(res, created);
}
2020-08-12 05:24:41 +00:00
return methodNotAllowed(res);
};