2022-12-07 03:36:41 +01:00
|
|
|
import { NextApiRequestQueryBody } from 'lib/types';
|
2022-12-02 05:53:37 +01:00
|
|
|
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 {
|
2022-11-23 07:17:49 +01:00
|
|
|
email: string;
|
|
|
|
role_id: string;
|
2022-11-18 09:27:42 +01:00
|
|
|
team_user_id?: string;
|
|
|
|
}
|
|
|
|
|
|
|
|
export default async (
|
|
|
|
req: NextApiRequestQueryBody<TeamUserRequestQuery, TeamUserRequestBody>,
|
|
|
|
res: NextApiResponse,
|
|
|
|
) => {
|
|
|
|
await useAuth(req, res);
|
|
|
|
|
2022-12-02 05:53:37 +01:00
|
|
|
const {
|
|
|
|
user: { id: userId },
|
|
|
|
} = req.auth;
|
2022-11-18 09:27:42 +01:00
|
|
|
const { id: teamId } = req.query;
|
|
|
|
|
|
|
|
if (req.method === 'GET') {
|
2022-12-07 03:36:41 +01:00
|
|
|
if (!(await canViewTeam(userId, 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') {
|
2022-12-07 03:36:41 +01:00
|
|
|
if (!(await canUpdateTeam(userId, teamId))) {
|
2022-11-20 09:48:13 +01:00
|
|
|
return unauthorized(res, 'You must be the owner of this team.');
|
|
|
|
}
|
|
|
|
|
2022-11-23 07:17:49 +01:00
|
|
|
const { email, role_id: roleId } = req.body;
|
2022-11-18 09:27:42 +01:00
|
|
|
|
2022-11-23 07:17:49 +01:00
|
|
|
// Check for User
|
|
|
|
const user = await getUser({ username: email });
|
2022-11-22 01:44:42 +01:00
|
|
|
|
2022-11-23 07:17:49 +01:00
|
|
|
if (!user) {
|
|
|
|
return badRequest(res, 'The User does not exists.');
|
2022-11-22 01:44:42 +01:00
|
|
|
}
|
|
|
|
|
2022-11-23 07:17:49 +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') {
|
2022-12-02 05:53:37 +01:00
|
|
|
if (await canUpdateTeam(userId, teamId)) {
|
2022-11-20 09:48:13 +01:00
|
|
|
return unauthorized(res, 'You must be the owner of this team.');
|
|
|
|
}
|
2022-11-18 09:27:42 +01:00
|
|
|
const { team_user_id } = req.body;
|
|
|
|
|
|
|
|
await deleteTeamUser(team_user_id);
|
|
|
|
|
|
|
|
return ok(res);
|
|
|
|
}
|
|
|
|
|
|
|
|
return methodNotAllowed(res);
|
|
|
|
};
|