2020-07-28 08:52:14 +02:00
|
|
|
import { parse } from 'cookie';
|
2020-09-18 07:52:20 +02:00
|
|
|
import { parseSecureToken, parseToken } from './crypto';
|
2020-08-05 07:45:05 +02:00
|
|
|
import { AUTH_COOKIE_NAME } from './constants';
|
2020-09-18 07:52:20 +02:00
|
|
|
import { getWebsiteById } from './queries';
|
2020-07-28 08:52:14 +02:00
|
|
|
|
2020-09-18 07:52:20 +02:00
|
|
|
export async function getAuthToken(req) {
|
2020-08-05 07:45:05 +02:00
|
|
|
const token = parse(req.headers.cookie || '')[AUTH_COOKIE_NAME];
|
2020-07-28 08:52:14 +02:00
|
|
|
|
2020-08-08 02:19:42 +02:00
|
|
|
return parseSecureToken(token);
|
2020-08-05 07:45:05 +02:00
|
|
|
}
|
2020-09-18 07:52:20 +02:00
|
|
|
|
|
|
|
export async function isValidToken(token, validation) {
|
|
|
|
try {
|
|
|
|
const result = await parseToken(token);
|
|
|
|
|
|
|
|
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) {
|
|
|
|
const { id, token } = req.query;
|
|
|
|
const websiteId = +id;
|
|
|
|
|
|
|
|
const website = await getWebsiteById(websiteId);
|
|
|
|
|
|
|
|
if (website) {
|
|
|
|
if (token && !skipToken) {
|
|
|
|
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;
|
|
|
|
}
|