Skip to content

Commit 59edfe4

Browse files
committed
updates to rate limiter
1 parent 529529d commit 59edfe4

File tree

1 file changed

+7
-10
lines changed

1 file changed

+7
-10
lines changed

src/utils/rateLimiter.ts

Lines changed: 7 additions & 10 deletions
Original file line numberDiff line numberDiff line change
@@ -3,28 +3,25 @@ import { Request } from 'express-jwt' // this ideally should come after the cust
33
import { logger } from './logger.js'
44
import { Response } from 'express'
55

6-
// Look for specific sub claims to determine if regular JWT or Keycloak specific OAuth was used
7-
function oauthUsed(req: Request): boolean {
6+
function isAuthenticated(req: Request): boolean {
87
return Boolean(req.auth?.sub || req?.kauth?.grant?.access_token?.content?.sub)
98
}
109

11-
function getUserId(req: Request): string {
12-
return req.auth?.sub
13-
? `session-${req.auth.sub}`
14-
: req.kauth?.grant?.access_token?.content?.sub ?? `anon-session-${req.ip}`
10+
function getSessionId(req: Request): string {
11+
return req.auth?.sub ? `session-${req.auth.sub}` : (req.kauth?.grant?.access_token?.content?.sub ?? `anon-session-${req.ip}`)
1512
}
1613

17-
1814
export const rateLimiter: RateLimitRequestHandler = rateLimit({
1915
windowMs: 60 * 1000,
2016
limit: (req: Request): number => {
2117
const ip = req.headers['cf-connecting-ip'] ?? req.ip
22-
logger.info(`Rate limit check ${req.auth ? 'authenticated' : 'anon'} - ${ip}`)
23-
return req.auth ? 60 : 5 // 60 req/min for auth, 5 for anon
18+
const authed = isAuthenticated(req)
19+
logger.info(`Rate limit check for ${authed ? 'authenticated' : 'anon'} - ${ip}`)
20+
return authed ? 60 : 5 // 60 req/min for auth, 5 for anon
2421
},
2522
keyGenerator: (req: Request): string => {
2623
const ip = req.headers['cf-connecting-ip'] ?? req.ip
27-
return getUserId(req) ?? ip
24+
return getSessionId(req) ?? ip
2825
},
2926
handler: (req: Request, res: Response) => {
3027
const ip = req.headers['cf-connecting-ip'] ?? req.ip

0 commit comments

Comments
 (0)