umami/src/lib/session.ts

93 lines
2.1 KiB
TypeScript
Raw Normal View History

import { secret, uuid, visitSalt } from 'lib/crypto';
2023-08-30 23:40:32 +00:00
import { getClientInfo } from 'lib/detect';
2023-07-29 00:21:34 +00:00
import { parseToken } from 'next-basics';
2023-08-30 23:40:32 +00:00
import { NextApiRequestCollect } from 'pages/api/send';
2023-04-02 00:38:35 +00:00
import { createSession } from 'queries';
2023-08-23 18:55:45 +00:00
import clickhouse from './clickhouse';
2024-04-26 07:31:38 +00:00
import { fetchSession, fetchWebsite } from './load';
2024-04-18 21:23:14 +00:00
import { SessionData } from 'lib/types';
2024-04-18 21:23:14 +00:00
export async function getSession(req: NextApiRequestCollect): Promise<SessionData> {
2023-08-30 23:40:32 +00:00
const { payload } = req.body;
2020-08-09 06:48:43 +00:00
if (!payload) {
throw new Error('Invalid payload.');
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
2024-04-18 21:23:14 +00:00
// Token is valid
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
// Find website
2024-04-26 07:31:38 +00:00
const website = await fetchWebsite(websiteId);
2022-08-29 20:04:58 +00:00
2023-04-02 00:38:35 +00:00
if (!website) {
throw new Error(`Website not found: ${websiteId}.`);
2020-08-21 02:17:27 +00:00
}
2020-08-12 03:05:40 +00:00
const { userAgent, browser, os, ip, country, subdivision1, subdivision2, city, device } =
await getClientInfo(req);
2020-08-12 03:05:40 +00:00
const sessionId = uuid(websiteId, hostname, ip, userAgent);
const visitId = uuid(sessionId, visitSalt());
2023-08-23 18:55:45 +00:00
// Clickhouse does not require session lookup
if (clickhouse.enabled) {
return {
id: sessionId,
websiteId,
visitId,
2023-08-23 18:55:45 +00:00
hostname,
browser,
2024-04-18 21:23:14 +00:00
os,
2023-08-23 18:55:45 +00:00
device,
screen,
language,
country,
subdivision1,
subdivision2,
city,
};
}
2022-11-09 01:11:08 +00:00
// Find session
let session = await fetchSession(websiteId, sessionId);
2022-11-09 01:11:08 +00:00
// Create a session if not found
if (!session) {
try {
session = await createSession({
id: sessionId,
websiteId,
hostname,
browser,
os,
device,
screen,
language,
country,
subdivision1,
subdivision2,
city,
2022-11-09 01:11:08 +00:00
});
2023-03-30 18:18:57 +00:00
} catch (e: any) {
2022-11-09 01:11:08 +00:00
if (!e.message.toLowerCase().includes('unique constraint')) {
throw e;
}
}
}
return { ...session, visitId: visitId };
2020-08-05 05:45:05 +00:00
}