umami/pages/api/website/index.js

44 lines
1.2 KiB
JavaScript
Raw Normal View History

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';
import { ok, unauthorized, methodNotAllowed } from 'lib/response';
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 } = 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);
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 });
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;
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
return ok(res, website);
2020-08-07 11:27:12 +02:00
}
}
return methodNotAllowed(res);
2020-07-28 08:52:14 +02:00
};