Repository navigation
Expand file tree
/
Copy pathsession.js
More file actions
96 lines (80 loc) · 2 KB
/
Copy pathsession.js
File metadata and controls
96 lines (80 loc) · 2 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
import { parseToken } from 'next-basics';
import { validate } from 'uuid';
import { secret, uuid } from 'lib/crypto';
import cache from 'lib/cache';
import clickhouse from 'lib/clickhouse';
import { getClientInfo, getJsonBody } from 'lib/request';
import { createSession, getSession, getWebsite } from 'queries';
export async function findSession(req) {
const { payload } = getJsonBody(req);
if (!payload) {
return null;
}
// Check if cache token is passed
const cacheToken = req.headers['x-umami-cache'];
if (cacheToken) {
const result = await parseToken(cacheToken, secret());
if (result) {
return result;
}
}
// Verify payload
const { website: websiteId, hostname, screen, language } = payload;
if (!validate(websiteId)) {
return null;
}
// Find website
let website;
if (cache.enabled) {
website = await cache.fetchWebsite(websiteId);
} else {
website = await getWebsite({ id: websiteId });
}
if (!website || website.deletedAt) {
throw new Error(`Website not found: ${websiteId}`);
}
const { userAgent, browser, os, ip, country, device } = await getClientInfo(req, payload);
const sessionId = uuid(websiteId, hostname, ip, userAgent);
// Clickhouse does not require session lookup
if (clickhouse.enabled) {
return {
id: sessionId,
websiteId,
hostname,
browser,
os,
device,
screen,
language,
country,
};
}
// 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;
}