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

68 lines
1.6 KiB
TypeScript
Raw Normal View History

2022-12-07 03:36:41 +01:00
import { NextApiRequestQueryBody } from 'lib/types';
import { canUpdateTeam, canViewTeam } from 'lib/auth';
2022-11-18 09:27:42 +01:00
import { useAuth } from 'lib/middleware';
import { NextApiResponse } from 'next';
2022-11-22 01:44:42 +01:00
import { badRequest, methodNotAllowed, ok, unauthorized } from 'next-basics';
2022-12-07 03:36:41 +01:00
import { createTeamUser, deleteTeamUser, getUser, getTeamUsers } from 'queries';
2022-11-18 09:27:42 +01:00
export interface TeamUserRequestQuery {
id: string;
}
export interface TeamUserRequestBody {
email: string;
2022-12-27 02:36:48 +01:00
roleId: string;
teamUserId?: string;
2022-11-18 09:27:42 +01:00
}
export default async (
req: NextApiRequestQueryBody<TeamUserRequestQuery, TeamUserRequestBody>,
res: NextApiResponse,
) => {
await useAuth(req, res);
const { id: teamId } = req.query;
if (req.method === 'GET') {
if (!(await canViewTeam(req.auth, teamId))) {
2022-11-20 09:48:13 +01:00
return unauthorized(res);
}
2022-12-07 03:36:41 +01:00
const users = await getTeamUsers(teamId);
2022-11-18 09:27:42 +01:00
2022-12-07 03:36:41 +01:00
return ok(res, users);
2022-11-18 09:27:42 +01:00
}
if (req.method === 'POST') {
if (!(await canUpdateTeam(req.auth, teamId))) {
2022-11-20 09:48:13 +01:00
return unauthorized(res, 'You must be the owner of this team.');
}
2022-12-27 02:36:48 +01:00
const { email, roleId: roleId } = req.body;
2022-11-18 09:27:42 +01:00
// Check for User
const user = await getUser({ username: email });
2022-11-22 01:44:42 +01:00
if (!user) {
return badRequest(res, 'The User does not exists.');
2022-11-22 01:44:42 +01:00
}
const updated = await createTeamUser(user.id, teamId, roleId);
2022-11-18 09:27:42 +01:00
return ok(res, updated);
}
if (req.method === 'DELETE') {
if (await canUpdateTeam(req.auth, teamId)) {
2022-11-20 09:48:13 +01:00
return unauthorized(res, 'You must be the owner of this team.');
}
2022-12-27 02:36:48 +01:00
const { teamUserId } = req.body;
2022-11-18 09:27:42 +01:00
2022-12-27 02:36:48 +01:00
await deleteTeamUser(teamUserId);
2022-11-18 09:27:42 +01:00
return ok(res);
}
return methodNotAllowed(res);
};