GithubHelp home page GithubHelp logo

sf-kansara / loopback4-ratelimiter Goto Github PK

View Code? Open in Web Editor NEW

This project forked from sourcefuse/loopback4-ratelimiter

0.0 0.0 0.0 419 KB

A rate limiting extension for loopback4 applications

License: MIT License

JavaScript 5.37% TypeScript 94.63%

loopback4-ratelimiter's Introduction

loopback4-ratelimiter

LoopBack

A simple loopback-next extension for rate limiting in loopback applications. This extension uses express-rate-limit under the hood with redis used as store for rate limiting key storage using rate-limit-redis

Install

npm install loopback4-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 to work is the redis datasource name. Please provide it as below.
this.bind(RateLimitSecurityBindings.CONFIG).to({
  name: 'redis',
});
  • By default, ratelimiter will be initialized with default options as mentioned here. However, you can override any of the options using the Config Binding like below.
const rateLimitKeyGen = (req: Request) => {
  const token =
    (req.headers &&
      req.headers.authorization &&
      req.headers.authorization.replace(/bearer /i, '')) ||
    '';
  return token;
};

......

this.bind(RateLimitSecurityBindings.CONFIG).to({
  name: 'redis',
  max: 60,
  keyGenerator: 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.RATELIMIT_SECURITY_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;
};

.....

@ratelimit(true, {
  max: 60,
  keyGenerator: 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.
@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);
}

Feedback

If you've noticed a bug or have a question or have a feature request, search the issue tracker to see if someone else in the community has already created a ticket. If not, go ahead and make one! All feature requests are welcome. Implementation time may vary. Feel free to contribute the same, if you can. If you think this extension is useful, please star it. Appreciation really helps in keeping this project alive.

Contributing

Please read CONTRIBUTING.md for details on the process for submitting pull requests to us.

Code of conduct

Code of conduct guidelines here.

License

MIT

loopback4-ratelimiter's People

Contributors

samarpan-b avatar sf-kansara avatar dependabot[bot] avatar

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    ๐Ÿ–– Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. ๐Ÿ“Š๐Ÿ“ˆ๐ŸŽ‰

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google โค๏ธ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.