2020-08-12 07:24:41 +02:00
|
|
|
import { getWebsiteByUuid, getSessionByUuid, createSession } from 'lib/queries';
|
2020-08-07 04:14:44 +02:00
|
|
|
import { getClientInfo } from 'lib/request';
|
2020-09-18 07:52:20 +02:00
|
|
|
import { uuid, isValidUuid } from 'lib/crypto';
|
2020-07-20 10:54:21 +02:00
|
|
|
|
2020-09-18 07:52:20 +02:00
|
|
|
export async function getSession(req) {
|
2020-07-20 10:54:21 +02:00
|
|
|
const { payload } = req.body;
|
2020-08-09 08:48:43 +02:00
|
|
|
|
|
|
|
if (!payload) {
|
|
|
|
throw new Error('Invalid request');
|
|
|
|
}
|
|
|
|
|
2020-08-21 04:17:27 +02:00
|
|
|
const { website: website_uuid, hostname, screen, language } = payload;
|
2020-07-20 10:54:21 +02:00
|
|
|
|
2020-09-18 07:52:20 +02:00
|
|
|
if (!isValidUuid(website_uuid)) {
|
2020-08-12 05:05:40 +02:00
|
|
|
throw new Error(`Invalid website: ${website_uuid}`);
|
|
|
|
}
|
|
|
|
|
2020-08-21 04:17:27 +02:00
|
|
|
const { userAgent, browser, os, ip, country, device } = await getClientInfo(req, payload);
|
2020-08-19 08:35:26 +02:00
|
|
|
|
2020-08-21 04:17:27 +02:00
|
|
|
const website = await getWebsiteByUuid(website_uuid);
|
2020-07-23 05:45:09 +02:00
|
|
|
|
2020-08-21 04:17:27 +02:00
|
|
|
if (!website) {
|
|
|
|
throw new Error(`Website not found: ${website_uuid}`);
|
|
|
|
}
|
2020-08-12 05:05:40 +02:00
|
|
|
|
2020-08-21 04:17:27 +02:00
|
|
|
const { website_id } = website;
|
|
|
|
const session_uuid = uuid(website_id, hostname, ip, userAgent, os);
|
2020-08-12 05:05:40 +02:00
|
|
|
|
2020-08-21 04:17:27 +02:00
|
|
|
let session = await getSessionByUuid(session_uuid);
|
2020-08-12 05:05:40 +02:00
|
|
|
|
2020-08-21 04:17:27 +02:00
|
|
|
if (!session) {
|
|
|
|
session = await createSession(website_id, {
|
2020-08-12 05:05:40 +02:00
|
|
|
session_uuid,
|
2020-08-21 04:17:27 +02:00
|
|
|
hostname,
|
|
|
|
browser,
|
|
|
|
os,
|
|
|
|
screen,
|
|
|
|
language,
|
|
|
|
country,
|
|
|
|
device,
|
|
|
|
});
|
2020-07-20 10:54:21 +02:00
|
|
|
}
|
2020-08-08 02:19:42 +02:00
|
|
|
|
2020-08-21 04:17:27 +02:00
|
|
|
const { session_id } = session;
|
|
|
|
|
|
|
|
return {
|
|
|
|
website_id,
|
|
|
|
session_id,
|
|
|
|
};
|
2020-08-05 07:45:05 +02:00
|
|
|
}
|