umami/pages/api/websites/[id]/index.js

65 lines
1.5 KiB
JavaScript
Raw Normal View History

import { allowQuery } from 'lib/auth';
import { useAuth, useCors } from 'lib/middleware';
2022-10-12 04:37:38 +02:00
import { getRandomChars, methodNotAllowed, ok, unauthorized } from 'next-basics';
import { deleteWebsite, getAccount, getWebsite, getWebsiteByUuid, updateWebsite } from 'queries';
export default async (req, res) => {
2022-10-12 04:37:38 +02:00
const { id: websiteId } = req.query;
if (req.method === 'GET') {
await useCors(req, res);
if (!(await allowQuery(req))) {
return unauthorized(res);
}
2022-10-12 04:37:38 +02:00
const website = await getWebsiteByUuid(websiteId);
return ok(res, website);
}
if (req.method === 'POST') {
await useAuth(req, res);
const { isAdmin: currentUserIsAdmin, userId: currentUserId, accountUuid } = req.auth;
const { name, domain, owner, enable_share_url } = req.body;
2022-10-08 02:13:03 +02:00
let account;
if (accountUuid) {
account = await getAccount({ accountUuid });
}
2022-10-12 04:37:38 +02:00
const website = await getWebsite(websiteId);
const shareId = enable_share_url ? website.shareId || getRandomChars(8) : null;
if (website.userId !== currentUserId && !currentUserIsAdmin) {
2022-10-08 02:13:03 +02:00
return unauthorized(res);
}
2022-10-08 02:13:03 +02:00
await updateWebsite(
{
name,
domain,
shareId: shareId,
userId: account ? account.id : +owner,
2022-10-08 02:13:03 +02:00
},
2022-10-12 04:37:38 +02:00
{ websiteUuid: websiteId },
2022-10-08 02:13:03 +02:00
);
return ok(res);
}
if (req.method === 'DELETE') {
if (!(await allowQuery(req, true))) {
return unauthorized(res);
}
await deleteWebsite(websiteId);
return ok(res);
}
return methodNotAllowed(res);
};