2022-10-12 06:48:33 +02:00
|
|
|
import { parseSecureToken, parseToken } from 'next-basics';
|
2022-10-06 23:18:27 +02:00
|
|
|
import { getWebsite } from 'queries';
|
2022-10-12 06:48:33 +02:00
|
|
|
import { SHARE_TOKEN_HEADER } from 'lib/constants';
|
|
|
|
import { secret } from 'lib/crypto';
|
2020-07-28 08:52:14 +02:00
|
|
|
|
2022-10-12 06:48:33 +02:00
|
|
|
export function getAuthToken(req) {
|
2022-01-23 09:32:17 +01:00
|
|
|
try {
|
|
|
|
const token = req.headers.authorization;
|
2020-07-28 08:52:14 +02:00
|
|
|
|
2022-08-29 05:20:54 +02:00
|
|
|
return parseSecureToken(token.split(' ')[1], secret());
|
2022-01-23 09:32:17 +01:00
|
|
|
} catch {
|
|
|
|
return null;
|
|
|
|
}
|
2020-08-05 07:45:05 +02:00
|
|
|
}
|
2020-09-18 07:52:20 +02:00
|
|
|
|
2022-10-12 06:48:33 +02:00
|
|
|
export function getShareToken(req) {
|
|
|
|
try {
|
|
|
|
return parseSecureToken(req.headers[SHARE_TOKEN_HEADER], secret());
|
|
|
|
} catch {
|
|
|
|
return null;
|
|
|
|
}
|
2022-08-30 05:57:34 +02:00
|
|
|
}
|
|
|
|
|
2022-10-12 06:48:33 +02:00
|
|
|
export function isValidToken(token, validation) {
|
2020-09-18 07:52:20 +02:00
|
|
|
try {
|
2022-08-29 05:20:54 +02:00
|
|
|
const result = parseToken(token, secret());
|
2020-09-18 07:52:20 +02:00
|
|
|
|
|
|
|
if (typeof validation === 'object') {
|
|
|
|
return !Object.keys(validation).find(key => result[key] !== validation[key]);
|
|
|
|
} else if (typeof validation === 'function') {
|
|
|
|
return validation(result);
|
|
|
|
}
|
|
|
|
} catch (e) {
|
|
|
|
return false;
|
|
|
|
}
|
|
|
|
|
|
|
|
return false;
|
|
|
|
}
|
|
|
|
|
2022-10-12 22:11:44 +02:00
|
|
|
export async function allowQuery(req) {
|
|
|
|
const { id: websiteId } = req.query;
|
2020-09-18 07:52:20 +02:00
|
|
|
|
2022-10-12 22:11:44 +02:00
|
|
|
const { userId, isAdmin, shareToken } = req.auth ?? {};
|
2020-09-18 07:52:20 +02:00
|
|
|
|
2022-10-12 22:11:44 +02:00
|
|
|
if (isAdmin) {
|
|
|
|
return true;
|
|
|
|
}
|
2020-09-18 07:52:20 +02:00
|
|
|
|
2022-10-12 22:11:44 +02:00
|
|
|
if (shareToken) {
|
|
|
|
return isValidToken(shareToken, { websiteUuid: websiteId });
|
|
|
|
}
|
2020-09-18 07:52:20 +02:00
|
|
|
|
2022-10-12 22:11:44 +02:00
|
|
|
if (userId) {
|
|
|
|
const website = await getWebsite({ websiteUuid: websiteId });
|
2020-09-18 07:52:20 +02:00
|
|
|
|
2022-10-12 22:11:44 +02:00
|
|
|
return website && website.userId === userId;
|
2020-09-18 07:52:20 +02:00
|
|
|
}
|
|
|
|
|
|
|
|
return false;
|
|
|
|
}
|