umami/pages/api/users/index.ts

57 lines
1.3 KiB
TypeScript
Raw Normal View History

import { canCreateUser, canViewUsers } from 'lib/auth';
import { ROLES } from 'lib/constants';
2022-11-20 08:48:13 +00:00
import { uuid } from 'lib/crypto';
import { useAuth } from 'lib/middleware';
import { NextApiRequestQueryBody } 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';
import { createUser, getUser, getUsers, User } from 'queries';
2022-11-15 21:21:14 +00:00
export interface UsersRequestBody {
username: string;
password: string;
id: string;
}
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') {
if (!(await canViewUsers(req.auth))) {
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
}
if (req.method === 'POST') {
if (!(await canCreateUser(req.auth))) {
return unauthorized(res);
}
2022-11-09 18:59:03 +00:00
const { username, password, id } = req.body;
2022-12-07 02:36:41 +00:00
const existingUser = await getUser({ username });
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),
2022-12-07 02:36:41 +00:00
role: ROLES.user,
});
return ok(res, created);
}
2020-08-12 05:24:41 +00:00
return methodNotAllowed(res);
};