From 0d38f9e56724257c78160873bf1ff0f7fe09cf0e Mon Sep 17 00:00:00 2001 From: Tobe O Date: Fri, 16 Aug 2019 09:00:56 -0400 Subject: [PATCH] Init CookieSigner --- example/rate_limit.dart | 4 ++-- lib/angel_security.dart | 1 + lib/src/cookie_signer.dart | 20 ++++++++++++++++++++ pubspec.yaml | 1 + 4 files changed, 24 insertions(+), 2 deletions(-) create mode 100644 lib/src/cookie_signer.dart diff --git a/example/rate_limit.dart b/example/rate_limit.dart index 8b33d5a7..baccb01a 100644 --- a/example/rate_limit.dart +++ b/example/rate_limit.dart @@ -12,11 +12,11 @@ main() async { var app = Angel(logger: Logger('rate_limit')), http = AngelHttp(app); // Create a simple in-memory rate limiter that limits users to 5 - // queries per hour. + // queries per 30 seconds. // // In this case, we rate limit users by IP address. var rateLimiter = - InMemoryRateLimiter(5, Duration(hours: 1), (req, res) => req.ip); + InMemoryRateLimiter(5, Duration(seconds: 30), (req, res) => req.ip); // `RateLimiter.handleRequest` is a middleware, and can be used anywhere // a middleware can be used. In this case, we apply the rate limiter to diff --git a/lib/angel_security.dart b/lib/angel_security.dart index e9a28383..4bcfd7ef 100644 --- a/lib/angel_security.dart +++ b/lib/angel_security.dart @@ -1,3 +1,4 @@ +export 'src/cookie_signer.dart'; export 'src/in_memory_rate_limiter.dart'; export 'src/rate_limiter.dart'; export 'src/rate_limiting_window.dart'; \ No newline at end of file diff --git a/lib/src/cookie_signer.dart b/lib/src/cookie_signer.dart new file mode 100644 index 00000000..9adf048e --- /dev/null +++ b/lib/src/cookie_signer.dart @@ -0,0 +1,20 @@ +import 'dart:convert'; +import 'dart:io'; +import 'package:angel_framework/angel_framework.dart'; +import 'package:crypto/crypto.dart'; + +class CookieSigner { + final Hmac hmac; + + CookieSigner(List keyBytes, {Hash hash}) + : hmac = Hmac(hash ?? sha256, keyBytes); + + factory CookieSigner.fromStringKey(String key, {Hash hash}) { + if (key.length != 32) { + throw ArgumentError.value(key, 'key', 'must have a length of 32'); + } + return CookieSigner(utf8.encode(key), hash: hash); + } + + CookieSigner.fromHmac(this.hmac); +} diff --git a/pubspec.yaml b/pubspec.yaml index cbde50fa..561b9b26 100644 --- a/pubspec.yaml +++ b/pubspec.yaml @@ -11,6 +11,7 @@ dev_dependencies: angel_auth: ^2.0.0 angel_test: ^2.0.0 angel_validate: ^2.0.0 + crypto: ^2.0.0 pedantic: ^1.0.0 pretty_logging: ^1.0.0 test: ^1.0.0