umami/lib/session.js

97 lines
2 KiB
JavaScript
Raw Normal View History

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