Created admin API endpoints.

This commit is contained in:
Mike Cao 2023-12-12 21:23:12 -08:00
parent e1c65cdf2a
commit 442ad61779
8 changed files with 133 additions and 49 deletions

View file

@ -0,0 +1,53 @@
import { canViewUsers } from 'lib/auth';
import { useAuth, useValidate } from 'lib/middleware';
import { NextApiRequestQueryBody, Role, SearchFilter, User } from 'lib/types';
import { pageInfo } from 'lib/schema';
import { NextApiResponse } from 'next';
import { methodNotAllowed, ok, unauthorized } from 'next-basics';
import { getUsers } from 'queries';
import * as yup from 'yup';
export interface UsersRequestQuery extends SearchFilter {}
export interface UsersRequestBody {
username: string;
password: string;
id: string;
role: Role;
}
const schema = {
GET: yup.object().shape({
...pageInfo,
}),
POST: yup.object().shape({
username: yup.string().max(255).required(),
password: yup.string().required(),
id: yup.string().uuid(),
role: yup
.string()
.matches(/admin|user|view-only/i)
.required(),
}),
};
export default async (
req: NextApiRequestQueryBody<UsersRequestQuery, UsersRequestBody>,
res: NextApiResponse<User[] | User>,
) => {
await useAuth(req, res);
await useValidate(schema, req, res);
if (req.method === 'GET') {
if (!(await canViewUsers(req.auth))) {
return unauthorized(res);
}
const { page, query, pageSize } = req.query;
const users = await getUsers({ page, query, pageSize: +pageSize || undefined });
return ok(res, users);
}
return methodNotAllowed(res);
};

View file

@ -0,0 +1,66 @@
import { canViewAllWebsites } from 'lib/auth';
import { useAuth, useCors, useValidate } from 'lib/middleware';
import { NextApiRequestQueryBody, SearchFilter } from 'lib/types';
import { NextApiResponse } from 'next';
import { methodNotAllowed, ok, unauthorized } from 'next-basics';
import { getWebsites } from 'queries';
import * as yup from 'yup';
import { pageInfo } from 'lib/schema';
export interface WebsitesRequestQuery extends SearchFilter {}
export interface WebsitesRequestBody {
name: string;
domain: string;
shareId: string;
}
const schema = {
GET: yup.object().shape({
...pageInfo,
}),
POST: yup.object().shape({
name: yup.string().max(100).required(),
domain: yup.string().max(500).required(),
shareId: yup.string().max(50).nullable(),
}),
};
export default async (
req: NextApiRequestQueryBody<WebsitesRequestQuery, WebsitesRequestBody>,
res: NextApiResponse,
) => {
await useCors(req, res);
await useAuth(req, res);
await useValidate(schema, req, res);
if (req.method === 'GET') {
if (!(await canViewAllWebsites(req.auth))) {
return unauthorized(res);
}
const websites = await getWebsites(req.query, {
include: {
teamWebsite: {
include: {
team: {
select: {
name: true,
},
},
},
},
user: {
select: {
username: true,
id: true,
},
},
},
});
return ok(res, websites);
}
return methodNotAllowed(res);
};