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

69 lines
1.8 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 { uuid } from 'lib/crypto';
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, getUsersByTeamId, getTeamUser } from 'queries';
2022-11-18 09:27:42 +01:00
export interface TeamUserRequestQuery {
id: string;
}
export interface TeamUserRequestBody {
user_id: string;
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.');
}
2022-11-18 09:27:42 +01:00
const { user_id: userId } = req.body;
2022-11-22 01:44:42 +01:00
// Check for TeamUser
const teamUser = getTeamUser({ userId, teamId });
if (!teamUser) {
return badRequest(res, 'The User already exists on this Team.');
}
2022-11-18 09:27:42 +01:00
const updated = await createTeamUser({ id: uuid(), userId, teamId });
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);
};