umami/pages/api/website/index.js

45 lines
1.2 KiB
JavaScript
Raw Normal View History

2022-08-29 05:20:54 +02:00
import { ok, unauthorized, methodNotAllowed, getRandomChars } from 'next-basics';
2022-07-12 23:14:36 +02:00
import { updateWebsite, createWebsite, getWebsiteById } from 'queries';
2020-07-28 08:52:14 +02:00
import { useAuth } from 'lib/middleware';
2022-08-29 05:20:54 +02:00
import { uuid } from 'lib/crypto';
2020-07-28 08:52:14 +02:00
export default async (req, res) => {
await useAuth(req, res);
const { user_id, is_admin } = req.auth;
2020-08-17 06:28:54 +02:00
const { website_id, enable_share_url } = req.body;
2020-07-28 08:52:14 +02:00
2020-08-07 11:27:12 +02:00
if (req.method === 'POST') {
const { name, domain, owner } = req.body;
const website_owner = parseInt(owner);
2020-08-07 11:27:12 +02:00
if (website_id) {
2020-08-15 10:17:15 +02:00
const website = await getWebsiteById(website_id);
if (website.user_id !== user_id && !is_admin) {
return unauthorized(res);
}
2020-08-15 10:17:15 +02:00
let { share_id } = website;
if (enable_share_url) {
share_id = share_id ? share_id : getRandomChars(8);
} else {
share_id = null;
}
await updateWebsite(website_id, { name, domain, share_id, user_id: website_owner });
return ok(res);
} else {
const website_uuid = uuid();
2020-08-17 06:28:54 +02:00
const share_id = enable_share_url ? getRandomChars(8) : null;
const website = await createWebsite(website_owner, { website_uuid, name, domain, share_id });
2020-08-07 11:27:12 +02:00
return ok(res, website);
2020-08-07 11:27:12 +02:00
}
}
return methodNotAllowed(res);
2020-07-28 08:52:14 +02:00
};