Add permission checks.

This commit is contained in:
Brian Cao 2022-11-20 00:48:13 -08:00
parent 51e2331315
commit 78225691df
20 changed files with 225 additions and 333 deletions

View file

@ -4,7 +4,7 @@ import { allowQuery } from 'lib/auth';
import { UmamiApi } from 'lib/constants';
import { useAuth, useCors } from 'lib/middleware';
import { NextApiResponse } from 'next';
import { methodNotAllowed, ok, serverError, unauthorized } from 'next-basics';
import { methodNotAllowed, ok, serverError, unauthorized, badRequest } from 'next-basics';
import { deleteWebsite, getWebsite, updateWebsite } from 'queries';
export interface WebsiteRequestQuery {
@ -15,6 +15,8 @@ export interface WebsiteRequestBody {
name: string;
domain: string;
shareId: string;
userId?: string;
teamId?: string;
}
export default async (
@ -37,14 +39,14 @@ export default async (
}
if (req.method === 'POST') {
const { name, domain, shareId } = req.body;
const { ...data } = req.body;
if (!data.userId && !data.teamId) {
badRequest(res, 'A website must be assigned to a User or Team.');
}
try {
await updateWebsite(websiteId, {
name,
domain,
shareId,
});
await updateWebsite(websiteId, data);
} catch (e: any) {
if (e.message.includes('Unique constraint') && e.message.includes('share_id')) {
return serverError(res, 'That share ID is already taken.');
@ -55,10 +57,6 @@ export default async (
}
if (req.method === 'DELETE') {
if (!(await allowQuery(req, UmamiApi.AuthType.Website))) {
return unauthorized(res);
}
await deleteWebsite(websiteId);
return ok(res);

View file

@ -1,9 +1,10 @@
import { Prisma } from '@prisma/client';
import { NextApiRequestQueryBody } from 'interface/api/nextApi';
import { uuid } from 'lib/crypto';
import { useAuth, useCors } from 'lib/middleware';
import { NextApiResponse } from 'next';
import { getRandomChars, methodNotAllowed, ok } from 'next-basics';
import { createWebsiteByUser, getAllWebsites, getWebsitesByUserId } from 'queries';
import { methodNotAllowed, ok } from 'next-basics';
import { createWebsite, getAllWebsites, getWebsitesByUserId } from 'queries';
export interface WebsitesRequestQuery {
include_all?: boolean;
@ -12,7 +13,8 @@ export interface WebsitesRequestQuery {
export interface WebsitesRequestBody {
name: string;
domain: string;
enableShareUrl: boolean;
shareId: string;
teamId?: string;
}
export default async (
@ -36,10 +38,22 @@ export default async (
}
if (req.method === 'POST') {
const { name, domain, enableShareUrl } = req.body;
const { name, domain, shareId, teamId } = req.body;
const shareId = enableShareUrl ? getRandomChars(8) : null;
const website = await createWebsiteByUser(userId, { id: uuid(), name, domain, shareId });
const data: Prisma.WebsiteCreateInput = {
id: uuid(),
name,
domain,
shareId,
};
if (teamId) {
data.teamId = teamId;
} else {
data.userId = userId;
}
const website = await createWebsite(data);
return ok(res, website);
}