]> git.immae.eu Git - github/Chocobozzz/PeerTube.git/blob - server/middlewares/rate-limiter.ts
Merge branch 'release/4.2.0' into develop
[github/Chocobozzz/PeerTube.git] / server / middlewares / rate-limiter.ts
1 import { UserRole } from '@shared/models'
2 import RateLimit from 'express-rate-limit'
3 import { optionalAuthenticate } from './auth'
4
5 const whitelistRoles = new Set([ UserRole.ADMINISTRATOR, UserRole.MODERATOR ])
6
7 function buildRateLimiter (options: {
8 windowMs: number
9 max: number
10 skipFailedRequests?: boolean
11 }) {
12 return RateLimit({
13 windowMs: options.windowMs,
14 max: options.max,
15 skipFailedRequests: options.skipFailedRequests,
16
17 handler: (req, res, next, options) => {
18 return optionalAuthenticate(req, res, () => {
19 if (res.locals.authenticated === true && whitelistRoles.has(res.locals.oauth.token.User.role)) {
20 return next()
21 }
22
23 return res.status(options.statusCode).send(options.message)
24 })
25 }
26 })
27 }
28
29 export {
30 buildRateLimiter
31 }