umami/pages/api/users/[id]/role.ts

63 lines
1.6 KiB
TypeScript
Raw Normal View History

2022-11-21 07:24:31 +01:00
import { UserRole } from '@prisma/client';
import { NextApiRequestQueryBody } from 'interface/api/nextApi';
import { canUpdateUserRole } from 'lib/auth';
2022-11-21 07:24:31 +01:00
import { UmamiApi } from 'lib/constants';
import { useAuth } from 'lib/middleware';
import { NextApiResponse } from 'next';
import { badRequest, methodNotAllowed, ok, unauthorized } from 'next-basics';
import { deleteUserRole, getUserRole, getUserRoles, updateUserRole } from 'queries';
2022-11-21 07:24:31 +01:00
export interface UserRoleRequestQuery {
id: string;
}
export interface UserRoleRequestBody {
role: UmamiApi.Role;
2022-11-21 07:24:31 +01:00
userRoleId?: string;
}
export default async (
req: NextApiRequestQueryBody<UserRoleRequestQuery, UserRoleRequestBody>,
res: NextApiResponse<UserRole>,
) => {
await useAuth(req, res);
const {
user: { id: userId },
} = req.auth;
const { id } = req.query;
if (await canUpdateUserRole(userId)) {
2022-11-21 07:24:31 +01:00
return unauthorized(res);
}
if (req.method === 'GET') {
const userRole = await getUserRoles({ userId: id });
return ok(res, userRole);
}
if (req.method === 'POST') {
const { role } = req.body;
2022-11-21 07:24:31 +01:00
const userRole = await getUserRole({ userId: id });
2022-11-21 07:24:31 +01:00
if (userRole && userRole.role === role) {
2022-11-21 07:24:31 +01:00
return badRequest(res, 'Role already exists for User.');
} else {
const updated = await updateUserRole({ role }, { id: userRole.id });
2022-11-21 07:24:31 +01:00
return ok(res, updated);
}
2022-11-21 07:24:31 +01:00
}
if (req.method === 'DELETE') {
const { userRoleId } = req.body;
const updated = await deleteUserRole(userRoleId);
return ok(res, updated);
}
return methodNotAllowed(res);
};