umami/lib/session.js

54 lines
1.4 KiB
JavaScript
Raw Normal View History

import { getWebsite, getSession, createSession } from 'lib/db';
2020-08-07 02:14:44 +00:00
import { getClientInfo } from 'lib/request';
2020-07-24 02:56:55 +00:00
import { uuid, isValidId, verifyToken } from 'lib/crypto';
2020-08-05 05:45:05 +00:00
export async function verifySession(req) {
const { payload } = req.body;
2020-07-23 03:45:09 +00:00
const { website: website_uuid, hostname, screen, language, session } = payload;
2020-07-24 02:56:55 +00:00
if (!isValidId(website_uuid)) {
2020-07-23 03:45:09 +00:00
throw new Error(`Invalid website: ${website_uuid}`);
}
2020-07-23 03:45:09 +00:00
try {
2020-07-23 04:33:17 +00:00
return await verifyToken(session);
2020-07-23 03:45:09 +00:00
} catch {
2020-08-07 02:14:44 +00:00
const { userAgent, browser, os, ip, country, device } = await getClientInfo(req, payload);
2020-07-23 03:45:09 +00:00
if (website_uuid) {
2020-08-04 01:12:28 +00:00
const website = await getWebsite({ website_uuid });
2020-07-23 03:45:09 +00:00
if (website) {
const { website_id } = website;
const session_uuid = uuid(website_id, hostname, ip, userAgent, os);
2020-08-04 01:12:28 +00:00
let session = await getSession({ session_uuid });
2020-07-23 03:45:09 +00:00
if (!session) {
session = await createSession(website_id, {
session_uuid,
hostname,
browser,
os,
screen,
language,
country,
2020-08-07 02:14:44 +00:00
device,
2020-07-23 03:45:09 +00:00
});
}
const { session_id } = session;
return {
website_id,
website_uuid,
session_id,
session_uuid,
2020-07-23 03:45:09 +00:00
};
2020-07-28 06:52:14 +00:00
} else {
throw new Error(`Invalid website: ${website_uuid}`);
}
}
}
2020-08-05 05:45:05 +00:00
}