umami/lib/session.js

97 lines
2.0 KiB
JavaScript
Raw Normal View History

import { parseToken } from 'next-basics';
import { validate } from 'uuid';
2022-10-07 00:00:16 +02:00
import { secret, uuid } from 'lib/crypto';
import cache from 'lib/cache';
2022-11-09 00:50:34 +01:00
import clickhouse from 'lib/clickhouse';
2022-12-28 05:20:44 +01:00
import { getClientInfo, getJsonBody } from 'lib/detect';
import { createSession, getSession, getWebsite } from 'queries';
export async function findSession(req) {
2022-03-11 04:01:33 +01:00
const { payload } = getJsonBody(req);
2020-08-09 08:48:43 +02:00
if (!payload) {
return null;
2020-08-09 08:48:43 +02:00
}
// Check if cache token is passed
const cacheToken = req.headers['x-umami-cache'];
2020-10-03 05:33:46 +02:00
if (cacheToken) {
const result = await parseToken(cacheToken, secret());
2020-10-03 05:33:46 +02:00
if (result) {
return result;
}
}
// Verify payload
2022-11-01 07:42:37 +01:00
const { website: websiteId, hostname, screen, language } = payload;
2022-08-26 08:12:47 +02:00
2022-11-01 07:42:37 +01:00
if (!validate(websiteId)) {
2022-08-29 05:20:54 +02:00
return null;
2020-08-12 05:05:40 +02:00
}
// Find website
let website;
2022-08-29 22:04:58 +02:00
if (cache.enabled) {
website = await cache.fetchWebsite(websiteId);
} else {
website = await getWebsite({ id: websiteId });
}
2022-12-07 03:36:41 +01:00
if (!website || website.deletedAt) {
2022-11-01 07:42:37 +01:00
throw new Error(`Website not found: ${websiteId}`);
2020-08-21 04:17:27 +02:00
}
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);
2022-11-01 07:42:37 +01:00
const sessionId = uuid(websiteId, hostname, ip, userAgent);
2020-08-12 05:05:40 +02:00
2022-11-09 02:11:08 +01:00
// Clickhouse does not require session lookup
if (clickhouse.enabled) {
return {
2022-11-09 00:50:34 +01:00
id: sessionId,
websiteId,
hostname,
browser,
os,
device,
screen,
language,
country,
};
}
2022-11-09 02:11:08 +01:00
// Find session
let session;
if (cache.enabled) {
session = await cache.fetchSession(sessionId);
} else {
session = await getSession({ id: sessionId });
}
// Create a session if not found
if (!session) {
try {
session = await createSession({
id: sessionId,
websiteId,
hostname,
browser,
os,
device,
screen,
language,
country,
});
} catch (e) {
if (!e.message.toLowerCase().includes('unique constraint')) {
throw e;
}
}
}
return session;
2020-08-05 07:45:05 +02:00
}