Skip to content

Commit

Permalink
Add rate limiter
Browse files Browse the repository at this point in the history
  • Loading branch information
l7ssha committed Dec 23, 2024
1 parent 14fbdd9 commit 348cbdd
Show file tree
Hide file tree
Showing 3 changed files with 24 additions and 0 deletions.
15 changes: 15 additions & 0 deletions lib/src/web_app/api_server.dart
Original file line number Diff line number Diff line change
Expand Up @@ -14,6 +14,7 @@ import 'package:running_on_dart/src/web_app/utils.dart';
import 'package:running_on_dart/src/services/bot_info.dart';
import 'package:shelf_cors_headers/shelf_cors_headers.dart';

import 'package:shelf_limiter/shelf_limiter.dart' as shelf_limiter;
import 'package:shelf_router/shelf_router.dart' as shelf_router;
import 'package:shelf/shelf.dart' as shelf;
import 'package:shelf/shelf_io.dart' as shelf_io;
Expand Down Expand Up @@ -186,9 +187,23 @@ class WebServer {

final corsChecker = dev ? originAllowAll : originOneOf(webServerAllowedOrigins.split(','));

final limiter = shelf_limiter.shelfLimiterByEndpoint(
endpointLimits: {
'/api/*': shelf_limiter.RateLimiterOptions(
maxRequests: 10,
windowSize: const Duration(seconds: 10),
),
},
defaultOptions: shelf_limiter.RateLimiterOptions(
maxRequests: 120,
windowSize: const Duration(minutes: 1),
),
);

final app = const shelf.Pipeline()
.addMiddleware(shelf.logRequests())
.addMiddleware(corsHeaders(originChecker: corsChecker))
.addMiddleware(limiter)
.addHandler(router.call);

_logger.info("Starting server at: http://$webServerHost:$webServerPort/");
Expand Down
8 changes: 8 additions & 0 deletions pubspec.lock
Original file line number Diff line number Diff line change
Expand Up @@ -490,6 +490,14 @@ packages:
url: "https://pub.dev"
source: hosted
version: "0.1.5"
shelf_limiter:
dependency: "direct main"
description:
name: shelf_limiter
sha256: adcd253c5121ca70100928cc8f4fcd4c842395777fb7b4782bacbc7f491384d5
url: "https://pub.dev"
source: hosted
version: "2.0.1"
shelf_packages_handler:
dependency: transitive
description:
Expand Down
1 change: 1 addition & 0 deletions pubspec.yaml
Original file line number Diff line number Diff line change
Expand Up @@ -36,6 +36,7 @@ dependencies:
shelf_router: ^1.1.4
shelf_cors_headers: ^0.1.0
shelf_static: ^1.1.3
shelf_limiter: ^2.0.1
jaguar_jwt: ^3.0.0

dev_dependencies:
Expand Down

0 comments on commit 348cbdd

Please sign in to comment.