umami/pages/api/websites/index.js

53 lines
1.5 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 { user_id: current_user_id, is_admin, account_uuid } = req.auth;
const { user_id, include_all } = req.query;
let account;
if (account_uuid) {
account = await getAccount({ account_uuid });
}
const userId = account ? account.user_id : +user_id;
2020-08-12 07:24:41 +02:00
if (req.method === 'GET') {
2020-09-18 09:34:22 +02:00
if (userId && userId !== current_user_id && !is_admin) {
2020-09-11 08:55:29 +02:00
return unauthorized(res);
}
const websites =
is_admin && include_all
? await getAllWebsites()
: await getUserWebsites(userId || current_user_id);
2020-08-12 07:24:41 +02:00
return ok(res, websites);
}
if (req.method === 'POST') {
await useAuth(req, res);
const { is_admin: currentUserIsAdmin, user_id: currentUserId } = req.auth;
const { name, domain, owner, enable_share_url } = req.body;
const website_owner = account ? account.user_id : +owner;
if (website_owner !== currentUserId && !currentUserIsAdmin) {
return unauthorized(res);
}
const website_uuid = uuid();
const share_id = enable_share_url ? getRandomChars(8) : null;
const website = await createWebsite(website_owner, { website_uuid, name, domain, share_id });
return ok(res, website);
}
2020-08-12 07:24:41 +02:00
return methodNotAllowed(res);
};