umami/pages/api/websites/index.js

50 lines
1.4 KiB
JavaScript
Raw Normal View History

import { createWebsite, getAccount, getAllWebsites, getUserWebsites } from 'queries';
import { ok, methodNotAllowed, unauthorized, getRandomChars } from 'next-basics';
2020-08-12 07:24:41 +02:00
import { useAuth } from 'lib/middleware';
import { uuid } from 'lib/crypto';
2020-08-12 07:24:41 +02:00
export default async (req, res) => {
await useAuth(req, res);
const { userId: currentUserId, isAdmin, accountUuid } = req.auth;
const { user_id, include_all } = req.query;
let account;
if (accountUuid) {
account = await getAccount({ accountUuid: accountUuid });
}
const userId = account ? account.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 =
isAdmin && include_all
? await getAllWebsites()
: await getUserWebsites(userId || currentUserId);
2020-08-12 07:24:41 +02:00
return ok(res, websites);
}
if (req.method === 'POST') {
const { name, domain, owner, enable_share_url } = req.body;
const website_owner = account ? account.id : +owner;
if (website_owner !== currentUserId && !isAdmin) {
return unauthorized(res);
}
const websiteUuid = uuid();
const shareId = enable_share_url ? getRandomChars(8) : null;
const website = await createWebsite(website_owner, { websiteUuid, name, domain, shareId });
return ok(res, website);
}
2020-08-12 07:24:41 +02:00
return methodNotAllowed(res);
};