Search in sources :

Example 6 with Authenticator

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

the class ProxyServlet method doGet.

@Override
protected void doGet(final HttpServletRequest request, final HttpServletResponse response) {
    final PropertyKey<String> proxyUrlKey = StructrApp.key(User.class, "proxyUrl");
    final PropertyKey<String> proxyUsernameKey = StructrApp.key(User.class, "proxyUsernameKey");
    final PropertyKey<String> proxyPasswordKey = StructrApp.key(User.class, "proxyPasswordKey");
    final Authenticator auth = getConfig().getAuthenticator();
    SecurityContext securityContext;
    String content;
    if (auth == null) {
        final String errorMessage = "No authenticator class found. Check log for 'Missing authenticator key " + this.getClass().getSimpleName() + ".authenticator'";
        logger.error(errorMessage);
        try {
            final ServletOutputStream out = response.getOutputStream();
            content = errorPage(new Throwable(errorMessage));
            IOUtils.write(content, out);
        } catch (IOException ex) {
            logger.error("Could not write to response", ex);
        }
        return;
    }
    try {
        // isolate request authentication in a transaction
        try (final Tx tx = StructrApp.getInstance().tx()) {
            securityContext = auth.initializeAndExamineRequest(request, response);
            tx.success();
        }
        // Ensure access mode is frontend
        securityContext.setAccessMode(AccessMode.Frontend);
        String address = request.getParameter("url");
        final URI url = URI.create(address);
        String proxyUrl = request.getParameter("proxyUrl");
        String proxyUsername = request.getParameter("proxyUsername");
        String proxyPassword = request.getParameter("proxyPassword");
        String authUsername = request.getParameter("authUsername");
        String authPassword = request.getParameter("authPassword");
        String cookie = request.getParameter("cookie");
        final Principal user = securityContext.getCachedUser();
        if (user != null && StringUtils.isBlank(proxyUrl)) {
            proxyUrl = user.getProperty(proxyUrlKey);
            proxyUsername = user.getProperty(proxyUsernameKey);
            proxyPassword = user.getProperty(proxyPasswordKey);
        }
        content = HttpHelper.get(address, authUsername, authPassword, proxyUrl, proxyUsername, proxyPassword, cookie, Collections.EMPTY_MAP).replace("<head>", "<head>\n  <base href=\"" + url + "\">");
    } catch (Throwable t) {
        logger.error("Exception while processing request", t);
        content = errorPage(t);
    }
    try {
        final ServletOutputStream out = response.getOutputStream();
        IOUtils.write(content, out, "utf-8");
    } catch (IOException ex) {
        logger.error("Could not write to response", ex);
    }
}
Also used : Tx(org.structr.core.graph.Tx) ServletOutputStream(javax.servlet.ServletOutputStream) SecurityContext(org.structr.common.SecurityContext) IOException(java.io.IOException) URI(java.net.URI) UiAuthenticator(org.structr.web.auth.UiAuthenticator) Authenticator(org.structr.core.auth.Authenticator) Principal(org.structr.core.entity.Principal)

Example 7 with Authenticator

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

the class LoginCommand method processMessage.

// ~--- methods --------------------------------------------------------
@Override
public void processMessage(final WebSocketMessage webSocketData) {
    final String username = (String) webSocketData.getNodeData().get("username");
    final String password = (String) webSocketData.getNodeData().get("password");
    Principal user;
    if ((username != null) && (password != null)) {
        try {
            StructrWebSocket socket = this.getWebSocket();
            Authenticator auth = socket.getAuthenticator();
            user = auth.doLogin(socket.getRequest(), username, password);
            if (user != null) {
                String sessionId = webSocketData.getSessionId();
                if (sessionId == null) {
                    logger.debug("Unable to login {}: No sessionId found", new Object[] { username, password });
                    getWebSocket().send(MessageBuilder.status().code(403).build(), true);
                    return;
                }
                sessionId = SessionHelper.getShortSessionId(sessionId);
                try {
                    Actions.call(Actions.NOTIFICATION_LOGIN, user);
                } catch (UnlicensedException ex) {
                    ex.log(logger);
                }
                // Clear possible existing sessions
                SessionHelper.clearSession(sessionId);
                user.addSessionId(sessionId);
                // store token in response data
                webSocketData.getNodeData().clear();
                webSocketData.setSessionId(sessionId);
                webSocketData.getNodeData().put("username", user.getProperty(AbstractNode.name));
                // authenticate socket
                socket.setAuthenticated(sessionId, user);
                // send data..
                socket.send(webSocketData, false);
            }
        } catch (AuthenticationException e) {
            logger.info("Unable to login {}, probably wrong password", username);
            getWebSocket().send(MessageBuilder.status().code(403).build(), true);
        } catch (FrameworkException fex) {
            logger.warn("Unable to execute command", fex);
        }
    }
}
Also used : UnlicensedException(org.structr.common.error.UnlicensedException) FrameworkException(org.structr.common.error.FrameworkException) AuthenticationException(org.structr.core.auth.exception.AuthenticationException) StructrWebSocket(org.structr.websocket.StructrWebSocket) Principal(org.structr.core.entity.Principal) Authenticator(org.structr.core.auth.Authenticator)

Example 8 with Authenticator

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

the class GraphQLServlet method handleGraphQLRequest.

// ----- private methods -----
private void handleGraphQLRequest(final HttpServletRequest request, final HttpServletResponse response, final String query) throws IOException, FrameworkException {
    final SecurityContext securityContext;
    final Authenticator authenticator;
    try {
        // 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);
        if (securityContext != null) {
            // isolate write output
            try (final Tx tx = app.tx()) {
                final Document doc = GraphQLRequest.parse(new Parser(), query);
                if (doc != null) {
                    final List<ValidationError> errors = new Validator().validateDocument(SchemaService.getGraphQLSchema(), doc);
                    if (errors.isEmpty()) {
                        // no validation errors in query, do request
                        final GraphQLWriter graphQLWriter = new GraphQLWriter(true);
                        // no trailing semicolon so we dont trip MimeTypes.getContentTypeWithoutCharset
                        response.setContentType("application/json; charset=utf-8");
                        final Writer writer = response.getWriter();
                        graphQLWriter.stream(securityContext, writer, new GraphQLRequest(securityContext, doc, query));
                        // useful newline
                        writer.append("\n");
                    } else {
                        final Map<String, Object> map = new LinkedHashMap<>();
                        final Writer writer = response.getWriter();
                        final Gson gson = getGson();
                        map.put("errors", errors);
                        gson.toJson(map, writer);
                        // useful newline
                        writer.append("\n");
                        // send 422 status
                        response.setStatus(422);
                    }
                }
                tx.success();
            }
        }
    } catch (FrameworkException frameworkException) {
        // set status & write JSON output
        response.setStatus(frameworkException.getStatus());
        getGson().toJson(frameworkException, response.getWriter());
        response.getWriter().println();
    } catch (IllegalStateException | IllegalArgumentException iex) {
        final Map<String, Object> map = new LinkedHashMap<>();
        map.put("code", 422);
        map.put("message", iex.getMessage());
        // set status & write JSON output
        response.setStatus(422);
        getGson().toJson(map, response.getWriter());
        response.getWriter().println();
    } catch (UnsupportedOperationException uoe) {
        logger.warn("POST not supported");
        int code = HttpServletResponse.SC_BAD_REQUEST;
        response.setStatus(code);
        response.getWriter().append(RestMethodResult.jsonError(code, "POST not supported: " + uoe.getMessage()));
    } catch (Throwable t) {
        logger.warn("Exception in POST", t);
        int code = HttpServletResponse.SC_INTERNAL_SERVER_ERROR;
        response.setStatus(code);
        response.getWriter().append(RestMethodResult.jsonError(code, "JsonSyntaxException in POST: " + 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 : StructrApp(org.structr.core.app.StructrApp) App(org.structr.core.app.App) Gson(com.google.gson.Gson) Document(graphql.language.Document) LinkedHashMap(java.util.LinkedHashMap) GraphQLRequest(org.structr.core.graphql.GraphQLRequest) GraphQLWriter(org.structr.rest.serialization.GraphQLWriter) ValidationError(graphql.validation.ValidationError) Authenticator(org.structr.core.auth.Authenticator) Tx(org.structr.core.graph.Tx) FrameworkException(org.structr.common.error.FrameworkException) Parser(graphql.parser.Parser) SecurityContext(org.structr.common.SecurityContext) LinkedHashMap(java.util.LinkedHashMap) Map(java.util.Map) Validator(graphql.validation.Validator) Writer(java.io.Writer) GraphQLWriter(org.structr.rest.serialization.GraphQLWriter)

Example 9 with Authenticator

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

the class JsonRestServlet method doDelete.

// <editor-fold defaultstate="collapsed" desc="DELETE">
@Override
protected void doDelete(final HttpServletRequest request, final HttpServletResponse response) throws ServletException, IOException {
    SecurityContext securityContext = null;
    Authenticator authenticator = null;
    RestMethodResult result = null;
    Resource resource = null;
    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.optimizeNestedResourceChain(securityContext, request, resourceMap, propertyView);
            authenticator.checkResourceAccess(securityContext, request, resource.getResourceSignature(), propertyView.get(securityContext));
            tx.success();
        }
        // isolate doDelete
        boolean retry = true;
        while (retry) {
            try {
                result = resource.doDelete();
                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 DELETE", jsex);
        int code = HttpServletResponse.SC_BAD_REQUEST;
        response.setStatus(code);
        response.getWriter().append(RestMethodResult.jsonError(code, "JsonSyntaxException in DELETE: " + jsex.getMessage()));
    } catch (JsonParseException jpex) {
        logger.warn("JsonParseException in DELETE", jpex);
        int code = HttpServletResponse.SC_BAD_REQUEST;
        response.setStatus(code);
        response.getWriter().append(RestMethodResult.jsonError(code, "JsonSyntaxException in DELETE: " + jpex.getMessage()));
    } catch (Throwable t) {
        logger.warn("Exception in DELETE", t);
        int code = HttpServletResponse.SC_INTERNAL_SERVER_ERROR;
        response.setStatus(code);
        response.getWriter().append(RestMethodResult.jsonError(code, "JsonSyntaxException in DELETE: " + t.getMessage()));
    } finally {
        try {
            // response.getWriter().flush();
            response.getWriter().close();
        } catch (IOException 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) Tx(org.structr.core.graph.Tx) FrameworkException(org.structr.common.error.FrameworkException) Resource(org.structr.rest.resource.Resource) StaticRelationshipResource(org.structr.rest.resource.StaticRelationshipResource) IOException(java.io.IOException) RetryException(org.structr.api.RetryException) JsonParseException(com.google.gson.JsonParseException) JsonSyntaxException(com.google.gson.JsonSyntaxException) SecurityContext(org.structr.common.SecurityContext) Authenticator(org.structr.core.auth.Authenticator) RestMethodResult(org.structr.rest.RestMethodResult)

Example 10 with Authenticator

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

the class JsonRestServlet method doPut.

// </editor-fold>
// <editor-fold defaultstate="collapsed" desc="PUT">
@Override
protected void doPut(final HttpServletRequest request, final 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");
        // get reader before initalizing security context
        final String input = IOUtils.toString(request.getReader());
        // 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);
        final IJsonInput jsonInput = cleanAndParseJsonString(app, input);
        if (securityContext != null) {
            // isolate resource authentication
            try (final Tx tx = app.tx()) {
                // evaluate constraint chain
                resource = ResourceHelper.applyViewTransformation(request, securityContext, ResourceHelper.optimizeNestedResourceChain(securityContext, request, resourceMap, propertyView), propertyView);
                authenticator.checkResourceAccess(securityContext, request, resource.getResourceSignature(), propertyView.get(securityContext));
                tx.success();
            }
            // isolate doPut
            boolean retry = true;
            while (retry) {
                try (final Tx tx = app.tx()) {
                    result = resource.doPut(convertPropertySetToMap(jsonInput.getJsonInputs().get(0)));
                    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();
            }
        } else {
            // isolate write output
            try (final Tx tx = app.tx()) {
                result = new RestMethodResult(HttpServletResponse.SC_FORBIDDEN);
                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("PUT: Invalid JSON syntax", jsex.getMessage());
        int code = HttpServletResponse.SC_BAD_REQUEST;
        response.setStatus(code);
        response.getWriter().append(RestMethodResult.jsonError(code, "JsonSyntaxException in PUT: " + jsex.getMessage()));
    } catch (JsonParseException jpex) {
        logger.warn("PUT: Unable to parse JSON string", jpex.getMessage());
        int code = HttpServletResponse.SC_BAD_REQUEST;
        response.setStatus(code);
        response.getWriter().append(RestMethodResult.jsonError(code, "JsonSyntaxException in PUT: " + jpex.getMessage()));
    } catch (Throwable t) {
        logger.warn("Exception in PUT", t);
        logger.warn("", t);
        int code = HttpServletResponse.SC_INTERNAL_SERVER_ERROR;
        response.setStatus(code);
        response.getWriter().append(RestMethodResult.jsonError(code, "JsonSyntaxException in PUT: " + 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) Tx(org.structr.core.graph.Tx) FrameworkException(org.structr.common.error.FrameworkException) Resource(org.structr.rest.resource.Resource) StaticRelationshipResource(org.structr.rest.resource.StaticRelationshipResource) RetryException(org.structr.api.RetryException) JsonParseException(com.google.gson.JsonParseException) JsonSyntaxException(com.google.gson.JsonSyntaxException) SecurityContext(org.structr.common.SecurityContext) IJsonInput(org.structr.core.IJsonInput) Authenticator(org.structr.core.auth.Authenticator) RestMethodResult(org.structr.rest.RestMethodResult)

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