jwt static method

Middleware Function() jwt({
  1. required String secret,
  2. String? issuer,
  3. List<String> requiredRoles = const [],
})

Creates JWT authentication middleware.

For production use, integrate with a real JWT library like dart_jsonwebtoken. This implementation provides the structure for JWT validation.

Implementation

static Middleware Function() jwt({
  required String secret,
  String? issuer,
  List<String> requiredRoles = const [],
}) {
  return () => (Handler handler) {
    return (Request request) async {
      // Extract JWT from Authorization header
      final authHeader = request.headers['authorization'];
      if (authHeader == null || !authHeader.startsWith('Bearer ')) {
        return Response(401,
          body: '{"success": false, "error": {"code": "UNAUTHORIZED", "message": "Missing or invalid token"}}',
          headers: {'content-type': 'application/json'});
      }

      final token = authHeader.substring(7);

      // Basic token validation (extend with real JWT library)
      if (token.isEmpty) {
        return Response(401,
          body: '{"success": false, "error": {"code": "UNAUTHORIZED", "message": "Invalid token"}}',
          headers: {'content-type': 'application/json'});
      }

      // TODO: Validate JWT signature and expiration with real JWT library
      // For now, we parse a mock payload - replace with real JWT validation
      final mockPayload = _parseTokenMock(token);

      if (mockPayload == null) {
        return Response(401,
          body: '{"success": false, "error": {"code": "UNAUTHORIZED", "message": "Invalid token format"}}',
          headers: {'content-type': 'application/json'});
      }

      // Check required roles if specified
      if (requiredRoles.isNotEmpty) {
        final userRoles = (mockPayload['roles'] as List<dynamic>?) ?? [];
        final hasRequiredRole = requiredRoles.any((role) => userRoles.contains(role));

        if (!hasRequiredRole) {
          return Response(403,
            body: '{"success": false, "error": {"code": "FORBIDDEN", "message": "Insufficient permissions"}}',
            headers: {'content-type': 'application/json'});
        }
      }

      // Add JWT payload to request context for downstream handlers
      final updatedRequest = request.change(context: {
        ...request.context,
        'jwt_payload': mockPayload,
        'user_id': mockPayload['user_id'],
        'user_email': mockPayload['email'],
        'user_roles': mockPayload['roles'] ?? [],
        'token': token,
      });

      return handler(updatedRequest);
    };
  };
}