2021-03-13 07:44:25 +01:00
|
|
|
import isbot from 'isbot';
|
2021-04-26 08:57:49 +02:00
|
|
|
import ipaddr from 'ipaddr.js';
|
2020-08-12 07:24:41 +02:00
|
|
|
import { savePageView, saveEvent } from 'lib/queries';
|
2020-07-28 08:52:14 +02:00
|
|
|
import { useCors, useSession } from 'lib/middleware';
|
2021-03-13 07:44:25 +01:00
|
|
|
import { getIpAddress } from 'lib/request';
|
2020-08-08 02:19:42 +02:00
|
|
|
import { ok, badRequest } from 'lib/response';
|
2020-10-03 05:33:46 +02:00
|
|
|
import { createToken } from 'lib/crypto';
|
2022-01-26 06:23:40 +01:00
|
|
|
import { removeTrailingSlash } from 'lib/url';
|
2020-07-17 10:03:38 +02:00
|
|
|
|
|
|
|
export default async (req, res) => {
|
2020-10-09 19:48:47 +02:00
|
|
|
await useCors(req, res);
|
|
|
|
|
2021-03-13 07:44:25 +01:00
|
|
|
if (isbot(req.headers['user-agent'])) {
|
2020-09-11 05:37:07 +02:00
|
|
|
return ok(res);
|
|
|
|
}
|
|
|
|
|
2020-10-04 04:07:56 +02:00
|
|
|
if (process.env.IGNORE_IP) {
|
|
|
|
const ips = process.env.IGNORE_IP.split(',').map(n => n.trim());
|
|
|
|
const ip = getIpAddress(req);
|
2021-04-26 08:57:49 +02:00
|
|
|
const blocked = ips.find(i => {
|
|
|
|
if (i === ip) return true;
|
2020-10-04 04:07:56 +02:00
|
|
|
|
2021-04-26 08:57:49 +02:00
|
|
|
// CIDR notation
|
|
|
|
if (i.indexOf('/') > 0) {
|
|
|
|
const addr = ipaddr.parse(ip);
|
|
|
|
const range = ipaddr.parseCIDR(i);
|
|
|
|
|
2021-08-11 14:31:32 +02:00
|
|
|
if (addr.kind() === range[0].kind() && addr.match(range)) return true;
|
2021-04-26 08:57:49 +02:00
|
|
|
}
|
|
|
|
|
|
|
|
return false;
|
|
|
|
});
|
|
|
|
|
|
|
|
if (blocked) {
|
2020-10-04 04:07:56 +02:00
|
|
|
return ok(res);
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
2020-07-28 08:52:14 +02:00
|
|
|
await useSession(req, res);
|
2020-07-18 19:36:46 +02:00
|
|
|
|
2020-08-21 04:17:27 +02:00
|
|
|
const {
|
2022-01-26 06:23:40 +01:00
|
|
|
body: { type, payload },
|
2020-08-21 04:17:27 +02:00
|
|
|
session: { website_id, session_id },
|
|
|
|
} = req;
|
2020-07-17 10:03:38 +02:00
|
|
|
|
2022-01-26 06:23:40 +01:00
|
|
|
let { url, referrer, event_type, event_value } = payload;
|
|
|
|
|
|
|
|
if (process.env.REMOVE_TRAILING_SLASH) {
|
|
|
|
url = removeTrailingSlash(url);
|
|
|
|
}
|
2020-07-24 04:56:55 +02:00
|
|
|
|
2022-01-26 06:23:40 +01:00
|
|
|
if (type === 'pageview') {
|
2020-07-24 04:56:55 +02:00
|
|
|
await savePageView(website_id, session_id, url, referrer);
|
2020-07-20 10:54:21 +02:00
|
|
|
} else if (type === 'event') {
|
2020-07-24 04:56:55 +02:00
|
|
|
await saveEvent(website_id, session_id, url, event_type, event_value);
|
2020-08-08 02:19:42 +02:00
|
|
|
} else {
|
|
|
|
return badRequest(res);
|
2020-07-24 04:56:55 +02:00
|
|
|
}
|
2020-07-23 05:45:09 +02:00
|
|
|
|
2020-10-03 05:33:46 +02:00
|
|
|
const token = await createToken({ website_id, session_id });
|
|
|
|
|
|
|
|
return ok(res, token);
|
2020-07-17 10:03:38 +02:00
|
|
|
};
|