umami/pages/api/website.js

41 lines
1011 B
JavaScript
Raw Normal View History

import { getWebsites, updateWebsite, createWebsite, getWebsite } from 'lib/db';
2020-07-28 08:52:14 +02:00
import { useAuth } from 'lib/middleware';
import { uuid } 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-07 11:27:12 +02:00
const { website_id } = req.body;
2020-07-28 08:52:14 +02:00
2020-08-07 11:27:12 +02:00
if (req.method === 'GET') {
const websites = await getWebsites(user_id);
2020-07-28 08:52:14 +02:00
return ok(res, websites);
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) {
const website = getWebsite(website_id);
if (website.user_id === user_id || is_admin) {
await updateWebsite(website_id, { name, domain });
return ok(res);
}
return unauthorized(res);
} else {
const website_uuid = uuid();
const website = await createWebsite(user_id, { website_uuid, name, domain });
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
};