Search in sources :

Example 1 with User

use of io.openems.backend.metadata.api.User in project openems by OpenEMS.

the class UiWebsocketServer method _onOpen.

@Override
protected void _onOpen(WebSocket websocket, ClientHandshake handshake) {
    User user;
    // login using session_id from the cookie
    Optional<String> sessionIdOpt = getFieldFromHandshakeCookie(handshake, "session_id");
    try {
        if (sessionIdOpt.isPresent()) {
            // authenticate with Session-ID
            user = this.parent.metadataService.authenticate(sessionIdOpt.get());
        } else {
            // authenticate without Session-ID
            user = this.parent.metadataService.authenticate();
        }
    } catch (OpenemsException e) {
        // send connection failed to browser
        WebSocketUtils.sendOrLogError(websocket, DefaultMessages.uiLogoutReply());
        log.warn("User connection failed. Session [" + sessionIdOpt.orElse("") + "] Error [" + e.getMessage() + "].");
        websocket.closeConnection(CloseFrame.REFUSE, e.getMessage());
        return;
    }
    UUID uuid = UUID.randomUUID();
    synchronized (this.websocketsMap) {
        // add websocket to local cache
        this.websocketsMap.put(uuid, websocket);
    }
    // store userId together with the websocket
    websocket.setAttachment(new WebsocketData(user.getId(), uuid));
    // send connection successful to browser
    JsonArray jEdges = new JsonArray();
    for (Entry<Integer, Role> edgeRole : user.getEdgeRoles().entrySet()) {
        int edgeId = edgeRole.getKey();
        Role role = edgeRole.getValue();
        Edge edge;
        try {
            edge = this.parent.metadataService.getEdge(edgeId);
            JsonObject jEdge = edge.toJsonObject();
            jEdge.addProperty("role", role.toString());
            jEdges.add(jEdge);
        } catch (OpenemsException e) {
            log.warn("Unable to get Edge from MetadataService [ID:" + edgeId + "]: " + e.getMessage());
        }
    }
    log.info("User [" + user.getName() + "] connected with Session [" + sessionIdOpt.orElse("") + "].");
    JsonObject jReply = DefaultMessages.uiLoginSuccessfulReply("", /* empty token? */
    jEdges);
    WebSocketUtils.sendOrLogError(websocket, jReply);
}
Also used : User(io.openems.backend.metadata.api.User) JsonObject(com.google.gson.JsonObject) OpenemsException(io.openems.common.exceptions.OpenemsException) JsonArray(com.google.gson.JsonArray) Role(io.openems.common.session.Role) UUID(java.util.UUID) Edge(io.openems.backend.metadata.api.Edge)

Example 2 with User

use of io.openems.backend.metadata.api.User in project openems by OpenEMS.

the class File method refreshData.

private void refreshData() {
    if (this.edges.isEmpty()) {
        try {
            // read file
            FileReader fr = new FileReader(this.path);
            BufferedReader br = new BufferedReader(fr);
            String s;
            while ((s = br.readLine()) != null) {
                try {
                    String[] parameters = s.split(";");
                    String name = parameters[0];
                    String comment = parameters[1];
                    String producttype = parameters[2];
                    Role role = Role.getRole(parameters[3]);
                    int edgeId = Integer.parseInt(parameters[4]);
                    String apikey = parameters[5];
                    MyEdge edge = new MyEdge(edgeId, name, comment, producttype, role, apikey, new JsonObject());
                    edge.onSetConfig(jConfig -> {
                        log.debug("Edge [" + edgeId + "]. Update config: " + StringUtils.toShortString(jConfig, 100));
                    });
                    edge.onSetSoc(soc -> {
                        log.debug("Edge [" + edgeId + "]. Set SoC: " + soc);
                    });
                    edge.onSetIpv4(ipv4 -> {
                        log.debug("Edge [" + edgeId + "]. Set IPv4: " + ipv4);
                    });
                    edge.setOnline(this.edgeWebsocketService.isOnline(edge.getId()));
                    this.edges.put(edgeId, edge);
                } catch (Throwable e) {
                    log.error("Unable to parse line [" + s + "]. " + e.getClass().getSimpleName() + ": " + e.getMessage());
                }
            }
            fr.close();
        } catch (IOException e) {
            log.error("Unable to read file [" + this.path + "]: " + e.getMessage());
        }
        // refresh user
        this.user = new User(0, "admin");
        for (int edgeId : this.edges.keySet()) {
            this.user.addEdgeRole(edgeId, Role.ADMIN);
        }
    }
}
Also used : Role(io.openems.common.session.Role) User(io.openems.backend.metadata.api.User) BufferedReader(java.io.BufferedReader) JsonObject(com.google.gson.JsonObject) FileReader(java.io.FileReader) IOException(java.io.IOException)

Example 3 with User

use of io.openems.backend.metadata.api.User in project openems by OpenEMS.

the class UiWebsocketServer method _onMessage.

@Override
protected void _onMessage(WebSocket websocket, JsonObject jMessage) {
    // get current User
    WebsocketData data = websocket.getAttachment();
    int userId = data.getUserId();
    Optional<User> userOpt = this.parent.metadataService.getUser(userId);
    if (!userOpt.isPresent()) {
        WebSocketUtils.sendNotificationOrLogError(websocket, new JsonObject(), LogBehaviour.WRITE_TO_LOG, Notification.BACKEND_UNABLE_TO_READ_USER_DETAILS, userId);
        return;
    }
    User user = userOpt.get();
    // get MessageId from message
    Optional<JsonObject> jMessageIdOpt = JsonUtils.getAsOptionalJsonObject(jMessage, "messageId");
    // get EdgeId from message
    Optional<Integer> edgeIdOpt = JsonUtils.getAsOptionalInt(jMessage, "edgeId");
    if (jMessageIdOpt.isPresent() && edgeIdOpt.isPresent()) {
        JsonObject jMessageId = jMessageIdOpt.get();
        int edgeId = edgeIdOpt.get();
        // get Edge
        Edge edge;
        try {
            edge = this.parent.metadataService.getEdge(edgeId);
        } catch (OpenemsException e) {
            WebSocketUtils.sendNotificationOrLogError(websocket, jMessageId, LogBehaviour.WRITE_TO_LOG, Notification.BACKEND_UNABLE_TO_READ_EDGE_DETAILS, edgeId, e.getMessage());
            return;
        }
        /*
			 * verify that User is allowed to access Edge
			 */
        if (!user.getEdgeRole(edgeId).isPresent()) {
            WebSocketUtils.sendNotificationOrLogError(websocket, jMessageId, LogBehaviour.WRITE_TO_LOG, Notification.BACKEND_FORWARD_TO_EDGE_NOT_ALLOWED, edge.getName(), user.getName());
            return;
        }
        /*
			 * Query historic data
			 */
        Optional<JsonObject> jHistoricDataOpt = JsonUtils.getAsOptionalJsonObject(jMessage, "historicData");
        if (jHistoricDataOpt.isPresent()) {
            JsonObject jHistoricData = jHistoricDataOpt.get();
            log.info("User [" + user.getName() + "] queried historic data for Edge [" + edge.getName() + "]: " + StringUtils.toShortString(jHistoricData, 50));
            this.historicData(websocket, jMessageId, edgeId, jHistoricData);
            return;
        }
        /*
			 * Subscribe to currentData
			 */
        Optional<JsonObject> jCurrentDataOpt = JsonUtils.getAsOptionalJsonObject(jMessage, "currentData");
        if (jCurrentDataOpt.isPresent()) {
            JsonObject jCurrentData = jCurrentDataOpt.get();
            log.info("User [" + user.getName() + "] subscribed to current data for Edge [" + edge.getName() + "]: " + StringUtils.toShortString(jCurrentData, 50));
            this.currentData(websocket, data, jMessageId, edgeId, jCurrentData);
            return;
        }
        /*
			 * Serve "Config -> Query" from cache
			 */
        Optional<JsonObject> jConfigOpt = JsonUtils.getAsOptionalJsonObject(jMessage, "config");
        if (jConfigOpt.isPresent()) {
            JsonObject jConfig = jConfigOpt.get();
            switch(JsonUtils.getAsOptionalString(jConfig, "mode").orElse("")) {
                case "query":
                    /*
					 * Query current config
					 */
                    log.info("User [" + user.getName() + "] queried config for Edge [" + edge.getName() + "]: " + StringUtils.toShortString(jConfig, 50));
                    JsonObject jReply = DefaultMessages.configQueryReply(jMessageId, edge.getConfig());
                    WebSocketUtils.sendOrLogError(websocket, jReply);
                    return;
            }
        }
        /*
			 * Forward to OpenEMS Edge
			 */
        if (jMessage.has("config") || jMessage.has("log") || jMessage.has("system")) {
            try {
                log.info("User [" + user.getName() + "] forward message to Edge [" + edge.getName() + "]: " + StringUtils.toShortString(jMessage, 100));
                Optional<Role> roleOpt = user.getEdgeRole(edgeId);
                JsonObject j = DefaultMessages.prepareMessageForForwardToEdge(jMessage, data.getUuid(), roleOpt);
                this.parent.edgeWebsocketService.forwardMessageFromUi(edgeId, j);
            } catch (OpenemsException e) {
                WebSocketUtils.sendNotificationOrLogError(websocket, jMessageId, LogBehaviour.WRITE_TO_LOG, Notification.EDGE_UNABLE_TO_FORWARD, edge.getName(), e.getMessage());
            }
        }
    }
}
Also used : Role(io.openems.common.session.Role) User(io.openems.backend.metadata.api.User) JsonObject(com.google.gson.JsonObject) OpenemsException(io.openems.common.exceptions.OpenemsException) Edge(io.openems.backend.metadata.api.Edge)

Example 4 with User

use of io.openems.backend.metadata.api.User in project openems by OpenEMS.

the class Odoo method authenticate.

/**
 * Tries to authenticate at the Odoo server using a sessionId from a cookie.
 *
 * @param sessionId
 * @return
 * @throws OpenemsException
 */
@Override
public User authenticate(String sessionId) throws OpenemsException {
    HttpURLConnection connection = null;
    try {
        // send request to Odoo
        String charset = "US-ASCII";
        String query = String.format("session_id=%s", URLEncoder.encode(sessionId, charset));
        connection = (HttpURLConnection) new URL(this.url + "/openems_backend/info?" + query).openConnection();
        // 5 secs
        connection.setConnectTimeout(5000);
        // 5 secs
        connection.setReadTimeout(5000);
        connection.setRequestProperty("Accept-Charset", charset);
        connection.setRequestMethod("POST");
        connection.setDoOutput(true);
        connection.setRequestProperty("Content-Type", "application/json");
        OutputStreamWriter out = new OutputStreamWriter(connection.getOutputStream());
        out.write("{}");
        out.flush();
        out.close();
        InputStream is = connection.getInputStream();
        BufferedReader br = new BufferedReader(new InputStreamReader(is));
        String line = null;
        while ((line = br.readLine()) != null) {
            JsonObject j = (new JsonParser()).parse(line).getAsJsonObject();
            if (j.has("error")) {
                JsonObject jError = JsonUtils.getAsJsonObject(j, "error");
                String errorMessage = JsonUtils.getAsString(jError, "message");
                throw new OpenemsException("Odoo replied with error: " + errorMessage);
            }
            if (j.has("result")) {
                // parse the result
                JsonObject jResult = JsonUtils.getAsJsonObject(j, "result");
                JsonObject jUser = JsonUtils.getAsJsonObject(jResult, "user");
                User user = new // 
                User(// 
                JsonUtils.getAsInt(jUser, "id"), JsonUtils.getAsString(jUser, "name"));
                JsonArray jDevices = JsonUtils.getAsJsonArray(jResult, "devices");
                for (JsonElement jDevice : jDevices) {
                    int edgeId = JsonUtils.getAsInt(jDevice, "id");
                    Optional<Edge> edgeOpt = this.getEdgeOpt(edgeId);
                    if (edgeOpt.isPresent()) {
                        Edge edge = edgeOpt.get();
                        synchronized (this.edges) {
                            this.edges.putIfAbsent(edge.getId(), edge);
                        }
                    }
                    user.addEdgeRole(edgeId, Role.getRole(JsonUtils.getAsString(jDevice, "role")));
                }
                synchronized (this.users) {
                    this.users.put(user.getId(), user);
                }
                return user;
            }
        }
        throw new OpenemsException("No matching user found");
    } catch (IOException e) {
        throw new OpenemsException("IOException while reading from Odoo: " + e.getMessage());
    } finally {
        if (connection != null) {
            connection.disconnect();
        }
    }
}
Also used : User(io.openems.backend.metadata.api.User) InputStreamReader(java.io.InputStreamReader) InputStream(java.io.InputStream) JsonObject(com.google.gson.JsonObject) OpenemsException(io.openems.common.exceptions.OpenemsException) IOException(java.io.IOException) URL(java.net.URL) JsonArray(com.google.gson.JsonArray) HttpURLConnection(java.net.HttpURLConnection) JsonElement(com.google.gson.JsonElement) BufferedReader(java.io.BufferedReader) OutputStreamWriter(java.io.OutputStreamWriter) Edge(io.openems.backend.metadata.api.Edge) JsonParser(com.google.gson.JsonParser)

Example 5 with User

use of io.openems.backend.metadata.api.User in project openems by OpenEMS.

the class Dummy method authenticate.

@Override
public User authenticate(String sessionId) throws OpenemsException {
    int id = this.nextUserId++;
    User user = new User(id, "USER:" + sessionId);
    for (int edgeId : this.edges.keySet()) {
        user.addEdgeRole(edgeId, Role.ADMIN);
    }
    this.users.put(id, user);
    return user;
}
Also used : User(io.openems.backend.metadata.api.User)

Aggregations

User (io.openems.backend.metadata.api.User)5 JsonObject (com.google.gson.JsonObject)4 Edge (io.openems.backend.metadata.api.Edge)3 OpenemsException (io.openems.common.exceptions.OpenemsException)3 Role (io.openems.common.session.Role)3 JsonArray (com.google.gson.JsonArray)2 BufferedReader (java.io.BufferedReader)2 IOException (java.io.IOException)2 JsonElement (com.google.gson.JsonElement)1 JsonParser (com.google.gson.JsonParser)1 FileReader (java.io.FileReader)1 InputStream (java.io.InputStream)1 InputStreamReader (java.io.InputStreamReader)1 OutputStreamWriter (java.io.OutputStreamWriter)1 HttpURLConnection (java.net.HttpURLConnection)1 URL (java.net.URL)1 UUID (java.util.UUID)1