shelf_auth_session 0.4.0 copy "shelf_auth_session: ^0.4.0" to clipboard
shelf_auth_session: ^0.4.0 copied to clipboard

outdatedDart 1 only

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_handler/shelf_exception_handler.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';
import 'package:http_exception/http_exception.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(exceptionHandler())
      .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) async {
    approve = !approve;
    final now = new DateTime.now();

    if (approve) {
      return new Some(new SessionAuthenticatedContext(new Principal("fred"),
          new Uuid().v4(), now, now, now.add(const Duration(days: 10))));
    } else {
      throw new UnauthorizedException();
    }
  }
}

Future<Option<Principal>> testLookup(String username) {
  return new Future.value(new Some(new Principal(username)));
}
0
likes
0
pub points
0%
popularity

Publisher

unverified uploader

Session support for shelf_auth

Homepage

License

unknown (LICENSE)

Dependencies

collection, http_exception, option, shelf, shelf_auth

More

Packages that depend on shelf_auth_session