platform/packages/security/example/main.dart

36 lines
1.2 KiB
Dart
Raw Permalink Normal View History

import 'package:protevus_framework/protevus_framework.dart';
import 'package:protevus_framework/http.dart';
import 'package:protevus_security/protevus_security.dart';
2019-08-14 20:13:37 +00:00
import 'package:logging/logging.dart';
2021-09-25 15:37:22 +00:00
import 'package:belatuk_pretty_logging/belatuk_pretty_logging.dart';
2019-08-14 18:49:14 +00:00
2021-02-14 05:22:25 +00:00
void main() async {
2019-08-14 20:13:37 +00:00
// Logging boilerplate.
Logger.root.onRecord.listen(prettyLog);
2019-08-14 20:06:40 +00:00
// Create an app, and HTTP driver.
var app = Protevus(logger: Logger('rate_limit'));
var http = ProtevusHttp(app);
2019-08-14 20:06:40 +00:00
// Create a simple in-memory rate limiter that limits users to 5
2019-08-16 13:00:56 +00:00
// queries per 30 seconds.
2019-08-14 20:06:40 +00:00
//
// In this case, we rate limit users by IP address.
var rateLimiter =
2019-08-16 13:00:56 +00:00
InMemoryRateLimiter(5, Duration(seconds: 30), (req, res) => req.ip);
2019-08-14 20:06:40 +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
..get('/', (req, res) => 'Hello!')
..fallback((req, res) => throw ProtevusHttpException.notFound());
2019-08-14 20:06:40 +00:00
// Start the server.
await http.startServer('127.0.0.1', 3000);
print('Rate limiting example listening at ${http.uri}');
2019-08-14 18:49:14 +00:00
}