Refactor API authentication.
This commit is contained in:
26
lib/auth.js
26
lib/auth.js
@@ -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;
|
||||
|
||||
Reference in New Issue
Block a user