Refactored session and collect process.

This commit is contained in:
Mike Cao 2020-07-20 01:54:21 -07:00
parent e58aa9e90f
commit 132bbcbe0d
7 changed files with 192 additions and 252 deletions

View file

@ -12,8 +12,8 @@ export function md5(s) {
return crypto.createHash('md5').update(s).digest('hex');
}
export function hash(s) {
return uuid(s, md5(process.env.HASH_SALT));
export function hash(...args) {
return uuid(args.join(''), md5(process.env.HASH_SALT));
}
export function validHash(s) {
@ -60,61 +60,19 @@ export async function getCountry(req, ip) {
return result.country.iso_code;
}
export async function parseSessionRequest(req) {
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,
hostname,
browser,
os,
screen,
language,
country,
};
}
return {};
export function parseSession(session) {
const [website_id, website_uuid, session_id, session_uuid, sig] = (session || '').split(':');
return {
website_id: parseInt(website_id),
website_uuid,
session_id: parseInt(session_id),
session_uuid,
sig,
};
}
export function parseCollectRequest(req) {
if (req.method === 'POST') {
const { type, payload } = req.body;
export function isValidSession(session) {
const { website_id, website_uuid, session_id, session_uuid, sig } = parseSession(session);
if (payload.session) {
const {
url,
referrer,
event_type,
event_value,
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,
website_id,
session_id,
url,
referrer,
event_type,
event_value,
};
}
}
}
return { success: 0 };
return hash(website_id, website_uuid, session_id, session_uuid) === sig;
}