platform/packages/security/example/rate_limit_redis.dart

40 lines
1.5 KiB
Dart
Raw Normal View History

2019-08-16 15:37:34 +00:00
import 'package:angel_redis/angel_redis.dart';
2019-08-16 15:25:51 +00:00
import 'package:angel_framework/angel_framework.dart';
2019-08-16 15:37:34 +00:00
import 'package:angel_production/angel_production.dart';
2019-08-16 15:25:51 +00:00
import 'package:angel_security/angel_security.dart';
2019-08-16 15:37:34 +00:00
import 'package:resp_client/resp_client.dart';
import 'package:resp_client/resp_commands.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.
main(List<String> args) =>
Runner('rate_limit_redis', configureServer).run(args);
2019-08-16 15:25:51 +00:00
2019-08-16 15:37:34 +00:00
configureServer(Angel app) async {
// 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);
var service =
RedisService(RespCommands(client), prefix: 'rate_limit_redis_example');
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) {
var instance = req.container.make<InstanceInfo>();
res.writeln('This is instance ${instance.id}.');
})
2019-08-16 15:25:51 +00:00
..fallback((req, res) => throw AngelHttpException.notFound());
}