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

67 lines
1.5 KiB
JavaScript
Raw Normal View History

2022-10-08 02:13:03 +02:00
import { methodNotAllowed, ok, unauthorized } from 'next-basics';
import { deleteWebsite, getAccount, getWebsite, updateWebsite } from 'queries';
import { allowQuery } from 'lib/auth';
import { useAuth, useCors } from 'lib/middleware';
2022-10-06 23:18:27 +02:00
import { validate } from 'uuid';
export default async (req, res) => {
const { id } = req.query;
const websiteId = +id;
2022-10-06 23:18:27 +02:00
const where = validate(id) ? { website_uuid: id } : { website_id: +id };
if (req.method === 'GET') {
await useCors(req, res);
if (!(await allowQuery(req))) {
return unauthorized(res);
}
2022-10-06 23:18:27 +02:00
const website = await getWebsite(where);
return ok(res, website);
}
if (req.method === 'POST') {
await useAuth(req, res);
2022-10-08 02:13:03 +02:00
const { is_admin: currentUserIsAdmin, user_id: currentUserId, account_uuid } = req.auth;
const { name, domain, owner, share_id } = req.body;
let account;
2022-10-08 02:13:03 +02:00
if (account_uuid) {
account = await getAccount({ account_uuid });
}
2022-10-08 02:13:03 +02:00
const website = await getWebsite(where);
2022-10-08 02:13:03 +02:00
if (website.user_id !== currentUserId && !currentUserIsAdmin) {
return unauthorized(res);
}
2022-10-08 02:13:03 +02:00
await updateWebsite(
{
name,
domain,
share_id: share_id || null,
user_id: account ? account.id : +owner,
},
where,
);
return ok(res);
}
if (req.method === 'DELETE') {
if (!(await allowQuery(req, true))) {
return unauthorized(res);
}
await deleteWebsite(websiteId);
return ok(res);
}
return methodNotAllowed(res);
};