umami/pages/api/collect.js

64 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';
2021-03-13 07:44:25 +01:00
import { getIpAddress } from 'lib/request';
import { ok, 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);
}
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);
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 {
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
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 });
return ok(res, token);
2020-07-17 10:03:38 +02:00
};