platform/packages/security/example/cookie_signer.dart

58 lines
1.9 KiB
Dart
Raw Normal View History

2019-08-16 13:50:50 +00:00
import 'dart:io';
import 'dart:math';
2021-06-26 11:02:51 +00:00
import 'package:angel3_framework/angel3_framework.dart';
import 'package:angel3_framework/http.dart';
import 'package:angel3_security/angel3_security.dart';
2019-08-16 13:50:50 +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-16 13:50:50 +00:00
2021-02-14 05:22:25 +00:00
void main() async {
2019-08-16 13:50:50 +00:00
// Logging boilerplate.
Logger.root.onRecord.listen(prettyLog);
// Create an app, and HTTP driver.
2021-06-20 12:37:20 +00:00
var app = Angel(logger: Logger('cookie_signer'));
var http = AngelHttp(app);
2019-08-16 13:50:50 +00:00
// Create a cookie signer. Uses an SHA256 Hmac by default.
var signer = CookieSigner.fromStringKey(
'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789ab');
// When a user visits /getid, give them a (signed) uniqid cookie.
// When they visit /cookies, print their verified cookies.
var rnd = Random.secure();
// Endpoint to give a signed cookie.
app.get('/getid', (req, res) {
// Write the uniqid cookie.
var uniqid = rnd.nextInt(65536);
2019-08-16 13:53:15 +00:00
signer.writeCookie(res, Cookie('uniqid', uniqid.toString()));
2019-08-16 13:50:50 +00:00
// Send a response.
res.write('uniqid=$uniqid');
});
// Endpoint to dump all verified cookies.
//
// The [onInvalidCookie] callback is optional, but
// here we will use it to log invalid cookies.
app.get('/cookies', (req, res) {
var verifiedCookies = signer.readCookies(req, onInvalidCookie: (cookie) {
2022-04-25 00:54:13 +00:00
app.logger.warning('Invalid cookie: $cookie');
2019-08-16 13:50:50 +00:00
});
res.writeln('${verifiedCookies.length} verified cookie(s)');
res.writeln('${req.cookies.length} total unverified cookie(s)');
for (var cookie in verifiedCookies) {
res.writeln('${cookie.name}=${cookie.value}');
}
});
// 404 otherwise.
app.fallback((req, res) => throw AngelHttpException.notFound(
message: 'The only valid endpoints are /getid and /cookies.'));
// Start the server.
await http.startServer('127.0.0.1', 3000);
print('Cookie signer example listening at ${http.uri}');
}