platform/packages/security/example/rate_limit_redis.dart

41 lines
1.5 KiB
Dart
Raw Normal View History

2021-06-26 11:02:51 +00:00
import 'package:angel3_redis/angel3_redis.dart';
import 'package:angel3_framework/angel3_framework.dart';
import 'package:angel3_production/angel3_production.dart';
import 'package:angel3_security/angel3_security.dart';
2019-08-16 15:37:34 +00:00
import 'package:resp_client/resp_client.dart';
import 'package:resp_client/resp_commands.dart';
2021-06-20 12:37:20 +00:00
import 'package:resp_client/resp_server.dart';
2019-08-16 15:25:51 +00:00
2019-08-16 15:37:34 +00:00
// We run this through angel_production, so that we can have
// multiple instances, all using the same Redis queue.
2021-02-14 05:22:25 +00:00
void main(List<String> args) =>
2019-08-16 15:37:34 +00:00
Runner('rate_limit_redis', configureServer).run(args);
2019-08-16 15:25:51 +00:00
2021-02-14 05:22:25 +00:00
void configureServer(Angel app) async {
2019-08-16 15:37:34 +00:00
// Create a simple rate limiter that limits users to 10
2019-08-16 15:25:51 +00:00
// queries per 30 seconds.
//
// In this case, we rate limit users by IP address.
//
// Our Redis store will be used to manage windows.
2019-08-16 15:37:34 +00:00
var connection = await connectSocket('localhost');
var client = RespClient(connection);
2021-06-20 12:37:20 +00:00
var service = RedisService(RespCommandsTier2(client),
prefix: 'rate_limit_redis_example');
2019-08-16 15:37:34 +00:00
var rateLimiter = ServiceRateLimiter(
10, Duration(seconds: 30), service, (req, res) => req.ip);
2019-08-16 15:25:51 +00:00
// `RateLimiter.handleRequest` is a middleware, and can be used anywhere
// a middleware can be used. In this case, we apply the rate limiter to
// *all* incoming requests.
app.fallback(rateLimiter.handleRequest);
// Basic routes.
app
2019-08-16 15:37:34 +00:00
..get('/', (req, res) {
2022-04-23 04:21:39 +00:00
var instance = req.container!.make<InstanceInfo>();
2019-08-16 15:37:34 +00:00
res.writeln('This is instance ${instance.id}.');
})
2019-08-16 15:25:51 +00:00
..fallback((req, res) => throw AngelHttpException.notFound());
}