umami/src/pages/api/users/index.ts
2023-10-15 17:59:19 -07:00

79 lines
2.0 KiB
TypeScript

import { canCreateUser, canViewUsers } from 'lib/auth';
import { ROLES } from 'lib/constants';
import { uuid } from 'lib/crypto';
import { useAuth, useValidate } from 'lib/middleware';
import { NextApiRequestQueryBody, Role, SearchFilter, User } from 'lib/types';
import { pageInfo } from 'lib/schema';
import { NextApiResponse } from 'next';
import { badRequest, hashPassword, methodNotAllowed, ok, unauthorized } from 'next-basics';
import { createUser, getUserByUsername, getUsers } from 'queries';
import * as yup from 'yup';
export interface UsersRequestQuery extends SearchFilter {}
export interface UsersRequestBody {
username: string;
password: string;
id: string;
role: Role;
}
const schema = {
GET: yup.object().shape({
...pageInfo,
}),
POST: yup.object().shape({
username: yup.string().max(255).required(),
password: yup.string().required(),
id: yup.string().uuid(),
role: yup
.string()
.matches(/admin|user|view-only/i)
.required(),
}),
};
export default async (
req: NextApiRequestQueryBody<UsersRequestQuery, UsersRequestBody>,
res: NextApiResponse<User[] | User>,
) => {
await useAuth(req, res);
await useValidate(schema, req, res);
if (req.method === 'GET') {
if (!(await canViewUsers(req.auth))) {
return unauthorized(res);
}
const { page, query, pageSize } = req.query;
const users = await getUsers({ page, query, pageSize: +pageSize || undefined });
return ok(res, users);
}
if (req.method === 'POST') {
if (!(await canCreateUser(req.auth))) {
return unauthorized(res);
}
const { username, password, role, id } = req.body;
const existingUser = await getUserByUsername(username, { showDeleted: true });
if (existingUser) {
return badRequest(res, 'User already exists');
}
const created = await createUser({
id: id || uuid(),
username,
password: hashPassword(password),
role: role ?? ROLES.user,
});
return ok(res, created);
}
return methodNotAllowed(res);
};