Added CORS middleware. Updated umami script.

This commit is contained in:
Mike Cao 2020-07-18 10:36:46 -07:00
parent bb04015b46
commit 58a1c63407
10 changed files with 144 additions and 78 deletions

20
lib/middleware.js Normal file
View file

@ -0,0 +1,20 @@
import cors from 'cors';
export function use(middleware) {
return (req, res) =>
new Promise((resolve, reject) => {
middleware(req, res, result => {
if (result instanceof Error) {
return reject(result);
}
return resolve(result);
});
});
}
export const allowPost = use(
cors({
origin: '*',
methods: ['POST', 'OPTIONS'],
}),
);

View file

@ -61,48 +61,55 @@ export async function getCountry(req, ip) {
}
export async function parseSessionRequest(req) {
const ip = getIpAddress(req);
const { website_id, screen, language } = req.body;
const { userAgent, browser, os } = getDevice(req);
const country = await getCountry(req, ip);
const session_id = hash(`${website_id}${ip}${userAgent}${os}`);
if (req.method === 'POST') {
const ip = getIpAddress(req);
const { website_id, hostname, screen, language } = req.body;
const { userAgent, browser, os } = getDevice(req);
const country = await getCountry(req, ip);
const session_id = hash(`${website_id}${hostname}${ip}${userAgent}${os}`);
return {
website_id,
session_id,
browser,
os,
screen,
language,
country,
};
return {
website_id,
session_id,
hostname,
browser,
os,
screen,
language,
country,
};
}
return {};
}
export function parseCollectRequest(req) {
const { type, payload } = req.body;
if (req.method === 'POST') {
const { type, payload } = req.body;
if (payload.session) {
const {
url,
referrer,
session: { website_id, session_id, time, hash: validationHash },
} = payload;
if (
validHash(website_id) &&
validHash(session_id) &&
validHash(validationHash) &&
hash(`${website_id}${session_id}${time}`) === validationHash
) {
return {
valid: true,
type,
session_id,
if (payload.session) {
const {
url,
referrer,
};
session: { website_id, session_id, time, hash: validationHash },
} = payload;
if (
validHash(website_id) &&
validHash(session_id) &&
validHash(validationHash) &&
hash(`${website_id}${session_id}${time}`) === validationHash
) {
return {
success: 1,
type,
session_id,
url,
referrer,
};
}
}
}
return { valid: false };
return { success: 0 };
}