Search in sources :

Example 11 with Authenticator

use of org.structr.core.auth.Authenticator in project structr by structr.

the class JsonRestServlet method doOptions.

// <editor-fold defaultstate="collapsed" desc="OPTIONS">
@Override
protected void doOptions(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
    final SecurityContext securityContext;
    final Authenticator authenticator;
    final Resource resource;
    RestMethodResult result = new RestMethodResult(HttpServletResponse.SC_BAD_REQUEST);
    try {
        assertInitialized();
        // first thing to do!
        request.setCharacterEncoding("UTF-8");
        response.setCharacterEncoding("UTF-8");
        response.setContentType("application/json; charset=utf-8");
        // isolate request authentication in a transaction
        try (final Tx tx = StructrApp.getInstance().tx()) {
            authenticator = config.getAuthenticator();
            securityContext = authenticator.initializeAndExamineRequest(request, response);
            tx.success();
        }
        final App app = StructrApp.getInstance(securityContext);
        // isolate resource authentication
        try (final Tx tx = app.tx()) {
            resource = ResourceHelper.applyViewTransformation(request, securityContext, ResourceHelper.optimizeNestedResourceChain(securityContext, request, resourceMap, propertyView), propertyView);
            authenticator.checkResourceAccess(securityContext, request, resource.getResourceSignature(), propertyView.get(securityContext));
            tx.success();
        }
        // isolate doOptions
        boolean retry = true;
        while (retry) {
            try (final Tx tx = app.tx()) {
                result = resource.doOptions();
                tx.success();
                retry = false;
            } catch (RetryException ddex) {
                retry = true;
            }
        }
        // isolate write output
        try (final Tx tx = app.tx()) {
            result.commitResponse(gson.get(), response);
            tx.success();
        }
    } catch (FrameworkException frameworkException) {
        // set status & write JSON output
        response.setStatus(frameworkException.getStatus());
        gson.get().toJson(frameworkException, response.getWriter());
        response.getWriter().println();
    } catch (JsonSyntaxException jsex) {
        logger.warn("JsonSyntaxException in OPTIONS", jsex);
        int code = HttpServletResponse.SC_BAD_REQUEST;
        response.setStatus(code);
        response.getWriter().append(RestMethodResult.jsonError(code, "JsonSyntaxException in OPTIONS: " + jsex.getMessage()));
    } catch (JsonParseException jpex) {
        logger.warn("JsonParseException in OPTIONS", jpex);
        int code = HttpServletResponse.SC_BAD_REQUEST;
        response.setStatus(code);
        response.getWriter().append(RestMethodResult.jsonError(code, "JsonSyntaxException in OPTIONS: " + jpex.getMessage()));
    } catch (Throwable t) {
        logger.warn("Exception in OPTIONS", t);
        int code = HttpServletResponse.SC_INTERNAL_SERVER_ERROR;
        response.setStatus(code);
        response.getWriter().append(RestMethodResult.jsonError(code, "JsonSyntaxException in OPTIONS: " + t.getMessage()));
    } finally {
        try {
            // response.getWriter().flush();
            response.getWriter().close();
        } catch (Throwable t) {
            logger.warn("Unable to flush and close response: {}", t.getMessage());
        }
    }
}
Also used : App(org.structr.core.app.App) StructrApp(org.structr.core.app.StructrApp) JsonSyntaxException(com.google.gson.JsonSyntaxException) Tx(org.structr.core.graph.Tx) FrameworkException(org.structr.common.error.FrameworkException) SecurityContext(org.structr.common.SecurityContext) Resource(org.structr.rest.resource.Resource) StaticRelationshipResource(org.structr.rest.resource.StaticRelationshipResource) RetryException(org.structr.api.RetryException) JsonParseException(com.google.gson.JsonParseException) Authenticator(org.structr.core.auth.Authenticator) RestMethodResult(org.structr.rest.RestMethodResult)

Example 12 with Authenticator

use of org.structr.core.auth.Authenticator in project structr by structr.

the class RegistrationResource method doPost.

@Override
public RestMethodResult doPost(Map<String, Object> propertySet) throws FrameworkException {
    boolean existingUser = false;
    if (propertySet.containsKey("eMail")) {
        final PropertyKey<String> confKeyKey = StructrApp.key(User.class, "confirmationKey");
        final PropertyKey<String> eMailKey = StructrApp.key(User.class, "eMail");
        final String emailString = (String) propertySet.get("eMail");
        if (StringUtils.isEmpty(emailString)) {
            return new RestMethodResult(HttpServletResponse.SC_BAD_REQUEST);
        }
        final String localeString = (String) propertySet.get("locale");
        final String confKey = UUID.randomUUID().toString();
        Principal user = StructrApp.getInstance().nodeQuery(User.class).and(eMailKey, emailString).getFirst();
        if (user != null) {
            // For existing users, update confirmation key
            user.setProperty(confKeyKey, confKey);
            existingUser = true;
        } else {
            final Authenticator auth = securityContext.getAuthenticator();
            user = createUser(securityContext, eMailKey, emailString, propertySet, Settings.RestUserAutocreate.getValue(), auth.getUserClass(), confKey);
        }
        if (user != null) {
            if (!sendInvitationLink(user, propertySet, confKey, localeString)) {
                // return 400 Bad request
                return new RestMethodResult(HttpServletResponse.SC_BAD_REQUEST);
            }
            // return 200 to distinguish from new users
            if (existingUser) {
                // return 200 OK
                return new RestMethodResult(HttpServletResponse.SC_OK);
            } else {
                // return 201 Created
                return new RestMethodResult(HttpServletResponse.SC_CREATED);
            }
        } else {
            // return 400 Bad request
            return new RestMethodResult(HttpServletResponse.SC_BAD_REQUEST);
        }
    } else {
        // return 400 Bad request
        return new RestMethodResult(HttpServletResponse.SC_BAD_REQUEST);
    }
}
Also used : RestMethodResult(org.structr.rest.RestMethodResult) Principal(org.structr.core.entity.Principal) Authenticator(org.structr.core.auth.Authenticator)

Example 13 with Authenticator

use of org.structr.core.auth.Authenticator 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 14 with Authenticator

use of org.structr.core.auth.Authenticator in project structr by structr.

the class HtmlServlet method doOptions.

@Override
protected void doOptions(final HttpServletRequest request, final HttpServletResponse response) {
    final Authenticator auth = config.getAuthenticator();
    try {
        assertInitialized();
        // isolate request authentication in a transaction
        try (final Tx tx = StructrApp.getInstance().tx()) {
            auth.initializeAndExamineRequest(request, response);
            tx.success();
        }
        response.setContentLength(0);
        response.setHeader("Allow", "GET,HEAD,OPTIONS");
    } catch (FrameworkException t) {
        logger.error("Exception while processing request", t);
        UiAuthenticator.writeInternalServerError(response);
    }
}
Also used : Tx(org.structr.core.graph.Tx) FrameworkException(org.structr.common.error.FrameworkException) UiAuthenticator(org.structr.web.auth.UiAuthenticator) Authenticator(org.structr.core.auth.Authenticator)

Aggregations

Authenticator (org.structr.core.auth.Authenticator)14 FrameworkException (org.structr.common.error.FrameworkException)12 Tx (org.structr.core.graph.Tx)12 App (org.structr.core.app.App)10 StructrApp (org.structr.core.app.StructrApp)10 SecurityContext (org.structr.common.SecurityContext)9 RestMethodResult (org.structr.rest.RestMethodResult)8 JsonParseException (com.google.gson.JsonParseException)7 JsonSyntaxException (com.google.gson.JsonSyntaxException)7 Resource (org.structr.rest.resource.Resource)7 RetryException (org.structr.api.RetryException)6 Principal (org.structr.core.entity.Principal)5 StaticRelationshipResource (org.structr.rest.resource.StaticRelationshipResource)5 UiAuthenticator (org.structr.web.auth.UiAuthenticator)4 IOException (java.io.IOException)3 Writer (java.io.Writer)3 DecimalFormat (java.text.DecimalFormat)3 LinkedHashMap (java.util.LinkedHashMap)2 LinkedList (java.util.LinkedList)2 Matcher (java.util.regex.Matcher)2