umami/pages/api/websites/index.js

49 lines
1.3 KiB
JavaScript
Raw Normal View History

2022-11-01 07:42:37 +01:00
import { createWebsite, getUser, getAllWebsites, getUserWebsites } from 'queries';
import { ok, methodNotAllowed, unauthorized, getRandomChars } from 'next-basics';
import { useAuth, useCors } from 'lib/middleware';
import { uuid } from 'lib/crypto';
2020-08-12 07:24:41 +02:00
export default async (req, res) => {
await useCors(req, res);
2020-08-12 07:24:41 +02:00
await useAuth(req, res);
const { user_id, include_all } = req.query;
const { userId: currentUserId, isAdmin } = req.auth;
2022-11-01 07:42:37 +01:00
const id = user_id || currentUserId;
let user;
2022-11-01 07:42:37 +01:00
if (id) {
user = await getUser({ id });
}
2022-11-01 07:42:37 +01:00
const userId = user ? user.id : user_id;
2020-08-12 07:24:41 +02:00
if (req.method === 'GET') {
if (userId && userId !== currentUserId && !isAdmin) {
2020-09-11 08:55:29 +02:00
return unauthorized(res);
}
const websites =
2022-11-01 07:42:37 +01:00
isAdmin && include_all ? await getAllWebsites() : await getUserWebsites({ userId });
2020-08-12 07:24:41 +02:00
return ok(res, websites);
}
if (req.method === 'POST') {
2022-10-12 22:11:44 +02:00
const { name, domain, owner, enableShareUrl } = req.body;
2022-11-01 07:42:37 +01:00
const website_owner = user ? userId : +owner;
if (website_owner !== currentUserId && !isAdmin) {
return unauthorized(res);
}
2022-10-12 22:11:44 +02:00
const shareId = enableShareUrl ? getRandomChars(8) : null;
2022-11-01 07:42:37 +01:00
const website = await createWebsite(website_owner, { id: uuid(), name, domain, shareId });
return ok(res, website);
}
2020-08-12 07:24:41 +02:00
return methodNotAllowed(res);
};