Skip to content

Commit

Permalink
fix: moves userAgent check to http handler
Browse files Browse the repository at this point in the history
  • Loading branch information
jmcdo29 committed Jun 12, 2020
1 parent 6caf24d commit 87183af
Showing 1 changed file with 10 additions and 10 deletions.
20 changes: 10 additions & 10 deletions src/throttler.guard.ts
Original file line number Diff line number Diff line change
Expand Up @@ -29,7 +29,6 @@ export class ThrottlerGuard implements CanActivate {
* @throws ThrottlerException
*/
async canActivate(context: ExecutionContext): Promise<boolean> {
const req = context.switchToHttp().getRequest();
const handler = context.getHandler();
const classRef = context.getClass();

Expand All @@ -38,15 +37,6 @@ export class ThrottlerGuard implements CanActivate {
return true;
}

// Return early if the current user agent should be ignored.
if (Array.isArray(this.options.ignoreUserAgents)) {
for (const pattern of this.options.ignoreUserAgents) {
if (pattern.test(req.headers['user-agent'])) {
return true;
}
}
}

// Return early when we have no limit or ttl data.
const routeOrClassLimit = this.reflector.getAllAndOverride<number>(THROTTLER_LIMIT, [
handler,
Expand Down Expand Up @@ -87,6 +77,16 @@ export class ThrottlerGuard implements CanActivate {
// Here we start to check the amount of requests being done against the ttl.
const req = context.switchToHttp().getRequest();
const res = context.switchToHttp().getResponse();

// Return early if the current user agent should be ignored.
if (Array.isArray(this.options.ignoreUserAgents)) {
for (const pattern of this.options.ignoreUserAgents) {
if (pattern.test(req.headers['user-agent'])) {
return true;
}
}
}

const key = this.generateKey(context, req.ip);
const ttls = await this.storageService.getRecord(key);
const nearestExpiryTime = ttls.length > 0 ? Math.ceil((ttls[0] - Date.now()) / 1000) : 0;
Expand Down

0 comments on commit 87183af

Please sign in to comment.