Java Code Examples for io.vertx.ext.web.RoutingContext#fail()

The following examples show how to use io.vertx.ext.web.RoutingContext#fail() . These examples are extracted from open source projects. You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example 1
Source Project: nubes   File: RateLimitationHandler.java    License: Apache License 2.0 6 votes vote down vote up
@Override
public void handle(RoutingContext context) {
  Vertx vertx = context.vertx();
  LocalMap<Object, Object> rateLimitations = vertx.sharedData().getLocalMap("mvc.rateLimitation");
  String clientIp = context.request().remoteAddress().host();
  JsonObject json = (JsonObject) rateLimitations.get(clientIp);
  ClientAccesses accesses;
  if (json == null) {
    accesses = new ClientAccesses();
  } else {
    accesses = ClientAccesses.fromJsonObject(json);
  }
  accesses.newAccess();
  rateLimitations.put(clientIp, accesses.toJsonObject());
  if (accesses.isOverLimit(rateLimit)) {
    context.fail(420);
  } else {
    context.next();
  }
}
 
Example 2
Source Project: joyqueue   File: AdminLoginHandler.java    License: Apache License 2.0 6 votes vote down vote up
@Override
public void handle(final RoutingContext context) {
    HttpServerRequest request = context.request();
    Session session = context.session();
    if (session == null) {
        context.fail(new HttpStatusException(HTTP_INTERNAL_ERROR, "No session - did you forget to include a SessionHandler?"));
        return;
    }
    String remoteIP = getRemoteIP(request);
    context.put(REMOTE_IP, remoteIP);
    User user = session.get(userSessionKey);
    if (user == null) {
        user = userService.findByCode(DEFAULT_LOGIN_USER_CODE);
    }
    //存放用户上下文信息
    context.put(USER_KEY, user);
    context.next();
}
 
Example 3
private void authCallback(OAuth2Auth oauth2, String hostURL, RoutingContext context) {
  final String code = context.request().getParam("code");
  // code is a require value
  if (code == null) {
    context.fail(400);
    return;
  }
  final String redirectTo = context.request().getParam("redirect_uri");
  final String redirectURI = hostURL + context.currentRoute().getPath() + "?redirect_uri=" + redirectTo;
  oauth2.getToken(new JsonObject().put("code", code).put("redirect_uri", redirectURI), ar -> {
    if (ar.failed()) {
      logger.warn("Auth fail");
      context.fail(ar.cause());
    } else {
      logger.info("Auth success");
      context.setUser(ar.result());
      context.response()
        .putHeader("Location", redirectTo)
        .setStatusCode(302)
        .end();
    }
  });
}
 
Example 4
Source Project: nubes   File: CheckTokenHandler.java    License: Apache License 2.0 6 votes vote down vote up
@Override
public void handle(RoutingContext context) {
  User user = context.user();
  if (user != null) {
      authorize(user, event -> {});
    return;
  }
  String apiToken;
  try {
    apiToken = parseApiToken(context.request());
  } catch (BadRequestException bre) {
    context.fail(bre);
    return;
  }
  if (apiToken == null) {
    context.fail(401);
    return;
  }
  doAuth(context, apiToken);
}
 
Example 5
Source Project: vertx-swagger   File: ApiKeyAuthHandler.java    License: Apache License 2.0 6 votes vote down vote up
@Override
public void parseCredentials(RoutingContext context, Handler<AsyncResult<JsonObject>> handler) {
    HttpServerRequest request = context.request();

    String value = null;
    switch (this.location) {
        case QUERY:
            value = request.getParam(this.name);
            break;
        case HEADER:
            value = request.headers().get(this.name);
            break;
        default:
            context.fail(401);
            return;
    }

    JsonObject authInfo = new JsonObject()
            .put(API_KEY_NAME_PARAM, this.name)
            .put(API_KEY_VALUE_PARAM, value);

    handler.handle(Future.succeededFuture(authInfo));
}
 
Example 6
Source Project: quarkus   File: VertxRequestHandler.java    License: Apache License 2.0 6 votes vote down vote up
private void binaryContentMode(RoutingContext routingContext) {
    String ceType = routingContext.request().getHeader("ce-type");
    FunctionInvoker invoker = defaultInvoker;
    if (invoker == null) {
        // map by type trigger
        invoker = typeTriggers.get(ceType);
        if (invoker == null) {
            routingContext.fail(404);
            log.error("Could not map ce-type header: " + ceType + " to a function");
            return;
        }

    }
    final FunctionInvoker targetInvoker = invoker;
    processHttpRequest(new HeaderCloudEventImpl(routingContext.request()), routingContext, () -> {
        routingContext.response().putHeader("ce-id", getResponseId());
        routingContext.response().putHeader("ce-specversion", "1.0");
        routingContext.response().putHeader("ce-source",
                (String) targetInvoker.getBindingContext().get(RESPONSE_SOURCE));
        routingContext.response().putHeader("ce-type",
                (String) targetInvoker.getBindingContext().get(RESPONSE_TYPE));
    }, invoker);
}
 
Example 7
Source Project: quarkus   File: VertxRequestHandler.java    License: Apache License 2.0 6 votes vote down vote up
private boolean checkHttpMethod(RoutingContext routingContext, FunctionInvoker invoker) {
    if (invoker.hasInput()) {
        if (routingContext.request().method() != HttpMethod.POST) {
            routingContext.fail(405);
            log.error("Must be POST for: " + invoker.getName());
            return false;
        }
    }
    if (routingContext.request().method() != HttpMethod.POST && routingContext.request().method() != HttpMethod.GET) {
        routingContext.fail(405);
        log.error("Must be POST or GET for: " + invoker.getName());
        return false;

    }
    return true;
}
 
Example 8
Source Project: nubes   File: CheckAuthorityProcessor.java    License: Apache License 2.0 5 votes vote down vote up
@Override
public void preHandle(RoutingContext context) {
  User user = context.user();
  if (user == null) {
    context.fail(401);
    return;
  }
  user.isAuthorized(annotation.authority(), result -> {
    if (!result.result()) {
      context.fail(403);
    } else {
      context.next();
    }
  });
}
 
Example 9
@Override
public void handle(final RoutingContext context, final JsonRpcRequest rpcRequest) {
  LOG.debug("Internally responding to {}, id={}", rpcRequest.getMethod(), rpcRequest.getId());
  final JsonRpcBody providedBody = responseBodyProvider.getBody(rpcRequest);

  if (providedBody.hasError()) {
    context.fail(new JsonRpcException(providedBody.error()));
  } else {
    final JsonRpcSuccessResponse result =
        jsonDecoder.decodeValue(providedBody.body(), JsonRpcSuccessResponse.class);
    responder.create(context.request(), HttpResponseStatus.OK.code(), result);
  }
}
 
Example 10
Source Project: orion   File: DeletePrivacyGroupHandler.java    License: Apache License 2.0 5 votes vote down vote up
private void handleFailure(final RoutingContext routingContext, final Throwable ex) {
  log.warn("propagating the payload failed");

  final Throwable cause = ex.getCause();
  if (cause instanceof OrionException) {
    routingContext.fail(cause);
  } else {
    routingContext.fail(new OrionException(OrionErrorCode.NODE_PROPAGATING_TO_ALL_PEERS, ex));
  }
}
 
Example 11
@Override
public void handle(RoutingContext routingContext) {
    HttpServerRequest request = routingContext.request();
    request.pause();
    String authorization = request.headers().get(HttpHeaders.AUTHORIZATION);
    if (authorization == null) {
        routingContext.fail(401);
    } else {
        String[] parts = authorization.split(" ");
        if (parts.length != 2) {
            routingContext.fail(401);
        } else {
            String scheme = parts[0];
            if (!"bearer".equalsIgnoreCase(scheme)) {
                routingContext.fail(401);
            } else {
                String token = parts[1];
                JsonObject credentials = new JsonObject();
                credentials.put("token", token);

                authProvider.authenticate(credentials, res -> {
                    if (res.succeeded()) {
                        routingContext.setUser(res.result());
                        request.resume();
                        routingContext.next();
                    } else {
                        routingContext.fail(401);
                    }
                });
            }
        }
    }
}
 
Example 12
private void apiIncrease(RoutingContext context) {
  try {
    String productId = context.request().getParam("productId");
    int increase = Integer.valueOf(context.request().getParam("n"));
    if (increase <= 0) {
      badRequest(context, new IllegalStateException("Negative increase"));
    } else {
      inventoryService.increase(productId, increase)
        .setHandler(rawResultHandler(context));
    }
  } catch (Exception ex) {
    context.fail(400);
  }
}
 
Example 13
private void writeBinary(Buffer buffer,RoutingContext ctx) {
    try {
        ctx.response().putHeader("Content-Type", "application/octet-stream");
        ctx.response().putHeader("Content-Length", String.valueOf(buffer.length()));
        ctx.response().end(buffer);
    } catch (Exception e) {
        ctx.fail(e);
    }
}
 
Example 14
Source Project: vertx-vaadin   File: VertxVaadin.java    License: MIT License 5 votes vote down vote up
private void handleVaadinRequest(RoutingContext routingContext) {
    VertxVaadinRequest request = new VertxVaadinRequest(service, routingContext);
    VertxVaadinResponse response = new VertxVaadinResponse(service, routingContext);

    try {
        logger.trace("Handling Vaadin request: {}", routingContext.request().uri());
        service.handleRequest(request, response);
        response.end();
    } catch (ServiceException ex) {
        logger.error("Error processing request {}", routingContext.request().uri(), ex);
        routingContext.fail(ex);
    }
}
 
Example 15
@Override
public void handle(RoutingContext routingContext) {
  if (routingContext.user() == null) {
    routingContext.fail(FORBIDDEN_CODE, FORBIDDEN_EXCEPTION);
  } else {
    // create the authorization context
    AuthorizationContext authorizationContext = getAuhorizationContext(routingContext);
    // check or fetch authorizations
    checkOrFetchAuthorizations(routingContext, authorizationContext, authorizationProviders.iterator());
  }
}
 
Example 16
@Override
protected void processException(RoutingContext ctx, Throwable exception) {
    if (exception != null && exception.getCause() != null) {
        // override default process exception to redirect to the login page
        if (exception.getCause() instanceof AuthenticationException) {
            ctx.fail(exception.getCause());
            return;
        }
    }
    super.processException(ctx, exception);
}
 
Example 17
protected void serviceUnavailable(RoutingContext context) {
  context.fail(503);
}
 
Example 18
Source Project: quarkus   File: VertxRequestHandler.java    License: Apache License 2.0 4 votes vote down vote up
@Override
public void handle(RoutingContext request) {
    String path = request.request().path();
    if (path == null) {
        request.fail(404);
        return;
    }
    // expects rootPath to end with '/'
    if (!path.startsWith(rootPath)) {
        request.fail(404);
        return;
    }

    path = path.substring(rootPath.length());

    FunctionInvoker invoker = FunctionRecorder.registry.matchInvoker(path);

    if (invoker == null) {
        request.fail(404);
        return;
    }

    if (!checkHttpMethod(request, invoker))
        return;

    request.request().bodyHandler(buff -> {
        Object input = null;
        if (buff.length() > 0) {
            ByteBufInputStream in = new ByteBufInputStream(buff.getByteBuf());
            ObjectReader reader = (ObjectReader) invoker.getBindingContext().get(ObjectReader.class.getName());
            try {
                input = reader.readValue((InputStream) in);
            } catch (Exception e) {
                log.error("Failed to unmarshal input", e);
                request.fail(400);
                return;
            }
        }
        Object finalInput = input;
        executor.execute(() -> {
            dispatch(request, invoker, finalInput);
        });
    });
}
 
Example 19
Source Project: hono   File: AuthHandlerTools.java    License: Eclipse Public License 2.0 4 votes vote down vote up
/**
 * Processes an exception that occurred while trying to authenticate
 * a device.
 * <p>
 * This method checks if the given exception is an {@code HttpStatusException}
 * and if so, tries to extract the root cause of the problem from its
 * <em>cause</em> field. If the root cause is a {@link ServiceInvocationException}
 * then its error code is used to fail the routing context, otherwise the status
 * code from the {@code HttpStatusException} is used. In all other cases, the
 * context is failed with a 500 error code.
 *
 * @param ctx The routing context.
 * @param exception The cause of failure to process the request.
 * @param authenticateHeader The value to return in the HTTP Authenticate header.
 */
public static void processException(
        final RoutingContext ctx,
        final Throwable exception,
        final String authenticateHeader) {


    if (exception instanceof HttpStatusException) {

        final Throwable failure = Optional.ofNullable(exception.getCause()).map(c -> {
            if (c instanceof ServiceInvocationException) {
                // extract and use root cause
                return c;
            } else {
                return exception;
            }
        }).orElse(exception);

        final int statusCode;
        final String payload;

        if (failure instanceof ServiceInvocationException) {
            final ServiceInvocationException sie = (ServiceInvocationException) exception.getCause();
            statusCode = sie.getErrorCode();
            payload = null;
        } else {
            statusCode = ((HttpStatusException) exception).getStatusCode();
            payload = ((HttpStatusException) exception).getPayload();
        }

        switch (statusCode) {
        case 302:
            ctx.response()
                    .putHeader(HttpHeaders.LOCATION, payload)
                    .setStatusCode(302)
                    .end("Redirecting to " + payload + ".");
            return;
        case 401:
            if (authenticateHeader != null) {
                ctx.response()
                        .putHeader("WWW-Authenticate", authenticateHeader);
            }
            ctx.fail(failure);
            return;
        default:
            ctx.fail(failure);
            return;
        }
    }

    // fallback 500
    ctx.fail(exception);
}
 
Example 20
Source Project: vertx-web   File: FormLoginHandlerImpl.java    License: Apache License 2.0 4 votes vote down vote up
@Override
public void handle(RoutingContext context) {
  HttpServerRequest req = context.request();
  if (req.method() != HttpMethod.POST) {
    context.fail(405); // Must be a POST
  } else {
    if (!req.isExpectMultipart()) {
      throw new IllegalStateException("HttpServerRequest should have setExpectMultipart set to true, but it is currently set to false.");
    }
    MultiMap params = req.formAttributes();
    String username = params.get(usernameParam);
    String password = params.get(passwordParam);
    if (username == null || password == null) {
      log.warn("No username or password provided in form - did you forget to include a BodyHandler?");
      context.fail(400);
    } else {
      Session session = context.session();
      UsernamePasswordCredentials authInfo = new UsernamePasswordCredentials(username, password);

      authProvider.authenticate(authInfo, res -> {
        if (res.succeeded()) {
          User user = res.result();
          context.setUser(user);
          if (session != null) {
            // the user has upgraded from unauthenticated to authenticated
            // session should be upgraded as recommended by owasp
            session.regenerateId();

            String returnURL = session.remove(returnURLParam);
            if (returnURL != null) {
              // Now redirect back to the original url
              doRedirect(req.response(), returnURL);
              return;
            }
          }
          // Either no session or no return url
          if (directLoggedInOKURL != null) {
            // Redirect to the default logged in OK page - this would occur
            // if the user logged in directly at this URL without being redirected here first from another
            // url
            doRedirect(req.response(), directLoggedInOKURL);
          } else {
            // Just show a basic page
            req.response().end(DEFAULT_DIRECT_LOGGED_IN_OK_PAGE);
          }
        } else {
          context.fail(401);  // Failed login
        }
      });
    }
  }
}