Initial commit.

This commit is contained in:
Mike Cao 2020-07-17 01:03:38 -07:00
commit f7f0c05e12
27 changed files with 13028 additions and 0 deletions

65
lib/db.js Normal file
View file

@ -0,0 +1,65 @@
import { PrismaClient } from '@prisma/client';
const prisma = new PrismaClient();
export async function runQuery(query) {
return query
.catch(e => {
throw e;
})
.finally(async () => {
await prisma.disconnect();
});
}
export async function getWebsite(website_id) {
return runQuery(
prisma.website.findOne({
where: {
website_id,
},
}),
);
}
export async function createSession(website_id, session_id, data) {
await runQuery(
prisma.session.create({
data: {
session_id,
website: {
connect: {
website_id,
},
},
...data,
},
}),
);
}
export async function getSession(session_id) {
return runQuery(
prisma.session.findOne({
where: {
session_id,
},
}),
);
}
export async function savePageView(session_id, url, referrer) {
return runQuery(
prisma.pageview.create({
data: {
session: {
connect: {
session_id,
},
},
url,
referrer,
},
}),
);
}

72
lib/utils.js Normal file
View file

@ -0,0 +1,72 @@
import crypto from 'crypto';
import { v5 as uuid } from 'uuid';
import requestIp from 'request-ip';
import { browserName, detectOS } from 'detect-browser';
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 getIpAddress(req) {
if (req.headers['cf-connecting-ip']) {
return req.headers['cf-connecting-ip'];
}
return requestIp.getClientIp(req);
}
export function getDevice(req) {
const userAgent = req.headers['user-agent'];
const browser = browserName(userAgent);
const os = detectOS(userAgent);
return { userAgent, browser, os };
}
export function getCountry(req) {
return req.headers['cf-ipcountry'];
}
export function parseSessionRequest(req) {
const ip = getIpAddress(req);
const { website_id, screen, language } = JSON.parse(req.body);
const { userAgent, browser, os } = getDevice(req);
const country = getCountry(req);
const session_id = hash(`${website_id}${ip}${userAgent}${os}`);
return {
website_id,
session_id,
browser,
os,
screen,
language,
country,
};
}
export function parseCollectRequest(req) {
const { type, payload } = JSON.parse(req.body);
if (payload.session) {
const {
url,
referrer,
session: { website_id, session_id, time, hash: validationHash },
} = payload;
if (hash(`${website_id}${session_id}${time}`) === validationHash) {
return {
type,
session_id,
url,
referrer,
};
}
}
return null;
}