2022-11-21 07:24:31 +01:00
|
|
|
import { UserRole } from '@prisma/client';
|
|
|
|
import { NextApiRequestQueryBody } from 'interface/api/nextApi';
|
2022-12-02 05:53:37 +01:00
|
|
|
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';
|
2022-12-02 05:53:37 +01:00
|
|
|
import { deleteUserRole, getUserRole, getUserRoles, updateUserRole } from 'queries';
|
2022-11-21 07:24:31 +01:00
|
|
|
|
|
|
|
export interface UserRoleRequestQuery {
|
|
|
|
id: string;
|
|
|
|
}
|
|
|
|
export interface UserRoleRequestBody {
|
2022-12-02 05:53:37 +01:00
|
|
|
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;
|
|
|
|
|
2022-12-02 05:53:37 +01:00
|
|
|
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') {
|
2022-12-02 05:53:37 +01:00
|
|
|
const { role } = req.body;
|
2022-11-21 07:24:31 +01:00
|
|
|
|
2022-12-02 05:53:37 +01:00
|
|
|
const userRole = await getUserRole({ userId: id });
|
2022-11-21 07:24:31 +01:00
|
|
|
|
2022-12-02 05:53:37 +01:00
|
|
|
if (userRole && userRole.role === role) {
|
2022-11-21 07:24:31 +01:00
|
|
|
return badRequest(res, 'Role already exists for User.');
|
2022-12-02 05:53:37 +01:00
|
|
|
} else {
|
|
|
|
const updated = await updateUserRole({ role }, { id: userRole.id });
|
2022-11-21 07:24:31 +01:00
|
|
|
|
2022-12-02 05:53:37 +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);
|
|
|
|
};
|