{"size": 1862, "ext": "js", "max_stars_repo_path": "lib/reqHandlers/rateLimiters.js", "max_stars_repo_name": "a1ananth/loki", "max_stars_repo_stars_event_min_datetime": "2022-01-15T12:31:39.000Z", "max_stars_repo_stars_event_max_datetime": "2022-01-15T12:31:39.000Z", "max_issues_repo_path": "lib/reqHandlers/rateLimiters.js", "max_issues_repo_name": "a1ananth/loki", "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "lib/reqHandlers/rateLimiters.js", "max_forks_repo_name": "a1ananth/loki", "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null}
{"max_stars_count": 1, "max_issues_count": null, "max_forks_count": null, "avg_line_length": 30.5245901639, "max_line_length": 113, "alphanum_fraction": 0.67132116}
import RateLimit from 'express-rate-limit';
import RedisStore from 'rate-limit-redis';
import createRedisClient from '../../redis';
import Logger from '../../logger';

const redisClient = createRedisClient('For IP Based Rate Limiting');
const store = new RedisStore({
  client: redisClient,
  prefix: 'rate-limiter',
});

export const ipBasedLimiter = RateLimit({
  store,
  windowMs: 10 * 1000, // for every 10 seconds
  max: 50, // for every 10 second maximum 50 request is allowed
  message: "We are currently receiving unusual traffic from this IP address, please try again after some time",
  keyGenerator: (req) => {
    return req.ip;
  },
  handler: (req, res, next) => {
    // TODO Send email to notify administrator about this

    const err = new Error('Unusual traffic detected from an IP address');
    err.status = 429;
    err.customMsg = 'Too many requests, please try again later';
    Logger.warn('Unusual traffic detected from IP address', req.ip);
    return next(err);
  },
});

export const userIdBasedLimiter = RateLimit({
  store,
  windowMs: 10 * 1000, // for every 10 second
  max: 50, // for every 10 second maximum 50 request is allowed
  message: "We are currently receiving unusual traffic from your user account, please try again after some time",
  keyGenerator: (req) => {
    if (!req.user) {
      return req.ip;
    }

    return req.user._id.toString();
  },
  handler: (req, res, next) => {
    // TODO Send email to notify administrator about this

    let key;
    if (!req.user) {
      key = req.ip;
    } else {
      key = req.user._id.toString();
    }

    const err = new Error('Unusual traffic detected from a User account');
    err.status = 429;
    err.customMsg = 'Too many requests, please try again later';
    Logger.warn('Unusual traffic detected from User account', key);
    return next(err);
  },
});

