2020-08-12 07:24:41 +02:00
|
|
|
import { updateWebsite, createWebsite, getWebsiteById } from 'lib/queries';
|
2020-07-28 08:52:14 +02:00
|
|
|
import { useAuth } from 'lib/middleware';
|
2020-08-15 10:17:15 +02:00
|
|
|
import { uuid, getRandomChars } from 'lib/crypto';
|
2020-08-08 02:19:42 +02:00
|
|
|
import { ok, unauthorized, methodNotAllowed } from 'lib/response';
|
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') {
|
2020-08-08 02:19:42 +02:00
|
|
|
const { name, domain } = req.body;
|
|
|
|
|
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
|
|
|
}
|
|
|
|
|
2020-09-18 07:52:20 +02:00
|
|
|
await updateWebsite(website_id, { name, domain, share_id });
|
|
|
|
|
|
|
|
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;
|
2020-08-15 10:17:15 +02:00
|
|
|
const website = await createWebsite(user_id, { 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
|
|
|
};
|