umami/lib/session.js

80 lines
1.7 KiB
JavaScript
Raw Normal View History

2022-07-12 23:14:36 +02:00
import { getWebsiteByUuid, getSessionByUuid, createSession } from 'queries';
2022-03-11 04:01:33 +01:00
import { getJsonBody, getClientInfo } from 'lib/request';
2020-10-03 05:33:46 +02:00
import { uuid, isValidUuid, parseToken } from 'lib/crypto';
2022-08-26 08:12:47 +02:00
import { runAnalyticsQuery } from 'lib/db';
import { RELATIONAL, CLICKHOUSE } from 'lib/constants';
export async function getSession(req) {
2022-03-11 04:01:33 +01:00
const { payload } = getJsonBody(req);
2020-08-09 08:48:43 +02:00
if (!payload) {
throw new Error('Invalid request');
}
2022-03-19 06:26:23 +01:00
const cache = req.headers['x-umami-cache'];
2020-10-03 05:33:46 +02:00
if (cache) {
const result = await parseToken(cache);
if (result) {
return result;
}
}
2022-08-26 08:12:47 +02:00
const { website: website_uuid, hostname, screen, language } = payload;
if (!isValidUuid(website_uuid)) {
2020-08-12 05:05:40 +02:00
throw new Error(`Invalid website: ${website_uuid}`);
}
2020-08-21 04:17:27 +02:00
const website = await getWebsiteByUuid(website_uuid);
2020-07-23 05:45:09 +02:00
2020-08-21 04:17:27 +02:00
if (!website) {
throw new Error(`Website not found: ${website_uuid}`);
}
2020-08-12 05:05:40 +02:00
2022-08-26 08:12:47 +02:00
const { userAgent, browser, os, ip, country, device } = await getClientInfo(req, payload);
2020-08-21 04:17:27 +02:00
const { website_id } = website;
2022-03-14 19:14:05 +01:00
const session_uuid = uuid(website_id, hostname, ip, userAgent);
2020-08-12 05:05:40 +02:00
2022-08-26 08:12:47 +02:00
// logic placeholder for redis
runAnalyticsQuery({
[RELATIONAL]: () => {},
[CLICKHOUSE]: () => {},
});
2020-08-12 05:05:40 +02:00
2022-08-26 08:12:47 +02:00
let session = await getSessionByUuid(session_uuid);
2022-08-26 07:04:32 +02:00
2020-08-21 04:17:27 +02:00
if (!session) {
2022-01-06 10:21:05 +01:00
try {
session = await createSession(website_id, {
session_uuid,
hostname,
browser,
os,
screen,
language,
country,
device,
});
} catch (e) {
if (!e.message.toLowerCase().includes('unique constraint')) {
2022-01-06 10:21:05 +01:00
throw e;
}
}
}
if (!session) {
return null;
}
2020-08-21 04:17:27 +02:00
const { session_id } = session;
return {
website_id,
session_id,
2022-07-22 23:43:19 +02:00
session_uuid,
2020-08-21 04:17:27 +02:00
};
2020-08-05 07:45:05 +02:00
}