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

91 lines
2 KiB
TypeScript
Raw Normal View History

2024-01-26 19:28:16 +00:00
import { canAddUserToTeam, canViewTeam } from 'lib/auth';
2023-09-25 20:19:56 +00:00
import { useAuth, useValidate } from 'lib/middleware';
2024-01-26 19:28:16 +00:00
import { pageInfo } from 'lib/schema';
import { NextApiRequestQueryBody, SearchFilter } from 'lib/types';
2022-11-18 08:27:42 +00:00
import { NextApiResponse } from 'next';
2024-01-26 19:28:16 +00:00
import { badRequest, methodNotAllowed, ok, unauthorized } from 'next-basics';
2024-01-30 08:10:25 +00:00
import { createTeamUser, getTeamUser, getTeamUsers } from 'queries';
2024-01-26 19:28:16 +00:00
import * as yup from 'yup';
2022-11-18 08:27:42 +00:00
export interface TeamUserRequestQuery extends SearchFilter {
2024-02-01 06:08:48 +00:00
teamId: string;
2022-11-18 08:27:42 +00:00
}
2024-01-26 19:28:16 +00:00
export interface TeamUserRequestBody {
userId: string;
role: string;
}
2023-09-25 20:19:56 +00:00
const schema = {
GET: yup.object().shape({
2024-02-01 06:08:48 +00:00
teamId: yup.string().uuid().required(),
2023-10-16 00:59:19 +00:00
...pageInfo,
2023-09-25 20:19:56 +00:00
}),
2024-01-26 19:28:16 +00:00
POST: yup.object().shape({
userId: yup.string().uuid().required(),
role: yup
.string()
2024-02-16 20:02:18 +00:00
.matches(/team-member|team-view-only/i)
2024-01-26 19:28:16 +00:00
.required(),
}),
2023-09-25 20:19:56 +00:00
};
2022-11-18 08:27:42 +00:00
export default async (
2024-01-29 20:58:13 +00:00
req: NextApiRequestQueryBody<TeamUserRequestQuery, TeamUserRequestBody>,
2022-11-18 08:27:42 +00:00
res: NextApiResponse,
) => {
await useAuth(req, res);
2023-09-30 03:24:48 +00:00
await useValidate(schema, req, res);
2022-11-18 08:27:42 +00:00
2024-02-01 06:08:48 +00:00
const { teamId } = req.query;
2022-11-18 08:27:42 +00:00
if (req.method === 'GET') {
if (!(await canViewTeam(req.auth, teamId))) {
2022-11-20 08:48:13 +00:00
return unauthorized(res);
}
2024-02-03 01:49:17 +00:00
const users = await getTeamUsers(
{
where: {
teamId,
user: {
deletedAt: null,
},
},
2024-02-03 01:49:17 +00:00
include: {
user: {
select: {
id: true,
username: true,
},
},
},
},
2024-02-28 18:19:22 +00:00
req.query,
2024-02-03 01:49:17 +00:00
);
2022-11-18 08:27:42 +00:00
2022-12-07 02:36:41 +00:00
return ok(res, users);
2022-11-18 08:27:42 +00:00
}
2024-01-26 19:28:16 +00:00
// admin function only
if (req.method === 'POST') {
if (!(await canAddUserToTeam(req.auth))) {
return unauthorized(res);
}
const { userId, role } = req.body;
const teamUser = await getTeamUser(teamId, userId);
if (teamUser) {
return badRequest(res, 'User is already a member of the Team.');
}
const users = await createTeamUser(userId, teamId, role);
return ok(res, users);
}
2022-11-18 08:27:42 +00:00
return methodNotAllowed(res);
};