Switch to json web tokens.

This commit is contained in:
Mike Cao 2020-07-22 20:45:09 -07:00
parent 5219582803
commit cb0c912c5b
10 changed files with 202 additions and 86 deletions

View file

@ -1,50 +1,52 @@
import { getWebsite, getSession, createSession } from 'lib/db';
import { getCountry, getDevice, getIpAddress, isValidSession } from 'lib/utils';
import { hash } from 'lib/crypto';
import { getCountry, getDevice, getIpAddress } from 'lib/utils';
import { uuid, parseToken, isValidHash } from 'lib/crypto';
export default async req => {
const { payload } = req.body;
const { session } = payload;
const { website: website_uuid, hostname, screen, language, session } = payload;
if (isValidSession(session)) {
return session;
if (!isValidHash(website_uuid)) {
throw new Error(`Invalid website: ${website_uuid}`);
}
const ip = getIpAddress(req);
const { userAgent, browser, os } = getDevice(req);
const country = await getCountry(req, ip);
const { website: website_uuid, hostname, screen, language } = payload;
try {
return await parseToken(session);
} catch {
const ip = getIpAddress(req);
const { userAgent, browser, os } = getDevice(req);
const country = await getCountry(req, ip);
if (website_uuid) {
const website = await getWebsite(website_uuid);
if (website_uuid) {
const website = await getWebsite(website_uuid);
if (website) {
const { website_id } = website;
const session_uuid = hash(website_id, hostname, ip, userAgent, os);
if (website) {
const { website_id } = website;
const session_uuid = uuid(website_id, hostname, ip, userAgent, os);
let session = await getSession(session_uuid);
let session = await getSession(session_uuid);
if (!session) {
session = await createSession(website_id, {
if (!session) {
session = await createSession(website_id, {
session_uuid,
hostname,
browser,
os,
screen,
language,
country,
});
}
const { session_id } = session;
return {
website_id,
website_uuid,
session_id,
session_uuid,
hostname,
browser,
os,
screen,
language,
country,
});
};
}
const { session_id } = session;
return [
website_id,
website_uuid,
session_id,
session_uuid,
hash(website_id, website_uuid, session_id, session_uuid),
].join(':');
}
}
};