This commit is contained in:
Brian Cao 2022-10-31 23:42:37 -07:00
parent 246e4e5f4f
commit 17041efaae
73 changed files with 491 additions and 874 deletions

View file

@ -4,7 +4,7 @@ import { secret, uuid } from 'lib/crypto';
import redis, { DELETED } from 'lib/redis';
import clickhouse from 'lib/clickhouse';
import { getClientInfo, getJsonBody } from 'lib/request';
import { createSession, getSessionByUuid, getWebsite } from 'queries';
import { createSession, getSession as getSessionPrisma, getWebsite } from 'queries';
export async function getSession(req) {
const { payload } = getJsonBody(req);
@ -23,51 +23,51 @@ export async function getSession(req) {
}
}
const { website: websiteUuid, hostname, screen, language } = payload;
const { website: websiteId, hostname, screen, language } = payload;
if (!validate(websiteUuid)) {
if (!validate(websiteId)) {
return null;
}
let websiteId = null;
let isValidWebsite = null;
// Check if website exists
if (redis.enabled) {
websiteId = Number(await redis.get(`website:${websiteUuid}`));
isValidWebsite = await redis.get(`website:${websiteId}`);
}
// Check database if does not exists in Redis
if (!websiteId) {
const website = await getWebsite({ websiteUuid });
websiteId = website ? website.id : null;
if (!isValidWebsite) {
const website = await getWebsite({ id: websiteId });
isValidWebsite = !!website;
}
if (!websiteId || websiteId === DELETED) {
throw new Error(`Website not found: ${websiteUuid}`);
if (!isValidWebsite || isValidWebsite === DELETED) {
throw new Error(`Website not found: ${websiteId}`);
}
const { userAgent, browser, os, ip, country, device } = await getClientInfo(req, payload);
const sessionUuid = uuid(websiteUuid, hostname, ip, userAgent);
const sessionId = uuid(websiteId, hostname, ip, userAgent);
let sessionId = null;
let isValidSession = null;
let session = null;
if (!clickhouse.enabled) {
// Check if session exists
if (redis.enabled) {
sessionId = Number(await redis.get(`session:${sessionUuid}`));
isValidSession = await redis.get(`session:${sessionId}`);
}
// Check database if does not exists in Redis
if (!sessionId) {
session = await getSessionByUuid(sessionUuid);
sessionId = session ? session.id : null;
if (!isValidSession) {
session = await getSessionPrisma({ id: sessionId });
isValidSession = !!session;
}
if (!sessionId) {
if (!isValidSession) {
try {
session = await createSession(websiteId, {
sessionUuid,
id: sessionId,
hostname,
browser,
os,
@ -84,8 +84,7 @@ export async function getSession(req) {
}
} else {
session = {
sessionId,
sessionUuid,
id: sessionId,
hostname,
browser,
os,
@ -97,10 +96,7 @@ export async function getSession(req) {
}
return {
website: {
websiteId,
websiteUuid,
},
websiteId,
session,
};
}