umami/src/pages/api/teams/[teamId]/users/[userId].ts

86 lines
2.1 KiB
TypeScript
Raw Normal View History

2024-01-29 20:58:13 +00:00
import { canDeleteTeamUser, canUpdateTeam } from 'lib/auth';
2024-01-26 19:39:27 +00:00
import { useAuth, useValidate } from 'lib/middleware';
import { NextApiRequestQueryBody } from 'lib/types';
import { NextApiResponse } from 'next';
2024-01-29 20:58:13 +00:00
import { badRequest, methodNotAllowed, ok, unauthorized } from 'next-basics';
import { deleteTeamUser, getTeamUser, updateTeamUser } from 'queries';
2024-01-26 19:39:27 +00:00
import * as yup from 'yup';
export interface TeamUserRequestQuery {
2024-02-01 06:08:48 +00:00
teamId: string;
2024-01-26 19:39:27 +00:00
userId: string;
}
2024-01-29 20:58:13 +00:00
export interface TeamUserRequestBody {
role: string;
}
2024-01-26 19:39:27 +00:00
const schema = {
DELETE: yup.object().shape({
2024-02-01 06:08:48 +00:00
teamId: yup.string().uuid().required(),
2024-01-26 19:39:27 +00:00
userId: yup.string().uuid().required(),
}),
2024-01-29 20:58:13 +00:00
POST: yup.object().shape({
role: yup
.string()
.matches(/team-member|team-view-only/i)
2024-01-29 20:58:13 +00:00
.required(),
}),
2024-01-26 19:39:27 +00:00
};
2024-01-29 20:58:13 +00:00
export default async (
req: NextApiRequestQueryBody<TeamUserRequestQuery, TeamUserRequestBody>,
res: NextApiResponse,
) => {
2024-01-26 19:39:27 +00:00
await useAuth(req, res);
await useValidate(schema, req, res);
2024-02-01 06:08:48 +00:00
const { teamId, userId } = req.query;
2024-01-29 20:58:13 +00:00
if (req.method === 'GET') {
if (!(await canUpdateTeam(req.auth, teamId))) {
return unauthorized(res, 'You must be the owner of this team.');
}
const teamUser = await getTeamUser(teamId, userId);
return ok(res, teamUser);
}
2024-01-29 20:58:13 +00:00
if (req.method === 'POST') {
if (!(await canUpdateTeam(req.auth, teamId))) {
return unauthorized(res, 'You must be the owner of this team.');
}
const teamUser = await getTeamUser(teamId, userId);
if (!teamUser) {
return badRequest(res, 'The User does not exists on this team.');
}
2024-01-26 19:39:27 +00:00
2024-01-29 20:58:13 +00:00
const { role } = req.body;
await updateTeamUser(teamUser.id, { role });
return ok(res);
}
if (req.method === 'DELETE') {
2024-01-26 19:39:27 +00:00
if (!(await canDeleteTeamUser(req.auth, teamId, userId))) {
return unauthorized(res, 'You must be the owner of this team.');
}
2024-01-29 20:58:13 +00:00
const teamUser = await getTeamUser(teamId, userId);
if (!teamUser) {
return badRequest(res, 'The User does not exists on this team.');
}
2024-01-26 19:39:27 +00:00
await deleteTeamUser(teamId, userId);
return ok(res);
}
return methodNotAllowed(res);
};