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);
|
|
|
|
|
2020-08-08 02:19:42 +02:00
|
|
|
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') {
|
2022-08-26 17:22:46 +02:00
|
|
|
const { name, domain, owner } = req.body;
|
|
|
|
const website_owner = parseInt(owner);
|
2020-08-08 02:19:42 +02:00
|
|
|
|
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);
|
2020-08-08 02:19:42 +02:00
|
|
|
|
2020-09-18 07:52:20 +02:00
|
|
|
if (website.user_id !== user_id && !is_admin) {
|
|
|
|
return unauthorized(res);
|
|
|
|
}
|
2020-08-15 10:17:15 +02:00
|
|
|
|
2020-09-18 07:52:20 +02:00
|
|
|
let { share_id } = website;
|
2020-08-08 02:19:42 +02:00
|
|
|
|
2020-09-18 07:52:20 +02:00
|
|
|
if (enable_share_url) {
|
|
|
|
share_id = share_id ? share_id : getRandomChars(8);
|
|
|
|
} else {
|
|
|
|
share_id = null;
|
2020-08-08 02:19:42 +02:00
|
|
|
}
|
|
|
|
|
2022-08-26 17:22:46 +02:00
|
|
|
await updateWebsite(website_id, { name, domain, share_id, user_id: website_owner });
|
2020-09-18 07:52:20 +02:00
|
|
|
|
|
|
|
return ok(res);
|
2020-08-08 02:19:42 +02:00
|
|
|
} else {
|
|
|
|
const website_uuid = uuid();
|
2020-08-17 06:28:54 +02:00
|
|
|
const share_id = enable_share_url ? getRandomChars(8) : null;
|
2022-08-26 17:22:46 +02:00
|
|
|
const website = await createWebsite(website_owner, { website_uuid, name, domain, share_id });
|
2020-08-07 11:27:12 +02:00
|
|
|
|
2020-08-08 02:19:42 +02:00
|
|
|
return ok(res, website);
|
2020-08-07 11:27:12 +02:00
|
|
|
}
|
|
|
|
}
|
|
|
|
|
2020-08-08 02:19:42 +02:00
|
|
|
return methodNotAllowed(res);
|
2020-07-28 08:52:14 +02:00
|
|
|
};
|