umami/lib/session.js

71 lines
1.5 KiB
JavaScript
Raw Normal View History

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