umami/pages/api/collect.js

66 lines
1.6 KiB
JavaScript
Raw Normal View History

2021-03-13 07:44:25 +01:00
import isbot from 'isbot';
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';
2022-03-11 04:01:33 +01:00
import { getJsonBody, getIpAddress } from 'lib/request';
2022-03-11 05:39:11 +01:00
import { ok, send, badRequest } from 'lib/response';
2020-10-03 05:33:46 +02:00
import { createToken } from 'lib/crypto';
import { removeTrailingSlash } from 'lib/url';
2020-07-17 10:03:38 +02:00
export default async (req, res) => {
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);
}
2022-04-10 12:51:43 +02:00
const ignoreIps = process.env.IGNORE_IP;
if (ignoreIps) {
const ips = ignoreIps.split(',').map(n => n.trim());
2020-10-04 04:07:56 +02:00
const ip = getIpAddress(req);
const blocked = ips.find(i => {
if (i === ip) return true;
2020-10-04 04:07:56 +02:00
// CIDR notation
if (i.indexOf('/') > 0) {
const addr = ipaddr.parse(ip);
const range = ipaddr.parseCIDR(i);
if (addr.kind() === range[0].kind() && addr.match(range)) return true;
}
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-08-21 04:17:27 +02:00
const {
session: { website_id, session_id },
} = req;
2020-07-17 10:03:38 +02:00
2022-03-11 04:01:33 +01:00
const { type, payload } = getJsonBody(req);
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
if (type === 'pageview') {
2020-07-24 04:56:55 +02:00
await savePageView(website_id, session_id, url, referrer);
} else if (type === 'event') {
2020-07-24 04:56:55 +02:00
await saveEvent(website_id, session_id, url, event_type, event_value);
} 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 });
2022-03-11 05:39:11 +01:00
return send(res, token);
2020-07-17 10:03:38 +02:00
};