Search in sources :

Example 6 with VaadinServletRequest

use of com.vaadin.flow.server.VaadinServletRequest in project flow by vaadin.

the class DefaultTemplateParserTest method defaultParser_servletPathIsEmpty_returnsContent.

@Test
public void defaultParser_servletPathIsEmpty_returnsContent() {
    VaadinServletRequest request = (VaadinServletRequest) CurrentInstance.get(VaadinRequest.class);
    Mockito.when(request.getServletPath()).thenReturn("");
    Element element = DefaultTemplateParser.getInstance().getTemplateContent(ImportsInspectTemplate.class, "foo").getTemplateElement();
    Assert.assertTrue(element.getElementById("foo") != null);
}
Also used : Element(org.jsoup.nodes.Element) VaadinServletRequest(com.vaadin.flow.server.VaadinServletRequest) VaadinRequest(com.vaadin.flow.server.VaadinRequest) Test(org.junit.Test)

Example 7 with VaadinServletRequest

use of com.vaadin.flow.server.VaadinServletRequest in project flow by vaadin.

the class PushHandler method callWithUi.

/**
 * Find the UI for the atmosphere resource, lock it and invoke the callback.
 *
 * @param resource
 *            the atmosphere resource for the current request
 * @param callback
 *            the push callback to call when a UI is found and locked
 */
void callWithUi(final AtmosphereResource resource, final PushEventCallback callback) {
    AtmosphereRequest req = resource.getRequest();
    VaadinServletRequest vaadinRequest = new VaadinServletRequest(req, service);
    VaadinSession session = null;
    boolean isWebsocket = resource.transport() == TRANSPORT.WEBSOCKET;
    if (isWebsocket) {
        // For any HTTP request we have already started the request in the
        // servlet
        service.requestStart(vaadinRequest, null);
    }
    try {
        try {
            session = service.findVaadinSession(vaadinRequest);
            assert VaadinSession.getCurrent() == session;
        } catch (SessionExpiredException e) {
            sendNotificationAndDisconnect(resource, VaadinService.createSessionExpiredJSON(true));
            return;
        }
        UI ui = null;
        session.lock();
        try {
            ui = service.findUI(vaadinRequest);
            assert UI.getCurrent() == ui;
            if (ui == null) {
                sendNotificationAndDisconnect(resource, VaadinService.createUINotFoundJSON(true));
            } else {
                callback.run(resource, ui);
            }
        } catch (final IOException e) {
            callErrorHandler(session, e);
        } catch (final Exception e) {
            SystemMessages msg = service.getSystemMessages(HandlerHelper.findLocale(null, vaadinRequest), vaadinRequest);
            AtmosphereResource errorResource = resource;
            if (ui != null && ui.getInternals().getPushConnection() != null) {
                // We MUST use the opened push connection if there is one.
                // Otherwise we will write the response to the wrong request
                // when using streaming (the client -> server request
                // instead of the opened push channel)
                errorResource = ((AtmospherePushConnection) ui.getInternals().getPushConnection()).getResource();
            }
            sendNotificationAndDisconnect(errorResource, VaadinService.createCriticalNotificationJSON(msg.getInternalErrorCaption(), msg.getInternalErrorMessage(), null, msg.getInternalErrorURL()));
            callErrorHandler(session, e);
        } finally {
            try {
                session.unlock();
            } catch (Exception e) {
                getLogger().warn("Error while unlocking session", e);
            // can't call ErrorHandler, we (hopefully) don't have a lock
            }
        }
    } finally {
        try {
            if (isWebsocket) {
                service.requestEnd(vaadinRequest, null, session);
            }
        } catch (Exception e) {
            getLogger().warn("Error while ending request", e);
        // can't call ErrorHandler, we don't have a lock
        }
    }
}
Also used : AtmosphereRequest(org.atmosphere.cpr.AtmosphereRequest) VaadinSession(com.vaadin.flow.server.VaadinSession) UI(com.vaadin.flow.component.UI) AtmosphereResource(org.atmosphere.cpr.AtmosphereResource) VaadinServletRequest(com.vaadin.flow.server.VaadinServletRequest) SessionExpiredException(com.vaadin.flow.server.SessionExpiredException) SystemMessages(com.vaadin.flow.server.SystemMessages) IOException(java.io.IOException) InvalidUIDLSecurityKeyException(com.vaadin.flow.server.communication.ServerRpcHandler.InvalidUIDLSecurityKeyException) JsonException(elemental.json.JsonException) SessionExpiredException(com.vaadin.flow.server.SessionExpiredException) IOException(java.io.IOException)

Example 8 with VaadinServletRequest

use of com.vaadin.flow.server.VaadinServletRequest in project flow by vaadin.

the class AccessAnnotationCheckerTest method specialViewsMustBeAccessible.

@Test
public void specialViewsMustBeAccessible() {
    CurrentInstance.set(VaadinRequest.class, new VaadinServletRequest(createRequest(null), null));
    Assert.assertTrue(accessAnnotationChecker.hasAccess(ClientViewPlaceholder.class));
    Assert.assertTrue(accessAnnotationChecker.hasAccess(InternalServerError.class));
    Assert.assertTrue(accessAnnotationChecker.hasAccess(RouteNotFoundError.class));
}
Also used : VaadinServletRequest(com.vaadin.flow.server.VaadinServletRequest) ClientViewPlaceholder(com.vaadin.flow.component.internal.JavaScriptBootstrapUI.ClientViewPlaceholder) RouteNotFoundError(com.vaadin.flow.router.RouteNotFoundError) InternalServerError(com.vaadin.flow.router.InternalServerError) Test(org.junit.Test)

Example 9 with VaadinServletRequest

use of com.vaadin.flow.server.VaadinServletRequest in project flow by vaadin.

the class ViewAccessChecker method beforeEnter.

@Override
public void beforeEnter(BeforeEnterEvent beforeEnterEvent) {
    if (!enabled) {
        return;
    }
    Class<?> targetView = beforeEnterEvent.getNavigationTarget();
    VaadinServletRequest vaadinServletRequest = VaadinServletRequest.getCurrent();
    if (vaadinServletRequest == null) {
        // This is in a background thread and we cannot access the request
        // to check access
        getLogger().warn("Preventing navigation to " + targetView.getName() + " because no HTTP request is available for checking access.");
        beforeEnterEvent.rerouteToError(NotFoundException.class);
        return;
    }
    HttpServletRequest httpServletRequest = vaadinServletRequest.getHttpServletRequest();
    getLogger().debug("Checking access for view {}", targetView.getName());
    if (loginView != null && targetView == loginView) {
        getLogger().debug("Allowing access for login view {}", targetView.getName());
        return;
    }
    boolean hasAccess = accessAnnotationChecker.hasAccess(targetView, httpServletRequest);
    if (hasAccess) {
        getLogger().debug("Allowed access to view {}", targetView.getName());
        return;
    }
    getLogger().debug("Denied access to view {}", targetView.getName());
    if (httpServletRequest.getUserPrincipal() == null) {
        httpServletRequest.getSession().setAttribute(SESSION_STORED_REDIRECT, beforeEnterEvent.getLocation().getPathWithQueryParameters());
        if (loginView != null) {
            beforeEnterEvent.forwardTo(loginView);
        } else {
            // Prevent the view from being ceated
            beforeEnterEvent.rerouteToError(NotFoundException.class);
            if (loginUrl != null) {
                beforeEnterEvent.getUI().getPage().setLocation(loginUrl);
            }
        }
    } else if (isProductionMode(beforeEnterEvent)) {
        // Intentionally does not reveal if the route exists
        beforeEnterEvent.rerouteToError(NotFoundException.class);
    } else {
        beforeEnterEvent.rerouteToError(NotFoundException.class, "Access denied");
    }
}
Also used : HttpServletRequest(javax.servlet.http.HttpServletRequest) VaadinServletRequest(com.vaadin.flow.server.VaadinServletRequest) NotFoundException(com.vaadin.flow.router.NotFoundException)

Example 10 with VaadinServletRequest

use of com.vaadin.flow.server.VaadinServletRequest in project flow by vaadin.

the class EndpointInvoker method invoke.

/**
 * Invoke the given endpoint method with the given parameters if the user
 * has access to do so.
 *
 * @param endpointName
 *            the name of the endpoint
 * @param methodName
 *            the name of the method in the endpoint
 * @param body
 *            optional request body, that should be specified if the method
 *            called has parameters
 * @param request
 *            the HTTP request which should not be here in the end
 * @return the return value of the invoked endpoint method, wrapped in a
 *         response entity
 */
public ResponseEntity<String> invoke(String endpointName, String methodName, ObjectNode body, HttpServletRequest request) {
    VaadinEndpointData vaadinEndpointData = endpointRegistry.get(endpointName);
    if (vaadinEndpointData == null) {
        getLogger().debug("Endpoint '{}' not found", endpointName);
        return ResponseEntity.notFound().build();
    }
    Method methodToInvoke = vaadinEndpointData.getMethod(methodName).orElse(null);
    if (methodToInvoke == null) {
        getLogger().debug("Method '{}' not found in endpoint '{}'", methodName, endpointName);
        return ResponseEntity.notFound().build();
    }
    try {
        // Put a VaadinRequest in the instances object so as the request is
        // available in the end-point method
        VaadinServletService service = (VaadinServletService) VaadinService.getCurrent();
        CurrentInstance.set(VaadinRequest.class, new VaadinServletRequest(request, service));
        return invokeVaadinEndpointMethod(endpointName, methodName, methodToInvoke, body, vaadinEndpointData, request);
    } catch (JsonProcessingException e) {
        String errorMessage = String.format("Failed to serialize endpoint '%s' method '%s' response. " + "Double check method's return type or specify a custom mapper bean with qualifier '%s'", endpointName, methodName, EndpointController.VAADIN_ENDPOINT_MAPPER_BEAN_QUALIFIER);
        getLogger().error(errorMessage, e);
        return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR).body(createResponseErrorObject(errorMessage));
    } finally {
        CurrentInstance.set(VaadinRequest.class, null);
    }
}
Also used : VaadinServletRequest(com.vaadin.flow.server.VaadinServletRequest) VaadinServletService(com.vaadin.flow.server.VaadinServletService) Method(java.lang.reflect.Method) VaadinEndpointData(dev.hilla.EndpointRegistry.VaadinEndpointData) JsonProcessingException(com.fasterxml.jackson.core.JsonProcessingException)

Aggregations

VaadinServletRequest (com.vaadin.flow.server.VaadinServletRequest)40 Test (org.junit.Test)19 VaadinSession (com.vaadin.flow.server.VaadinSession)12 HttpServletRequest (javax.servlet.http.HttpServletRequest)9 VaadinServletService (com.vaadin.flow.server.VaadinServletService)8 IOException (java.io.IOException)7 DeploymentConfiguration (com.vaadin.flow.function.DeploymentConfiguration)6 MockVaadinServletService (com.vaadin.flow.server.MockVaadinServletService)6 MockVaadinSession (com.vaadin.flow.server.MockVaadinSession)6 VaadinRequest (com.vaadin.flow.server.VaadinRequest)6 VaadinResponse (com.vaadin.flow.server.VaadinResponse)6 UI (com.vaadin.flow.component.UI)5 Element (org.jsoup.nodes.Element)5 RouteConfiguration (com.vaadin.flow.router.RouteConfiguration)3 SessionExpiredException (com.vaadin.flow.server.SessionExpiredException)3 VaadinService (com.vaadin.flow.server.VaadinService)3 InvalidUIDLSecurityKeyException (com.vaadin.flow.server.communication.ServerRpcHandler.InvalidUIDLSecurityKeyException)3 MockDeploymentConfiguration (com.vaadin.tests.util.MockDeploymentConfiguration)3 JsonException (elemental.json.JsonException)3 ByteArrayInputStream (java.io.ByteArrayInputStream)3