Search in sources :

Example 6 with Linkable

use of org.structr.web.entity.Linkable in project structr by structr.

the class HtmlServlet method findPossibleEntryPointsByPath.

private List<Linkable> findPossibleEntryPointsByPath(final SecurityContext securityContext, final HttpServletRequest request, final String path) throws FrameworkException {
    final List<Linkable> possibleEntryPoints = (List<Linkable>) request.getAttribute(POSSIBLE_ENTRY_POINTS_KEY);
    if (CollectionUtils.isNotEmpty(possibleEntryPoints)) {
        return possibleEntryPoints;
    }
    if (path.length() > 0) {
        logger.debug("Requested path: {}", path);
        final Query pageQuery = StructrApp.getInstance(securityContext).nodeQuery();
        pageQuery.and(StructrApp.key(Page.class, "path"), path).andType(Page.class);
        final Result pages = pageQuery.getResult();
        final Query fileQuery = StructrApp.getInstance(securityContext).nodeQuery();
        fileQuery.and(StructrApp.key(AbstractFile.class, "path"), path).andTypes(File.class);
        final Result files = fileQuery.getResult();
        logger.debug("Found {} pages and {} files/folders", new Object[] { pages.size(), files.size() });
        final List<Linkable> linkables = (List<Linkable>) pages.getResults();
        linkables.addAll(files.getResults());
        request.setAttribute(POSSIBLE_ENTRY_POINTS_KEY, linkables);
        return linkables;
    }
    return Collections.EMPTY_LIST;
}
Also used : Query(org.structr.core.app.Query) Linkable(org.structr.web.entity.Linkable) List(java.util.List) LinkedList(java.util.LinkedList) Result(org.structr.core.Result)

Example 7 with Linkable

use of org.structr.web.entity.Linkable in project structr by structr.

the class HtmlServlet method doHead.

@Override
protected void doHead(final HttpServletRequest request, final HttpServletResponse response) {
    final Authenticator auth = getConfig().getAuthenticator();
    SecurityContext securityContext;
    List<Page> pages = null;
    boolean requestUriContainsUuids = false;
    final App app;
    try {
        assertInitialized();
        String path = request.getPathInfo();
        // isolate request authentication in a transaction
        try (final Tx tx = StructrApp.getInstance().tx()) {
            securityContext = auth.initializeAndExamineRequest(request, response);
            tx.success();
        }
        app = StructrApp.getInstance(securityContext);
        try (final Tx tx = app.tx()) {
            // Ensure access mode is frontend
            securityContext.setAccessMode(AccessMode.Frontend);
            request.setCharacterEncoding("UTF-8");
            // Important: Set character encoding before calling response.getWriter() !!, see Servlet Spec 5.4
            response.setCharacterEncoding("UTF-8");
            response.setContentLength(0);
            boolean dontCache = false;
            logger.debug("Path info {}", path);
            // don't continue on redirects
            if (response.getStatus() == 302) {
                tx.success();
                return;
            }
            final Principal user = securityContext.getUser(false);
            if (user != null) {
                // Don't cache if a user is logged in
                dontCache = true;
            }
            final RenderContext renderContext = RenderContext.getInstance(securityContext, request, response);
            renderContext.setResourceProvider(config.getResourceProvider());
            final EditMode edit = renderContext.getEditMode(user);
            DOMNode rootElement = null;
            AbstractNode dataNode = null;
            String[] uriParts = PathHelper.getParts(path);
            if ((uriParts == null) || (uriParts.length == 0)) {
                // find a visible page
                rootElement = findIndexPage(securityContext, pages, edit);
                logger.debug("No path supplied, trying to find index page");
            } else {
                if (rootElement == null) {
                    rootElement = findPage(securityContext, pages, path, edit);
                } else {
                    dontCache = true;
                }
            }
            if (rootElement == null) {
                // No page found
                // Look for a file
                File file = findFile(securityContext, request, path);
                if (file != null) {
                    // streamFile(securityContext, file, request, response, edit);
                    tx.success();
                    return;
                }
                if (uriParts != null) {
                    // store remaining path parts in request
                    Matcher matcher = threadLocalUUIDMatcher.get();
                    for (int i = 0; i < uriParts.length; i++) {
                        request.setAttribute(uriParts[i], i);
                        matcher.reset(uriParts[i]);
                        // set to "true" if part matches UUID pattern
                        requestUriContainsUuids |= matcher.matches();
                    }
                }
                if (!requestUriContainsUuids) {
                    // Try to find a data node by name
                    dataNode = findFirstNodeByName(securityContext, request, path);
                } else {
                    dataNode = findNodeByUuid(securityContext, PathHelper.getName(path));
                }
                if (dataNode != null && !(dataNode instanceof Linkable)) {
                    // Last path part matches a data node
                    // Remove last path part and try again searching for a page
                    // clear possible entry points
                    request.removeAttribute(POSSIBLE_ENTRY_POINTS_KEY);
                    rootElement = findPage(securityContext, pages, StringUtils.substringBeforeLast(path, PathHelper.PATH_SEP), edit);
                    renderContext.setDetailsDataObject(dataNode);
                    // Start rendering on data node
                    if (rootElement == null && dataNode instanceof DOMNode) {
                        rootElement = ((DOMNode) dataNode);
                    }
                }
            }
            // look for pages with HTTP Basic Authentication (must be done as superuser)
            if (rootElement == null) {
                final HttpBasicAuthResult authResult = checkHttpBasicAuth(request, response, path);
                switch(authResult.authState()) {
                    // Element with Basic Auth found and authentication succeeded
                    case Authenticated:
                        final Linkable result = authResult.getRootElement();
                        if (result instanceof Page) {
                            rootElement = (DOMNode) result;
                            renderContext.pushSecurityContext(authResult.getSecurityContext());
                        } else if (result instanceof File) {
                            // streamFile(authResult.getSecurityContext(), (File)result, request, response, EditMode.NONE);
                            tx.success();
                            return;
                        }
                        break;
                    // Page with Basic Auth found but not yet authenticated
                    case MustAuthenticate:
                        tx.success();
                        return;
                    // no Basic Auth for given path, go on
                    case NoBasicAuth:
                        break;
                }
            }
            // Still nothing found, do error handling
            if (rootElement == null) {
                // Check if security context has set an 401 status
                if (response.getStatus() == HttpServletResponse.SC_UNAUTHORIZED) {
                    try {
                        UiAuthenticator.writeUnauthorized(response);
                    } catch (IllegalStateException ise) {
                    }
                } else {
                    rootElement = notFound(response, securityContext);
                }
            }
            if (rootElement == null) {
                // no content
                response.setContentLength(0);
                response.getOutputStream().close();
                tx.success();
                return;
            }
            // check dont cache flag on page (if root element is a page)
            // but don't modify true to false
            dontCache |= rootElement.dontCache();
            if (EditMode.WIDGET.equals(edit) || dontCache) {
                setNoCacheHeaders(response);
            }
            if (!securityContext.isVisible(rootElement)) {
                rootElement = notFound(response, securityContext);
                if (rootElement == null) {
                    tx.success();
                    return;
                }
            }
            if (securityContext.isVisible(rootElement)) {
                if (!EditMode.WIDGET.equals(edit) && !dontCache && notModifiedSince(request, response, rootElement, dontCache)) {
                    response.getOutputStream().close();
                } else {
                    // prepare response
                    response.setCharacterEncoding("UTF-8");
                    String contentType = rootElement.getProperty(StructrApp.key(Page.class, "contentType"));
                    if (contentType == null) {
                        // Default
                        contentType = "text/html;charset=UTF-8";
                    }
                    if (contentType.equals("text/html")) {
                        contentType = contentType.concat(";charset=UTF-8");
                    }
                    response.setContentType(contentType);
                    setCustomResponseHeaders(response);
                    response.getOutputStream().close();
                }
            } else {
                notFound(response, securityContext);
                response.getOutputStream().close();
            }
            tx.success();
        } catch (Throwable fex) {
            logger.error("Exception while processing request", fex);
        }
    } catch (FrameworkException t) {
        logger.error("Exception while processing request", t);
        UiAuthenticator.writeInternalServerError(response);
    }
}
Also used : App(org.structr.core.app.App) StructrApp(org.structr.core.app.StructrApp) RenderContext(org.structr.web.common.RenderContext) Tx(org.structr.core.graph.Tx) FrameworkException(org.structr.common.error.FrameworkException) AbstractNode(org.structr.core.entity.AbstractNode) Matcher(java.util.regex.Matcher) ThreadLocalMatcher(org.structr.common.ThreadLocalMatcher) Page(org.structr.web.entity.dom.Page) SecurityContext(org.structr.common.SecurityContext) EditMode(org.structr.web.common.RenderContext.EditMode) Linkable(org.structr.web.entity.Linkable) DOMNode(org.structr.web.entity.dom.DOMNode) AbstractFile(org.structr.web.entity.AbstractFile) File(org.structr.web.entity.File) UiAuthenticator(org.structr.web.auth.UiAuthenticator) Authenticator(org.structr.core.auth.Authenticator) Principal(org.structr.core.entity.Principal)

Example 8 with Linkable

use of org.structr.web.entity.Linkable in project structr by structr.

the class HtmlServlet method findPossibleEntryPointsByUuid.

private List<Linkable> findPossibleEntryPointsByUuid(final SecurityContext securityContext, final HttpServletRequest request, final String uuid) throws FrameworkException {
    final List<Linkable> possibleEntryPoints = (List<Linkable>) request.getAttribute(POSSIBLE_ENTRY_POINTS_KEY);
    if (CollectionUtils.isNotEmpty(possibleEntryPoints)) {
        return possibleEntryPoints;
    }
    if (uuid.length() > 0) {
        logger.debug("Requested id: {}", uuid);
        final Query query = StructrApp.getInstance(securityContext).nodeQuery();
        query.and(GraphObject.id, uuid);
        query.and().orType(Page.class).orTypes(File.class);
        // Searching for pages needs super user context anyway
        Result results = query.getResult();
        logger.debug("{} results", results.size());
        request.setAttribute(POSSIBLE_ENTRY_POINTS_KEY, results.getResults());
        return (List<Linkable>) results.getResults();
    }
    return Collections.EMPTY_LIST;
}
Also used : Query(org.structr.core.app.Query) Linkable(org.structr.web.entity.Linkable) List(java.util.List) LinkedList(java.util.LinkedList) Page(org.structr.web.entity.dom.Page) Result(org.structr.core.Result)

Example 9 with Linkable

use of org.structr.web.entity.Linkable in project structr by structr.

the class LinkCommand method processMessage.

@Override
public void processMessage(final WebSocketMessage webSocketData) {
    final String sourceId = webSocketData.getId();
    final Map<String, Object> properties = webSocketData.getNodeData();
    final String targetId = (String) properties.get("targetId");
    final LinkSource sourceNode = (LinkSource) getNode(sourceId);
    final Linkable targetNode = (Linkable) getNode(targetId);
    if ((sourceNode != null) && (targetNode != null)) {
        try {
            sourceNode.setLinkable(targetNode);
        } catch (FrameworkException t) {
            getWebSocket().send(MessageBuilder.status().code(400).message(t.getMessage()).build(), true);
        }
    } else {
        getWebSocket().send(MessageBuilder.status().code(400).message("The LINK command needs id and targetId!").build(), true);
    }
}
Also used : FrameworkException(org.structr.common.error.FrameworkException) LinkSource(org.structr.web.entity.LinkSource) Linkable(org.structr.web.entity.Linkable)

Aggregations

Linkable (org.structr.web.entity.Linkable)9 Page (org.structr.web.entity.dom.Page)5 SecurityContext (org.structr.common.SecurityContext)4 FrameworkException (org.structr.common.error.FrameworkException)4 LinkSource (org.structr.web.entity.LinkSource)4 DOMNode (org.structr.web.entity.dom.DOMNode)4 IOException (java.io.IOException)3 App (org.structr.core.app.App)3 StructrApp (org.structr.core.app.StructrApp)3 AbstractNode (org.structr.core.entity.AbstractNode)3 Principal (org.structr.core.entity.Principal)3 Tx (org.structr.core.graph.Tx)3 LinkedList (java.util.LinkedList)2 List (java.util.List)2 AtomicBoolean (java.util.concurrent.atomic.AtomicBoolean)2 Matcher (java.util.regex.Matcher)2 ThreadLocalMatcher (org.structr.common.ThreadLocalMatcher)2 Result (org.structr.core.Result)2 Query (org.structr.core.app.Query)2 Authenticator (org.structr.core.auth.Authenticator)2