1.4.10 • Published 4 months ago

@bleco/ratelimiter v1.4.10

Weekly downloads
-
License
MIT
Repository
-
Last release
4 months ago

@bleco/ratelimiter

A simple loopback-next extension for rate limiting in loopback applications.

Features

@bleco/ratelimiter using rate-limiter-flexible under the hood. It supports following datasources for rate limiting.

  • Memory
  • Redis
  • MongoDB
  • MySQL
  • Postgres

And it also supports following aggregating algorithms for rate limiting.

  • Union Combine 2 or more limiters to act as single
  • Burst Allow traffic bursts with BurstyRateLimiter implementation easier than with TokenBucket.

Install

npm install @bleco/ratelimiter

Usage

In order to use this component into your LoopBack application, please follow below steps.

  • Add component to application.
this.component(RateLimiterComponent);
  • Minimum configuration required for this component is given below.

Configure the datasource to be used for rate limiting. You can use any of the three datasources mentioned above.

this.bind(RateLimitSecurityBindings.CONFIG).to({
  ds: RedisDataSouece, // or data source binding key
});
  • By default, ratelimiter will be initialized with default options as mentioned here. However, you can override any of the options using the Config Binding. Below is an example of how to do it with the redis datasource, you can also do it with other two datasources similarly.
const rateLimitKeyGen = (req: Request) => {
  const token = (req.headers && req.headers.authorization && req.headers.authorization.replace(/bearer /i, '')) || '';
  return token;
};

// ......

this.bind(RateLimitSecurityBindings.CONFIG).to({
  ds: RedisDataSource,
  points: 60,
  key: rateLimitKeyGen,
});
  • The component exposes a sequence action which can be added to your server sequence class. Adding this will trigger ratelimiter middleware for all the requests passing through.
export class MySequence implements SequenceHandler {
  constructor(
    @inject(SequenceActions.FIND_ROUTE) protected findRoute: FindRoute,
    @inject(SequenceActions.PARSE_PARAMS) protected parseParams: ParseParams,
    @inject(SequenceActions.INVOKE_METHOD) protected invoke: InvokeMethod,
    @inject(SequenceActions.SEND) public send: Send,
    @inject(SequenceActions.REJECT) public reject: Reject,
    @inject(RateLimitSecurityBindings.ACTION)
    protected rateLimitAction: RateLimitAction,
  ) {}

  async handle(context: RequestContext) {
    const requestTime = Date.now();
    try {
      const {request, response} = context;
      const route = this.findRoute(request);
      const args = await this.parseParams(request, route);

      // rate limit Action here
      await this.rateLimitAction(request, response);

      const result = await this.invoke(route, args);
      this.send(response, result);
    } catch (err) {
      // ...
    } finally {
      // ...
    }
  }
}
  • This component also exposes a method decorator for cases where you want tp specify different rate limiting options at API method level. For example, you want to keep hard rate limit for unauthorized API requests and want to keep it softer for other API requests. In this case, the global config will be overwritten by the method decoration. Refer below.
const rateLimitKeyGen = (req: Request) => {
  const token = (req.headers && req.headers.authorization && req.headers.authorization.replace(/bearer /i, '')) || '';
  return token;
};

// .....

class SomeController {
  // ...
  @ratelimit(true, {
    points: 60,
    key: rateLimitKeyGen,
  })
  @patch(`/auth/change-password`, {
    responses: {
      [STATUS_CODE.OK]: {
        description: 'If User password successfully changed.',
      },
      ...ErrorCodes,
    },
    security: [
      {
        [STRATEGY.BEARER]: [],
      },
    ],
  })
  async resetPassword(
    @requestBody({
      content: {
        [CONTENT_TYPE.JSON]: {
          schema: getModelSchemaRef(ResetPassword, {partial: true}),
        },
      },
    })
    req: ResetPassword,
    @param.header.string('Authorization') auth: string,
  ): Promise<User> {
    return this.authService.changepassword(req, auth);
  }
}
  • You can also disable rate limiting for specific API methods using the decorator like below.
class SomeController {
  // ...
  @ratelimit(false)
  @authenticate(STRATEGY.BEARER)
  @authorize(['*'])
  @get('/auth/me', {
    description: ' To get the user details',
    security: [
      {
        [STRATEGY.BEARER]: [],
      },
    ],
    responses: {
      [STATUS_CODE.OK]: {
        description: 'User Object',
        content: {
          [CONTENT_TYPE.JSON]: AuthUser,
        },
      },
      ...ErrorCodes,
    },
  })
  async userDetails(@inject(RestBindings.Http.REQUEST) req: Request): Promise<AuthUser> {
    return this.authService.getme(req.headers.authorization);
  }
}
  • More examples can be found here and here.

Credits

License

MIT

1.4.10

4 months ago

1.4.9

5 months ago

1.4.8

5 months ago

1.2.0

9 months ago

1.4.6

7 months ago

1.4.5

7 months ago

1.4.4

8 months ago

1.4.3

8 months ago

1.4.2

8 months ago

1.4.1

8 months ago

1.4.0

8 months ago

1.0.0-alpha.2

9 months ago

1.0.0-alpha.1

9 months ago

1.0.0-alpha.0

9 months ago

1.1.1

9 months ago

1.1.0

9 months ago

0.3.9

10 months ago

0.3.16

9 months ago

0.3.15

10 months ago

0.3.14

10 months ago

0.3.13

10 months ago

0.3.12

10 months ago

0.3.11

10 months ago

1.3.0

9 months ago

0.3.10

10 months ago

1.4.7

5 months ago

0.3.8

11 months ago

0.3.7

11 months ago

0.3.0

12 months ago

0.3.6

11 months ago

0.3.5

12 months ago

0.3.2

12 months ago

0.3.1

12 months ago

0.3.4

12 months ago

0.3.3

12 months ago

0.2.44

1 year ago

0.2.41

1 year ago

0.2.43

1 year ago

0.2.42

1 year ago

0.2.40

1 year ago

0.2.39

1 year ago

0.2.38

1 year ago

0.2.37

1 year ago

0.2.36

1 year ago

0.2.35

1 year ago

0.2.34

1 year ago

0.2.33

1 year ago

0.2.32

1 year ago

0.2.30

2 years ago

0.2.31

1 year ago

0.2.29

2 years ago

0.2.27

2 years ago

0.2.26

2 years ago

0.2.25

2 years ago

0.2.24

2 years ago

0.2.23

2 years ago

0.2.22

2 years ago

0.2.21

2 years ago

0.2.20

2 years ago

0.2.19

2 years ago

0.2.18

2 years ago

0.2.17

2 years ago

0.2.16

2 years ago

0.2.28

2 years ago

0.2.15

2 years ago

0.2.14

2 years ago

0.2.13

2 years ago

0.2.12

2 years ago

0.2.11

2 years ago

0.2.10

2 years ago

0.2.7

2 years ago

0.2.6

2 years ago

0.2.9

2 years ago

0.2.8

2 years ago

0.2.5

2 years ago

0.2.4

2 years ago

0.2.2

2 years ago

0.2.1

2 years ago

0.2.0

2 years ago