umami/lib/session.js

51 lines
1.2 KiB
JavaScript
Raw Normal View History

import { getWebsite, getSession, createSession } from 'lib/db';
2020-07-23 00:46:05 +02:00
import { getCountry, getDevice, getIpAddress, isValidSession } from 'lib/utils';
import { hash } from 'lib/crypto';
2020-07-21 04:24:33 +02:00
export default async req => {
const { payload } = req.body;
const { session } = payload;
if (isValidSession(session)) {
return session;
}
const ip = getIpAddress(req);
const { userAgent, browser, os } = getDevice(req);
const country = await getCountry(req, ip);
const { website: website_uuid, hostname, screen, language } = payload;
if (website_uuid) {
const website = await getWebsite(website_uuid);
if (website) {
const { website_id } = website;
2020-07-21 04:24:33 +02:00
const session_uuid = hash(website_id, hostname, ip, userAgent, os);
let session = await getSession(session_uuid);
if (!session) {
session = await createSession(website_id, {
session_uuid,
hostname,
browser,
os,
screen,
language,
country,
});
}
const { session_id } = session;
return [
website_id,
website_uuid,
session_id,
session_uuid,
hash(website_id, website_uuid, session_id, session_uuid),
].join(':');
}
}
2020-07-21 04:24:33 +02:00
};