shelf_auth_session 0.2.0 shelf_auth_session: ^0.2.0 copied to clipboard
Session support for shelf_auth
example/shelf_auth_session.dart
// Copyright (c) 2014, Anders Holmgren. All rights reserved. Use of this source code
// is governed by a BSD-style license that can be found in the LICENSE file.
library shelf_auth_session.example;
import 'package:shelf/shelf.dart';
import 'package:shelf/shelf_io.dart' as io;
import 'package:shelf_auth/shelf_auth.dart';
import 'package:shelf_exception_response/exception_response.dart';
import 'dart:async';
import 'package:option/option.dart';
import 'package:logging/logging.dart';
import 'package:shelf_auth_session/shelf_auth_session.dart';
import 'package:uuid/uuid.dart';
void main() {
Logger.root.level = Level.FINER;
Logger.root.onRecord.listen((lr) {
print('${lr.time} ${lr.level} ${lr.message}');
});
var authMiddleware = (builder()
.authenticator(new RandomAuthenticator())
.jwtSession('moi', 'ssh', testLookup)
..allowHttp=true)
.build();
var handler = const Pipeline()
.addMiddleware(logRequests())
.addMiddleware(exceptionResponse())
.addMiddleware(authMiddleware)
.addMiddleware(sessionMiddleware(new InMemorySessionRepository()))
.addHandler(_fooHandler);
io.serve(handler, 'localhost', 8080).then((server) {
print('Serving at http://${server.address.host}:${server.port}');
});
}
Response _fooHandler(Request request) {
final s = session(request).get();
final currCount = s['count'];
final count = currCount == null ? 0 : currCount + 1;
s['count'] = count;
return new Response.ok("I'm in with "
"${authenticatedContext().map((ac) => ac.principal.name)}: "
"count is $count\n");
}
class RandomAuthenticator extends Authenticator {
bool approve = true;
bool readsBody = false;
@override
Future<Option<AuthenticatedContext>> authenticate(Request request) {
approve = !approve;
final now = new DateTime.now();
return new Future.value(approve ?
new Some(new SessionAuthenticatedContext(
new Principal("fred"), new Uuid().v4(), now, now, now.add(const Duration(days: 10))))
: throw new UnauthorizedException());
}
}
Future<Option<Principal>> testLookup(String username) {
return new Future.value(new Some(new Principal(username)));
}