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

56 lines
1.3 KiB
TypeScript
Raw Normal View History

2023-04-10 01:04:28 +02:00
import { canUpdateTeam, canViewTeam } from 'lib/auth';
2022-11-18 09:27:42 +01:00
import { useAuth } from 'lib/middleware';
2023-04-10 01:04:28 +02:00
import { NextApiRequestQueryBody } from 'lib/types';
2022-11-18 09:27:42 +01:00
import { NextApiResponse } from 'next';
2022-11-22 01:44:42 +01:00
import { badRequest, methodNotAllowed, ok, unauthorized } from 'next-basics';
2023-04-10 01:04:28 +02:00
import { createTeamUser, getTeamUsers, getUser } 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;
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);
}
return methodNotAllowed(res);
};