2022-08-30 05:57:34 +02:00
|
|
|
import { parseSecureToken, parseToken, getItem } from 'next-basics';
|
|
|
|
import { AUTH_TOKEN, SHARE_TOKEN_HEADER } from './constants';
|
2022-07-13 00:14:27 +02:00
|
|
|
import { getWebsiteById } from 'queries';
|
2022-08-29 05:20:54 +02:00
|
|
|
import { secret } from './crypto';
|
2020-07-28 08:52:14 +02:00
|
|
|
|
2020-09-18 07:52:20 +02:00
|
|
|
export async 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-08-30 05:57:34 +02:00
|
|
|
export function getAuthHeader() {
|
|
|
|
const token = getItem(AUTH_TOKEN);
|
|
|
|
|
|
|
|
return token ? { authorization: `Bearer ${token}` } : {};
|
|
|
|
}
|
|
|
|
|
2020-09-18 07:52:20 +02:00
|
|
|
export async function isValidToken(token, validation) {
|
|
|
|
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;
|
|
|
|
}
|
|
|
|
|
|
|
|
export async function allowQuery(req, skipToken) {
|
2020-10-11 11:29:55 +02:00
|
|
|
const { id } = req.query;
|
2022-05-06 04:04:28 +02:00
|
|
|
const token = req.headers[SHARE_TOKEN_HEADER];
|
2020-09-18 07:52:20 +02:00
|
|
|
const websiteId = +id;
|
|
|
|
|
|
|
|
const website = await getWebsiteById(websiteId);
|
|
|
|
|
|
|
|
if (website) {
|
2020-10-13 01:31:51 +02:00
|
|
|
if (token && token !== 'undefined' && !skipToken) {
|
2020-09-18 07:52:20 +02:00
|
|
|
return isValidToken(token, { website_id: websiteId });
|
|
|
|
}
|
|
|
|
|
|
|
|
const authToken = await getAuthToken(req);
|
|
|
|
|
|
|
|
if (authToken) {
|
|
|
|
const { user_id, is_admin } = authToken;
|
|
|
|
|
|
|
|
return is_admin || website.user_id === user_id;
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
return false;
|
|
|
|
}
|