1
0
mirror of https://github.com/kremalicious/umami.git synced 2024-12-23 01:30:05 +01:00
umami/pages/api/collect.js

47 lines
1.1 KiB
JavaScript
Raw Normal View History

2020-10-03 05:33:46 +02:00
import isBot from 'isbot-fast';
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';
import { ok, badRequest } from 'lib/response';
2020-10-03 05:33:46 +02:00
import { createToken } from 'lib/crypto';
2020-10-04 04:07:56 +02:00
import { getIpAddress } from '../../lib/request';
2020-07-17 10:03:38 +02:00
export default async (req, res) => {
await useCors(req, res);
2020-09-11 05:37:07 +02:00
if (isBot(req.headers['user-agent'])) {
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);
if (ips.includes(ip)) {
return ok(res);
}
}
2020-07-28 08:52:14 +02:00
await useSession(req, res);
const { type, payload } = req.body;
2020-08-21 04:17:27 +02:00
const {
session: { website_id, session_id },
} = req;
2020-07-17 10:03:38 +02:00
if (type === 'pageview') {
const { url, referrer } = payload;
2020-07-24 04:56:55 +02:00
await savePageView(website_id, session_id, url, referrer);
} else if (type === 'event') {
const { url, event_type, event_value } = payload;
2020-07-17 10:03:38 +02:00
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
};