Search in sources :

Example 1 with StructrWebSocket

use of org.structr.websocket.StructrWebSocket 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 2 with StructrWebSocket

use of org.structr.websocket.StructrWebSocket in project structr by structr.

the class ListRemoteSyncablesCommand method processMessage.

@Override
public void processMessage(final WebSocketMessage webSocketData) {
    final Map<String, Object> properties = webSocketData.getNodeData();
    final String username = (String) properties.get("username");
    final String password = (String) properties.get("password");
    final String host = (String) properties.get("host");
    final String key = (String) properties.get("key");
    final String type = (String) properties.get("type");
    final Long port = (Long) properties.get("port");
    if (host != null && port != null && username != null && password != null && key != null) {
        final App app = StructrApp.getInstance();
        try (final Tx tx = app.tx()) {
            final StructrWebSocket webSocket = getWebSocket();
            final List<SyncableInfo> syncables = CloudService.doRemote(webSocket.getSecurityContext(), new SingleTransmission<>(new ListSyncables(type)), new HostInfo(username, password, host, port.intValue()), new WebsocketProgressListener(getWebSocket(), key, callback));
            if (syncables != null) {
                final List<GraphObject> result = new LinkedList<>();
                for (final SyncableInfo info : syncables) {
                    final GraphObjectMap map = new GraphObjectMap();
                    map.put(GraphObject.id, info.getId());
                    map.put(NodeInterface.name, info.getName());
                    map.put(File.size, info.getSize());
                    map.put(GraphObject.type, info.getType());
                    map.put(GraphObject.visibleToPublicUsers, info.isVisibleToPublicUsers());
                    map.put(GraphObject.visibleToAuthenticatedUsers, info.isVisibleToAuthenticatedUsers());
                    map.put(GraphObject.lastModifiedDate, info.getLastModified());
                    // check for existance
                    map.put(isSynchronized, isSynchronized(info));
                    result.add(map);
                }
                webSocketData.setResult(result);
                webSocket.send(webSocketData, true);
            }
            tx.success();
        } catch (FrameworkException fex) {
            getWebSocket().send(MessageBuilder.status().code(400).message(fex.getMessage()).build(), true);
        }
    } else {
        getWebSocket().send(MessageBuilder.status().code(400).message("The PULL command needs sourceId, username, password, host, port and key!").build(), true);
    }
}
Also used : StructrApp(org.structr.core.app.StructrApp) App(org.structr.core.app.App) Tx(org.structr.core.graph.Tx) FrameworkException(org.structr.common.error.FrameworkException) ListSyncables(org.structr.cloud.message.ListSyncables) StructrWebSocket(org.structr.websocket.StructrWebSocket) SyncableInfo(org.structr.cloud.message.SyncableInfo) GraphObject(org.structr.core.GraphObject) LinkedList(java.util.LinkedList) GraphObjectMap(org.structr.core.GraphObjectMap) GraphObject(org.structr.core.GraphObject) WebsocketProgressListener(org.structr.cloud.WebsocketProgressListener) HostInfo(org.structr.cloud.HostInfo)

Example 3 with StructrWebSocket

use of org.structr.websocket.StructrWebSocket in project structr by structr.

the class WrappedRestCommand method processMessage.

@Override
public void processMessage(final WebSocketMessage webSocketData) throws FrameworkException {
    final Map<String, Object> nodeData = webSocketData.getNodeData();
    final String method = (String) nodeData.get("method");
    if (method == null || !(method.equals("POST") || method.equals("PUT"))) {
        logger.warn("Method not supported: {}", method);
        getWebSocket().send(MessageBuilder.wrappedRest().code(422).message("Method not supported: " + method).build(), true);
        return;
    }
    ResourceProvider resourceProvider;
    try {
        resourceProvider = UiResourceProvider.class.newInstance();
    } catch (Throwable t) {
        logger.error("Couldn't establish a resource provider", t);
        getWebSocket().send(MessageBuilder.wrappedRest().code(422).message("Couldn't establish a resource provider").build(), true);
        return;
    }
    final Map<Pattern, Class<? extends Resource>> resourceMap = new LinkedHashMap<>();
    resourceMap.putAll(resourceProvider.getResources());
    final StructrWebSocket socket = this.getWebSocket();
    final String url = (String) nodeData.get("url");
    // mimic HTTP request
    final HttpServletRequest wrappedRequest = new HttpServletRequestWrapper(socket.getRequest()) {

        @Override
        public Enumeration<String> getParameterNames() {
            return new IteratorEnumeration(getParameterMap().keySet().iterator());
        }

        @Override
        public String getParameter(String key) {
            String[] p = getParameterMap().get(key);
            return p != null ? p[0] : null;
        }

        @Override
        public Map<String, String[]> getParameterMap() {
            String[] parts = StringUtils.split(getQueryString(), "&");
            Map<String, String[]> parameterMap = new HashMap();
            for (String p : parts) {
                String[] kv = StringUtils.split(p, "=");
                if (kv.length > 1) {
                    parameterMap.put(kv[0], new String[] { kv[1] });
                }
            }
            return parameterMap;
        }

        @Override
        public String getQueryString() {
            return StringUtils.substringAfter(url, "?");
        }

        @Override
        public String getPathInfo() {
            return StringUtils.substringBefore(url, "?");
        }

        @Override
        public StringBuffer getRequestURL() {
            return new StringBuffer(url);
        }
    };
    Resource resource;
    final StaticValue fakePropertyView = new StaticValue(PropertyView.Public);
    try {
        resource = ResourceHelper.applyViewTransformation(wrappedRequest, socket.getSecurityContext(), ResourceHelper.optimizeNestedResourceChain(socket.getSecurityContext(), wrappedRequest, resourceMap, fakePropertyView), fakePropertyView);
    } catch (IllegalPathException | NotFoundException e) {
        logger.warn("Illegal path for REST query");
        getWebSocket().send(MessageBuilder.wrappedRest().code(422).message("Illegal path for REST query").build(), true);
        return;
    }
    final String data = (String) nodeData.get("data");
    final Gson gson = new GsonBuilder().create();
    final Map<String, Object> jsonData = gson.fromJson(data, Map.class);
    RestMethodResult result = null;
    switch(method) {
        case "PUT":
            // we want to update data
            result = resource.doPut(jsonData);
            break;
        case "POST":
            // we either want to create data or call a method on an object
            result = resource.doPost(jsonData);
            break;
    }
    // right now we do not send messages
    if (result != null) {
    // getWebSocket().send(MessageBuilder.wrappedRest().code(result.getResponseCode()).message(result.jsonMessage()).build(), true);
    }
}
Also used : IllegalPathException(org.structr.rest.exception.IllegalPathException) HashMap(java.util.HashMap) LinkedHashMap(java.util.LinkedHashMap) StructrWebSocket(org.structr.websocket.StructrWebSocket) NotFoundException(org.structr.rest.exception.NotFoundException) Gson(com.google.gson.Gson) LinkedHashMap(java.util.LinkedHashMap) HttpServletRequest(javax.servlet.http.HttpServletRequest) HttpServletRequestWrapper(javax.servlet.http.HttpServletRequestWrapper) ResourceProvider(org.structr.rest.ResourceProvider) UiResourceProvider(org.structr.web.common.UiResourceProvider) Pattern(java.util.regex.Pattern) IteratorEnumeration(org.apache.commons.collections.iterators.IteratorEnumeration) GsonBuilder(com.google.gson.GsonBuilder) Resource(org.structr.rest.resource.Resource) StaticValue(org.structr.core.StaticValue) UiResourceProvider(org.structr.web.common.UiResourceProvider) RestMethodResult(org.structr.rest.RestMethodResult)

Example 4 with StructrWebSocket

use of org.structr.websocket.StructrWebSocket in project structr by structr.

the class GraphQLCommand method processMessage.

@Override
public void processMessage(final WebSocketMessage webSocketData) {
    final StructrWebSocket socket = getWebSocket();
    final SecurityContext securityContext = socket.getSecurityContext();
    final List<GraphObject> result = new LinkedList<>();
    final String query = (String) webSocketData.getNodeData().get("query");
    if (query != null) {
        if (securityContext != null) {
            try {
                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
                        result.addAll(createResult(securityContext, new GraphQLRequest(securityContext, doc, query)));
                    } else {
                        final Map<String, Object> map = new LinkedHashMap<>();
                        map.put("errors", errors);
                        logger.warn("Errors occured while processing GraphQL request.");
                        getWebSocket().send(MessageBuilder.status().data(map).code(422).message("Errors occured while processing GraphQL request.").build(), true);
                        return;
                    }
                }
            } catch (IOException ioex) {
                logger.warn("Could not process GraphQL request.", ioex);
                getWebSocket().send(MessageBuilder.status().code(422).message(ioex.getMessage()).build(), true);
                return;
            } catch (FrameworkException ex) {
                logger.warn("Could not process GraphQL request.", ex);
                getWebSocket().send(MessageBuilder.status().code(ex.getStatus()).message(ex.getMessage()).build(), true);
                return;
            }
        }
    }
    webSocketData.setResult(result);
    // send only over local connection (no broadcast)
    getWebSocket().send(webSocketData, true);
}
Also used : FrameworkException(org.structr.common.error.FrameworkException) StructrWebSocket(org.structr.websocket.StructrWebSocket) IOException(java.io.IOException) GraphObject(org.structr.core.GraphObject) Document(graphql.language.Document) LinkedList(java.util.LinkedList) Parser(graphql.parser.Parser) LinkedHashMap(java.util.LinkedHashMap) GraphQLRequest(org.structr.core.graphql.GraphQLRequest) SecurityContext(org.structr.common.SecurityContext) GraphObject(org.structr.core.GraphObject) ValidationError(graphql.validation.ValidationError) Validator(graphql.validation.Validator)

Aggregations

StructrWebSocket (org.structr.websocket.StructrWebSocket)4 FrameworkException (org.structr.common.error.FrameworkException)3 LinkedHashMap (java.util.LinkedHashMap)2 LinkedList (java.util.LinkedList)2 GraphObject (org.structr.core.GraphObject)2 Gson (com.google.gson.Gson)1 GsonBuilder (com.google.gson.GsonBuilder)1 Document (graphql.language.Document)1 Parser (graphql.parser.Parser)1 ValidationError (graphql.validation.ValidationError)1 Validator (graphql.validation.Validator)1 IOException (java.io.IOException)1 HashMap (java.util.HashMap)1 Pattern (java.util.regex.Pattern)1 HttpServletRequest (javax.servlet.http.HttpServletRequest)1 HttpServletRequestWrapper (javax.servlet.http.HttpServletRequestWrapper)1 IteratorEnumeration (org.apache.commons.collections.iterators.IteratorEnumeration)1 HostInfo (org.structr.cloud.HostInfo)1 WebsocketProgressListener (org.structr.cloud.WebsocketProgressListener)1 ListSyncables (org.structr.cloud.message.ListSyncables)1