2022-10-12 06:48:33 +02:00
|
|
|
import { parseSecureToken, parseToken } from 'next-basics';
|
2022-10-26 01:50:12 +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;
|
|
|
|
}
|
|
|
|
|
2022-10-26 01:50:12 +02:00
|
|
|
export async function allowQuery(req, type) {
|
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
|
|
|
|
2022-10-12 22:11:44 +02:00
|
|
|
if (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-26 01:50:12 +02:00
|
|
|
if (type === TYPE_WEBSITE) {
|
|
|
|
const website = await getWebsite({ websiteUuid: id });
|
2020-09-18 07:52:20 +02:00
|
|
|
|
2022-10-26 01:50:12 +02:00
|
|
|
return website && website.userId === userId;
|
|
|
|
} else if (type === TYPE_ACCOUNT) {
|
|
|
|
const account = await getAccount({ accountUuid: id });
|
|
|
|
|
|
|
|
return account && account.accountUuid === id;
|
|
|
|
}
|
2020-09-18 07:52:20 +02:00
|
|
|
}
|
|
|
|
|
|
|
|
return false;
|
|
|
|
}
|