umami/lib/session.js

89 lines
2.1 KiB
JavaScript
Raw Normal View History

import { isValidUuid, parseToken, uuid } from 'lib/crypto';
import redis from 'lib/redis';
import { getClientInfo, getJsonBody } from 'lib/request';
import { createSession, getSessionByUuid, getWebsiteByUuid } from 'queries';
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 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;
}
}
2022-08-26 06:12:47 +00:00
const { website: website_uuid, hostname, screen, language } = payload;
if (!isValidUuid(website_uuid)) {
2020-08-12 03:05:40 +00:00
throw new Error(`Invalid website: ${website_uuid}`);
}
let websiteId = null;
2020-07-23 03:45:09 +00:00
// Check if website exists
if (process.env.REDIS_URL) {
websiteId = await redis.get(`website:${website_uuid}`);
} else {
const { website_id } = await getWebsiteByUuid(website_uuid);
websiteId = website_id;
}
if (!websiteId) {
2020-08-21 02:17:27 +00:00
throw new Error(`Website not found: ${website_uuid}`);
}
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);
const session_uuid = uuid(websiteId, hostname, ip, userAgent);
2020-08-12 03:05:40 +00:00
let sessionCreated = false;
let sessionId = null;
let session = null;
2020-08-12 03:05:40 +00:00
// Check if session exists
if (process.env.REDIS_URL) {
sessionCreated = (await redis.get(`session:${session_uuid}`)) !== null;
} else {
console.log('test');
session = await getSessionByUuid(session_uuid);
sessionCreated = !!session;
sessionId = session ? session.session_id : null;
}
2022-08-26 05:04:32 +00:00
if (!sessionCreated) {
2022-01-06 09:21:05 +00:00
try {
console.log('test2');
session = await createSession(websiteId, {
2022-01-06 09:21:05 +00:00
session_uuid,
hostname,
browser,
os,
screen,
language,
country,
device,
});
sessionId = session ? session.session_id : null;
2022-01-06 09:21:05 +00:00
} catch (e) {
if (!e.message.toLowerCase().includes('unique constraint')) {
2022-01-06 09:21:05 +00:00
throw e;
}
}
}
2020-08-21 02:17:27 +00:00
return {
website_id: websiteId,
session_id: sessionId,
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
}