2022-10-12 06:48:33 +02:00
|
|
|
import { parseSecureToken, parseToken } from 'next-basics';
|
2022-10-25 19:45:56 +02:00
|
|
|
import { getAccount, getWebsite } from 'queries';
|
|
|
|
import { SHARE_TOKEN_HEADER, TYPE_ACCOUNT, TYPE_WEBSITE } from 'lib/constants';
|
2022-10-12 06:48:33 +02:00
|
|
|
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 {
|
2022-10-25 04:48:10 +02:00
|
|
|
return parseToken(req.headers[SHARE_TOKEN_HEADER], secret());
|
2022-10-12 06:48:33 +02:00
|
|
|
} 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 {
|
|
|
|
if (typeof validation === 'object') {
|
2022-10-25 04:48:10 +02:00
|
|
|
return !Object.keys(validation).find(key => token[key] !== validation[key]);
|
2020-09-18 07:52:20 +02:00
|
|
|
} else if (typeof validation === 'function') {
|
2022-10-25 04:48:10 +02:00
|
|
|
return validation(token);
|
2020-09-18 07:52:20 +02:00
|
|
|
}
|
|
|
|
} catch (e) {
|
|
|
|
return false;
|
|
|
|
}
|
|
|
|
|
|
|
|
return false;
|
|
|
|
}
|
|
|
|
|
2023-01-19 00:09:49 +01:00
|
|
|
export async function allowQuery(req, type, allowShareToken = true) {
|
2022-10-25 04:48:10 +02:00
|
|
|
const { id } = 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
|
|
|
|
2023-01-19 00:09:49 +01:00
|
|
|
if (allowShareToken && shareToken) {
|
2022-10-25 04:48:10 +02:00
|
|
|
return isValidToken(shareToken, { id });
|
2022-10-12 22:11:44 +02:00
|
|
|
}
|
2020-09-18 07:52:20 +02:00
|
|
|
|
2022-10-12 22:11:44 +02:00
|
|
|
if (userId) {
|
2022-10-25 19:45:56 +02:00
|
|
|
if (type === TYPE_WEBSITE) {
|
|
|
|
const website = await getWebsite({ websiteUuid: id });
|
2020-09-18 07:52:20 +02:00
|
|
|
|
2022-10-25 19:45:56 +02:00
|
|
|
return website && website.userId === userId;
|
|
|
|
} else if (type === TYPE_ACCOUNT) {
|
|
|
|
const account = await getAccount({ accountUuid: id });
|
|
|
|
|
2022-10-25 20:01:28 +02:00
|
|
|
return account && account.accountUuid === id;
|
2022-10-25 19:45:56 +02:00
|
|
|
}
|
2020-09-18 07:52:20 +02:00
|
|
|
}
|
|
|
|
|
|
|
|
return false;
|
|
|
|
}
|