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);
}
}
}
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);
}
}
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);
}
}
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);
}
Aggregations