mirror of
https://github.com/umami-software/umami.git
synced 2026-02-16 10:35:35 +01:00
Convert teams api routes.
This commit is contained in:
parent
7d5556a637
commit
e51f182403
15 changed files with 354 additions and 4 deletions
90
src/pages/api/teams/[teamId]/users/_index.ts
Normal file
90
src/pages/api/teams/[teamId]/users/_index.ts
Normal file
|
|
@ -0,0 +1,90 @@
|
|||
import { canAddUserToTeam, canViewTeam } from 'lib/auth';
|
||||
import { useAuth, useValidate } from 'lib/middleware';
|
||||
import { pageInfo } from 'lib/schema';
|
||||
import { NextApiRequestQueryBody, PageParams } from 'lib/types';
|
||||
import { NextApiResponse } from 'next';
|
||||
import { badRequest, methodNotAllowed, ok, unauthorized } from 'next-basics';
|
||||
import { createTeamUser, getTeamUser, getTeamUsers } from 'queries';
|
||||
import * as yup from 'yup';
|
||||
|
||||
export interface TeamUserRequestQuery extends PageParams {
|
||||
teamId: string;
|
||||
}
|
||||
|
||||
export interface TeamUserRequestBody {
|
||||
userId: string;
|
||||
role: string;
|
||||
}
|
||||
|
||||
const schema = {
|
||||
GET: yup.object().shape({
|
||||
teamId: yup.string().uuid().required(),
|
||||
...pageInfo,
|
||||
}),
|
||||
POST: yup.object().shape({
|
||||
userId: yup.string().uuid().required(),
|
||||
role: yup
|
||||
.string()
|
||||
.matches(/team-member|team-view-only|team-manager/i)
|
||||
.required(),
|
||||
}),
|
||||
};
|
||||
|
||||
export default async (
|
||||
req: NextApiRequestQueryBody<TeamUserRequestQuery, TeamUserRequestBody>,
|
||||
res: NextApiResponse,
|
||||
) => {
|
||||
await useAuth(req, res);
|
||||
await useValidate(schema, req, res);
|
||||
|
||||
const { teamId } = req.query;
|
||||
|
||||
if (req.method === 'GET') {
|
||||
if (!(await canViewTeam(req.auth, teamId))) {
|
||||
return unauthorized(res);
|
||||
}
|
||||
|
||||
const users = await getTeamUsers(
|
||||
{
|
||||
where: {
|
||||
teamId,
|
||||
user: {
|
||||
deletedAt: null,
|
||||
},
|
||||
},
|
||||
include: {
|
||||
user: {
|
||||
select: {
|
||||
id: true,
|
||||
username: true,
|
||||
},
|
||||
},
|
||||
},
|
||||
},
|
||||
req.query,
|
||||
);
|
||||
|
||||
return ok(res, users);
|
||||
}
|
||||
|
||||
// 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);
|
||||
}
|
||||
|
||||
return methodNotAllowed(res);
|
||||
};
|
||||
Loading…
Add table
Add a link
Reference in a new issue