From 1dab03f87705632669d344eda8894cdf2506bc0a Mon Sep 17 00:00:00 2001 From: arpit1503khanna <108673359+arpit1503khanna@users.noreply.github.com> Date: Mon, 13 May 2024 18:59:34 +0530 Subject: [PATCH] docs(chore): copy the Readme to root as well (#171) copy the Readme to root as well GH-170 --- README.md | 286 ++++++++++++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 286 insertions(+) create mode 100644 README.md diff --git a/README.md b/README.md new file mode 100644 index 0000000..4d7858b --- /dev/null +++ b/README.md @@ -0,0 +1,286 @@ + + +# [loopback4-ratelimiter](https://github.com/sourcefuse/loopback4-ratelimiter) + +
+ + + + + + + + + + + + + + + + + + + + + +
+ +## Overview + +A simple loopback-next extension for rate limiting in loopback applications. This extension uses [express-rate-limit](https://github.com/nfriedly/express-rate-limit) under the hood with redis, memcache and mongodDB used as store for rate limiting key storage using [rate-limit-redis](https://github.com/wyattjoh/rate-limit-redis), [rate-limit-memcached](https://github.com/linyows/rate-limit-memcached) and [rate-limit-mongo](https://github.com/2do2go/rate-limit-mongo) + +## Install + +```sh +npm install loopback4-ratelimiter +``` + +## Usage + +In order to use this component into your LoopBack application, please follow below steps. + +- Add component to application. + +```ts +this.component(RateLimiterComponent); +``` + +- Minimum configuration required for this component is given below. + +For redis datasource, you have to pass the name of a loopback4 datasource + +```ts +this.bind(RateLimitSecurityBindings.CONFIG).to({ + name: 'redis', + type: 'RedisStore', +}); +``` + +For memcache datasource + +```ts +this.bind(RateLimitSecurityBindings.CONFIG).to({ + client: memoryClient, + type: 'MemcachedStore', +}); +``` + +For mongoDB datasource + +```ts +this.bind(RateLimitSecurityBindings.CONFIG).to({ + name: 'mongo', + type:'MongoStore'; + uri: 'mongodb://127.0.0.1:27017/test_db', + collectionName: 'expressRateRecords' +}); +``` + +- By default, ratelimiter will be initialized with default options as mentioned [here](https://github.com/nfriedly/express-rate-limit#configuration-options). 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. + +```ts +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', + type: 'RedisStore', + max: 60, + keyGenerator: rateLimitKeyGen, +}); +``` + +## EnabledbyDefault + +enabledByDefault option in Config Binding will provide a configurable mode. +When its enabled (default value is true),it will provide a way to +ratelimit all API's except a few that are disabled using a decorator. + +To disable ratelimiting for all APIs except those that are enabled using the decorator, +you can set its value to false in config binding option. + +``` +this.bind(RateLimitSecurityBindings.CONFIG).to({ + name: 'redis', + type: 'RedisStore', + max: 60, + keyGenerator: rateLimitKeyGen, + enabledByDefault:false +}); +``` + +- 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. + +```ts +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. + +```ts +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