aboutsummaryrefslogtreecommitdiffhomepage
path: root/server/middlewares/rate-limiter.ts
blob: bc95139693192d8d25811031c56d970482169307 (plain) (blame)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
import { UserRole } from '@shared/models'
import RateLimit from 'express-rate-limit'
import { optionalAuthenticate } from './auth'

const whitelistRoles = new Set([ UserRole.ADMINISTRATOR, UserRole.MODERATOR ])

function buildRateLimiter (options: {
  windowMs: number
  max: number
  skipFailedRequests?: boolean
}) {
  return RateLimit({
    windowMs: options.windowMs,
    max: options.max,
    skipFailedRequests: options.skipFailedRequests,

    handler: (req, res, next, options) => {
      return optionalAuthenticate(req, res, () => {
        if (res.locals.authenticated === true && whitelistRoles.has(res.locals.oauth.token.User.role)) {
          return next()
        }

        return res.status(options.statusCode).send(options.message)
      })
    }
  })
}

export {
  buildRateLimiter
}