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

69 lines
1.7 KiB
TypeScript
Raw Normal View History

2022-11-18 09:27:42 +01:00
import { NextApiRequestQueryBody } from 'interface/api/nextApi';
2022-11-20 09:48:13 +01:00
import { allowQuery } from 'lib/auth';
import { UmamiApi } from 'lib/constants';
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';
import { createTeamUser, deleteTeamUser, getUser, getUsersByTeamId } from 'queries';
2022-11-18 09:27:42 +01:00
export interface TeamUserRequestQuery {
id: string;
}
export interface TeamUserRequestBody {
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);
const { id: teamId } = req.query;
if (req.method === 'GET') {
2022-11-20 09:48:13 +01:00
if (!(await allowQuery(req, UmamiApi.AuthType.Team))) {
return unauthorized(res);
}
2022-11-18 09:27:42 +01:00
const user = await getUsersByTeamId({ teamId });
return ok(res, user);
}
if (req.method === 'POST') {
2022-11-20 09:48:13 +01:00
if (!(await allowQuery(req, UmamiApi.AuthType.TeamOwner))) {
return unauthorized(res, 'You must be the owner of this team.');
}
const { email, role_id: 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') {
2022-11-20 09:48:13 +01:00
if (!(await allowQuery(req, UmamiApi.AuthType.TeamOwner))) {
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);
};