rate-limiter.ts 804 B

12345678910111213141516171819202122232425262728293031
  1. import { UserRole } from '@shared/models'
  2. import RateLimit from 'express-rate-limit'
  3. import { optionalAuthenticate } from './auth'
  4. const whitelistRoles = new Set([ UserRole.ADMINISTRATOR, UserRole.MODERATOR ])
  5. function buildRateLimiter (options: {
  6. windowMs: number
  7. max: number
  8. skipFailedRequests?: boolean
  9. }) {
  10. return RateLimit({
  11. windowMs: options.windowMs,
  12. max: options.max,
  13. skipFailedRequests: options.skipFailedRequests,
  14. handler: (req, res, next, options) => {
  15. return optionalAuthenticate(req, res, () => {
  16. if (res.locals.authenticated === true && whitelistRoles.has(res.locals.oauth.token.User.role)) {
  17. return next()
  18. }
  19. return res.status(options.statusCode).send(options.message)
  20. })
  21. }
  22. })
  23. }
  24. export {
  25. buildRateLimiter
  26. }