Refactor API authentication.

This commit is contained in:
Mike Cao 2022-10-12 13:11:44 -07:00
parent c33729e185
commit 5a4fc96ebc
13 changed files with 71 additions and 73 deletions

View file

@ -1,4 +1,3 @@
import { validate } from 'uuid';
import { parseSecureToken, parseToken } from 'next-basics';
import { getWebsite } from 'queries';
import { SHARE_TOKEN_HEADER } from 'lib/constants';
@ -38,24 +37,23 @@ export function isValidToken(token, validation) {
return false;
}
export async function allowQuery(req, skipToken) {
const { id } = req.query;
const token = req.headers[SHARE_TOKEN_HEADER];
export async function allowQuery(req) {
const { id: websiteId } = req.query;
const website = await getWebsite(validate(id) ? { websiteUuid: id } : { id: +id });
const { userId, isAdmin, shareToken } = req.auth ?? {};
if (website) {
if (token && token !== 'undefined' && !skipToken) {
return isValidToken(token, { websiteId: website.id });
}
if (isAdmin) {
return true;
}
const authToken = await getAuthToken(req);
if (shareToken) {
return isValidToken(shareToken, { websiteUuid: websiteId });
}
if (authToken) {
const { userId, isAdmin } = authToken;
if (userId) {
const website = await getWebsite({ websiteUuid: websiteId });
return isAdmin || website.userId === userId;
}
return website && website.userId === userId;
}
return false;