Add collect limits.

This commit is contained in:
Brian Cao 2022-12-31 13:42:03 -08:00
parent f42cab8d83
commit e487da72c3
13 changed files with 217 additions and 61 deletions

View file

@ -1,24 +1,40 @@
const { Resolver } = require('dns').promises;
import isbot from 'isbot';
import ipaddr from 'ipaddr.js';
import { createToken, unauthorized, send, badRequest, forbidden } from 'next-basics';
import {
createToken,
unauthorized,
send,
badRequest,
forbidden,
tooManyRequest,
} from 'next-basics';
import { savePageView, saveEvent } from 'queries';
import { useCors, useSession } from 'lib/middleware';
import { getJsonBody, getIpAddress } from 'lib/detect';
import { secret } from 'lib/crypto';
import { NextApiRequest, NextApiResponse } from 'next';
import cache from 'lib/cache';
import { Team, Website } from '@prisma/client';
export interface NextApiRequestCollect extends NextApiRequest {
session: {
id: string;
websiteId: string;
hostname: string;
browser: string;
os: string;
device: string;
screen: string;
language: string;
country: string;
error?: {
status: number;
message: string;
};
session?: {
id: string;
websiteId: string;
hostname: string;
browser: string;
os: string;
device: string;
screen: string;
language: string;
country: string;
};
website?: Website & { team?: Team };
};
}
@ -88,7 +104,21 @@ export default async (req: NextApiRequestCollect, res: NextApiResponse) => {
await useSession(req, res);
const session = req.session;
const { session, website } = req.session;
// Check collection limit
if (process.env.ENABLE_COLLECT_LIMIT) {
const userId = website.userId ? website.userId : website.team.userId;
const limit = await cache.fetchCollectLimit(userId);
// To-do: Need to implement logic to find user-specific limit. Defaulted to 10k.
if (limit > 10000) {
return tooManyRequest(res, 'Collect currently exceeds monthly limit of 10000.');
}
await cache.incrementCollectLimit(userId);
}
if (process.env.REMOVE_TRAILING_SLASH) {
url = url.replace(/\/$/, '');