1

我在试图理解 Dart 架子如何执行中间件和处理程序时迷失了方向。从我读过的所有文档(并简要介绍)中,如果您编写一个返回 null 的中间件,那么执行将沿着管道进行。否则,如果中间件返回一个响应,则停止沿管道的执行,并将响应返回给调用者。

我有一个带有这样简单管道的服务器:

    var handler = const shelf.Pipeline()
    .addMiddleware(shelf.logRequests())
//.addMiddleware(options)
    .addMiddleware(auth)
    .addHandler(Router.handle);

auth 中间件检查 3 种情况:注册、登录和验证。

  • 注册 -> 创建新用户并返回 Response.ok(token),否则返回 Response.InternalServerError
  • 登录 -> 刷新令牌并返回 Response.ok(token),如果不正确则返回 Response(401)
  • 验证 -> 正常时返回 null(应继续沿管道),或响应(403,禁止)

问题是,我无法停止中间件的执行。如果我成功登录,程序仍然会顺流而下并调用路由器。哪个当然没有 register 的路径并按预期返回 404 。

根据架子文档,它应该在中间件返回响应时停止。我到底做错了什么?

这是 auth Middleware 的代码供参考:

    abstract class AuthProvider {
      static JsonDecoder _decoder = const JsonDecoder();
    
      static FutureOr<Response> handle(Request request) async {
        print('Entering auth middleware');
        if(request.url.toString() == 'login'){
          print('into login from auth');
          AuthProvider.auth(request);
        }
        else if(request.url.toString() == 'register'){
          print('Into register from auth');
          RegisterController.handle(request);
        }
        else {
          print('Into verify from auth');
          AuthProvider.verify(request);
        }
      }
    
      static FutureOr<Response> auth(Request request) async {
        print('Entering auth');
        String sql;
        var query = ExecQuery();
        try {
          dynamic data = jsonDecode(await request.readAsString()) as Map<String, dynamic>;
          final user = data['email'].toString();
          final hash = Hash.create(data['password'].toString());
          sql =
          '''SELECT COUNT(*) FROM public.user WHERE (email = '${user}' AND password = '${hash}')''';
          await query.countSql(sql);
          if (query.result.status && query.result.opResult[0][0] == 1) {
            JwtClaim claim = JwtClaim(
              subject: user,
              issuer: 'Me',
              audience: ['users'],
            );
            final token = issueJwtHS256(claim, config.secret);
            sql = '''UPDATE public.user SET token = '${token}'
              WHERE (email = '${user}' AND password = '${hash}')''';
            await query.rawQuery(sql);
            return Response.ok(token);
          }
          else{throw Exception();}
        } catch (e) {
          return Response(401, body: 'Incorrect username/password');
        }
      }
    
      static FutureOr<Response> verify(Request request) async {
        print('Entering verify');
        try {
          final token = request.headers['Authorization'].replaceAll('Bearer ', '');
          print('Received token: ${token}');
          final claim = verifyJwtHS256Signature(token, config.secret);
          print('got the claim');
          claim.validate(issuer: 'ACME Widgets Corp',
              audience: 'homacenter');
          print ('returning null in middleware');
          return null;
        } catch(e) {
          print(e.toString());
          return Response.forbidden('Authorization rejected');
        }
      }
    }
4

1 回答 1

1

我自己回答......在这失去了几天之后,缺少回报,这使得管道继续前进。问题已关闭。

abstract class AuthProvider {
  static JsonDecoder _decoder = const JsonDecoder();

  static FutureOr<Response> handle(Request request) async {
    if(request.url.toString() == 'login'){
      return AuthProvider.auth(request);
    }
    else if(request.url.toString() == 'register'){
      return RegisterController.handle(request);
    }
    else {
      return AuthProvider.verify(request);
    }
  }
于 2021-01-27T08:31:31.743 回答