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

The following examples show how to use io.vertx.reactivex.ext.web.RoutingContext#fail() . 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 File: MFAChallengeEndpoint.java    From graviteeio-access-management with Apache License 2.0 6 votes vote down vote up
private void renderMFAPage(RoutingContext routingContext) {
    try {
        final Client client = routingContext.get(CLIENT_CONTEXT_KEY);
        final io.gravitee.am.model.User endUser = ((io.gravitee.am.gateway.handler.common.vertx.web.auth.user.User) routingContext.user().getDelegate()).getUser();
        final Factor factor = getFactor(routingContext, client, endUser);
        final String error = routingContext.request().getParam(ERROR_PARAM);
        final String action = UriBuilderRequest.resolveProxyRequest(routingContext.request(), routingContext.request().uri(), null);
        routingContext.put("factor", factor);
        routingContext.put("action", action);
        routingContext.put(ERROR_PARAM, error);

        // render the mfa challenge page
        engine.render(routingContext.data(), getTemplateFileName(client), res -> {
            if (res.succeeded()) {
                routingContext.response().putHeader(HttpHeaders.CONTENT_TYPE, MediaType.TEXT_HTML);
                routingContext.response().end(res.result());
            } else {
                logger.error("Unable to render MFA challenge page", res.cause());
                routingContext.fail(res.cause());
            }
        });
    } catch (Exception ex) {
        logger.error("An error occurs while rendering MFA challenge page", ex);
        routingContext.fail(503);
    }
}
 
Example 2
Source File: LoginCallbackEndpoint.java    From graviteeio-access-management with Apache License 2.0 6 votes vote down vote up
@Override
public void handle(RoutingContext routingContext) {
    Session session = routingContext.session();
    if (session != null && session.get(RedirectAuthHandler.DEFAULT_RETURN_URL_PARAM) != null) {
        // if we have an id_token, put in the session context for post step (mainly the user consent step)
        if (routingContext.data().containsKey(ID_TOKEN_CONTEXT_KEY)) {
            session.put(ID_TOKEN_CONTEXT_KEY, routingContext.get(ID_TOKEN_CONTEXT_KEY));
        }

        final String redirectUrl = session.get(RedirectAuthHandler.DEFAULT_RETURN_URL_PARAM);
        doRedirect(routingContext.response(), redirectUrl);
    } else {
        routingContext.fail(503);
    }

}
 
Example 3
Source File: DynamicClientRegistrationHandler.java    From graviteeio-access-management with Apache License 2.0 6 votes vote down vote up
@Override
public void handle(RoutingContext context) {

    //Do not apply security check if open dynamic client registration is enabled.
    if(domain.isOpenDynamicClientRegistrationEnabled()) {
        LOGGER.debug("Open Dynamic client registration is enabled - no security will be performed.");
        context.next();
        return;
    }

    //1st check if dynamic client registration is enabled.
    if(!domain.isDynamicClientRegistrationEnabled()) {
        LOGGER.debug("Dynamic client registration is disabled");
        context.fail(new ClientRegistrationForbiddenException());
        return;
    }

    this.oAuth2AuthHandler.handle(context);
}
 
Example 4
Source File: IngesterVerticle.java    From vertx-in-action with MIT License 6 votes vote down vote up
private void httpIngest(RoutingContext ctx) {
  JsonObject payload = ctx.getBodyAsJson();
  if (invalidIngestedJson(payload)) {
    logger.error("Invalid HTTP JSON (discarded): {}", payload.encode());
    ctx.fail(400);
    return;
  }

  KafkaProducerRecord<String, JsonObject> record = makeKafkaRecord(payload);
  updateProducer.rxSend(record).subscribe(
    ok -> ctx.response().end(),
    err -> {
      logger.error("HTTP ingestion failed", err);
      ctx.fail(500);
    });
}
 
Example 5
Source File: ActionHelper.java    From introduction-to-eclipse-vertx with Apache License 2.0 6 votes vote down vote up
/**
 * Returns a bi-consumer writing the received {@link AsyncResult} to the routing context and setting
 * the HTTP status to the given status.
 *
 * @param context the routing context
 * @param status  the status
 * @return the bi-consumer
 */
private static <T> BiConsumer<T, Throwable> writeJsonResponse(RoutingContext context, int status) {
    return (res, err) -> {
        if (err != null) {
            if (err instanceof NoSuchElementException) {
                context.response().setStatusCode(404).end(err.getMessage());
            } else {
                context.fail(err);
            }
        } else {
            context.response().setStatusCode(status)
                .putHeader("content-type", "application/json; charset=utf-8")
                .end(Json.encodePrettily(res));
        }
    };
}
 
Example 6
Source File: DynamicClientAccessTokenHandler.java    From graviteeio-access-management with Apache License 2.0 6 votes vote down vote up
@Override
public void handle(RoutingContext context) {
    final JWT token = context.get(OAuth2AuthHandler.TOKEN_CONTEXT_KEY);
    final Client client = context.get(OAuth2AuthHandler.CLIENT_CONTEXT_KEY);

    if (token.hasScope(Scope.DCR_ADMIN.getKey())) {
        context.next();
        return;
    }

    // if not dcr admin, access token must match client registration token
    final String rawToken = context.get(OAuth2AuthHandler.RAW_TOKEN_CONTEXT_KEY);
    if (rawToken == null || !rawToken.equals(client.getRegistrationAccessToken())) {
        context.fail(new ClientRegistrationForbiddenException("Non matching registration_access_token"));
        return;
    }

    // registration token sub must match the client_id parameter
    final String clientIdPathParameter = context.request().getParam(Parameters.CLIENT_ID);
    if (!isRequestPathClientIdMatching(token, clientIdPathParameter)) {
        context.fail(new ClientRegistrationForbiddenException("Not allowed to access to : " + clientIdPathParameter));
        return;
    }

    context.next();
}
 
Example 7
Source File: Helpers.java    From vertx-kubernetes-workshop with Apache License 2.0 5 votes vote down vote up
/**
 * Utility method to report the completion/failure from a Single to a Routing Context.
 *
 * @param rc the routing context
 * @return the single observer to pass to {@link Single#subscribe()}
 */
public static SingleObserver<Buffer> toObserver(RoutingContext rc) {
    return new SingleObserver<Buffer>() {
        public void onSubscribe(@NonNull Disposable d) {
        }

        public void onSuccess(@NonNull Buffer payload) {
            rc.response().end(payload);
        }

        public void onError(Throwable error) {
            rc.fail(error);
        }
    };
}
 
Example 8
Source File: DynamicClientRegistrationTemplateHandler.java    From graviteeio-access-management with Apache License 2.0 5 votes vote down vote up
@Override
public void handle(RoutingContext context) {
    //Only allow access if dcr & template are enabled
    if(domain.isDynamicClientRegistrationEnabled() && domain.isDynamicClientRegistrationTemplateEnabled()) {
        context.next();
        return;
    }
    //Else fail...
    context.fail(new ClientRegistrationForbiddenException());
}
 
Example 9
Source File: UserRequestHandler.java    From graviteeio-access-management with Apache License 2.0 5 votes vote down vote up
protected void redirectToPage(RoutingContext context, Map<String, String> params, Throwable... exceptions) {
    try {
        if (exceptions != null && exceptions.length > 0) {
            logger.debug("Error user actions : " + params.get("error"), exceptions[0]);
        }
        String uri = UriBuilderRequest.resolveProxyRequest(context.request(), context.request().path(), params);
        doRedirect(context.response(), uri);
    } catch (Exception ex) {
        logger.error("An error occurs while redirecting to {}", context.request().absoluteURI(), ex);
        context.fail(503);
    }
}
 
Example 10
Source File: UserBodyRequestParseHandler.java    From graviteeio-access-management with Apache License 2.0 5 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("Form body not parsed - do you forget to include a BodyHandler?");
        }
        // check required parameters
        MultiMap params = req.formAttributes();
        Optional<String> missingParameter = requiredParams.stream().filter(param -> {
            String paramValue = params.get(param);
            if (paramValue == null) {
                logger.warn("No {} provided in form - did you forget to include a BodyHandler?", param);
                return true;
            }
            return false;
        }).findFirst();

        if (missingParameter.isPresent()) {
            redirectToPage(context, Collections.singletonMap(ERROR_PARAM, "missing_required_parameters"));
        } else {
            context.next();
        }
    }

}
 
Example 11
Source File: LoginCallbackFailureHandler.java    From graviteeio-access-management with Apache License 2.0 5 votes vote down vote up
private void redirectToLoginPage(RoutingContext context, Throwable throwable) {
    try {
        Client client = context.get(CLIENT_CONTEXT_KEY);
        Map<String, String> params = new HashMap<>();
        params.put(Parameters.CLIENT_ID, client.getClientId());
        params.put("error", "social_authentication_failed");
        params.put("error_description", UriBuilder.encodeURIComponent(throwable.getCause() != null ? throwable.getCause().getMessage() : throwable.getMessage()));
        String uri = UriBuilderRequest.resolveProxyRequest(context.request(), context.request().path().replaceFirst("/callback", ""), params);
        doRedirect(context.response(), uri);
    } catch (Exception ex) {
        logger.error("An error occurs while redirecting to the login page", ex);
        context.fail(503);
    }
}
 
Example 12
Source File: MFAEnrollEndpoint.java    From graviteeio-access-management with Apache License 2.0 5 votes vote down vote up
@Override
public void handle(RoutingContext routingContext) {
    HttpServerRequest req = routingContext.request();
    switch (req.method()) {
        case GET:
            renderPage(routingContext);
            break;
        case POST:
            saveEnrollment(routingContext);
            break;
        default:
            routingContext.fail(405);
    }
}
 
Example 13
Source File: UserProfileApiVerticle.java    From vertx-in-action with MIT License 5 votes vote down vote up
private void validateRegistration(RoutingContext ctx) {
  JsonObject body = jsonBody(ctx);
  if (anyRegistrationFieldIsMissing(body) || anyRegistrationFieldIsWrong(body)) {
    ctx.fail(400);
  } else {
    ctx.next();
  }
}
 
Example 14
Source File: RestApiUtil.java    From vertx-postgresql-starter with MIT License 5 votes vote down vote up
public static <T> T decodeBodyToObject(RoutingContext routingContext, Class<T> clazz) {
  try {
    return Json.decodeValue(routingContext.getBodyAsString("UTF-8"), clazz);
  } catch (DecodeException exception) {
    routingContext.fail(exception);
    return null;
  }
}
 
Example 15
Source File: ActionHelper.java    From introduction-to-eclipse-vertx with Apache License 2.0 5 votes vote down vote up
static Consumer<Throwable> onError(RoutingContext rc) {
    return err -> {
        if (err instanceof NoSuchElementException) {
            rc.response().setStatusCode(404).end(err.getMessage());
        } else {
            rc.fail(err);
        }
    };
}
 
Example 16
Source File: UserConsentPostEndpoint.java    From graviteeio-access-management with Apache License 2.0 5 votes vote down vote up
@Override
public void handle(RoutingContext routingContext) {
    // retrieve authorization request
    AuthorizationRequest authorizationRequest = routingContext.get(AUTHORIZATION_REQUEST_CONTEXT_KEY);

    // consent has been processed, replay authorization request
    try {
        final String authorizationRequestUrl = UriBuilderRequest.resolveProxyRequest(routingContext.request(), authorizationRequest.path(), authorizationRequest.parameters().toSingleValueMap());
        doRedirect(routingContext.response(), authorizationRequestUrl);
    } catch (Exception e) {
        LOGGER.error("An error occurs while handling authorization approval request", e);
        routingContext.fail(503);
    }
}
 
Example 17
Source File: DynamicClientAccessHandler.java    From graviteeio-access-management with Apache License 2.0 5 votes vote down vote up
@Override
public void handle(RoutingContext context) {
    //1st check if dynamic client registration is enabled.
    if(!domain.isDynamicClientRegistrationEnabled()) {
        context.fail(new ClientRegistrationForbiddenException());
        return;
    }

    context.next();
}
 
Example 18
Source File: UserProfileApiVerticle.java    From vertx-in-action with MIT License 5 votes vote down vote up
private void handleRegistrationError(RoutingContext ctx, Throwable err) {
  if (isIndexViolated(err)) {
    logger.error("Registration failure: {}", err.getMessage());
    ctx.fail(409);
  } else {
    fail500(ctx, err);
  }
}
 
Example 19
Source File: PublicApiVerticle.java    From vertx-in-action with MIT License 4 votes vote down vote up
private void sendBadGateway(RoutingContext ctx, Throwable err) {
  logger.error("Woops", err);
  ctx.fail(502);
}
 
Example 20
Source File: RestfulApiVerticle.java    From vertx-blueprint-todo-backend with Apache License 2.0 2 votes vote down vote up
/**
 * Send back a response with status 503 Service Unavailable.
 *
 * @param context routing context
 */
protected void serviceUnavailable(RoutingContext context) {
  context.fail(503);
}