Search in sources :

Example 16 with OpenemsException

use of io.openems.common.exceptions.OpenemsException in project openems by OpenEMS.

the class UserChangePasswordRestlet method handle.

@Override
public void handle(Request request, Response response) {
    super.handle(request, response);
    // get user
    User user;
    try {
        user = User.getUserByName(request.getClientInfo().getUser().getIdentifier());
    } catch (OpenemsException e) {
        // User not found
        throw new ResourceException(Status.CLIENT_ERROR_NOT_FOUND);
    }
    // check permission
    if (!isAuthenticatedAsRole(request, user.getRole())) {
        throw new ResourceException(Status.CLIENT_ERROR_UNAUTHORIZED);
    }
    // call handler methods
    if (request.getMethod().equals(Method.POST)) {
        JsonParser parser = new JsonParser();
        String httpPost = request.getEntityAsText();
        JsonObject jHttpPost = parser.parse(httpPost).getAsJsonObject();
        changePassword(user, jHttpPost);
    }
}
Also used : User(io.openems.api.security.User) JsonObject(com.google.gson.JsonObject) ResourceException(org.restlet.resource.ResourceException) OpenemsException(io.openems.common.exceptions.OpenemsException) JsonParser(com.google.gson.JsonParser)

Example 17 with OpenemsException

use of io.openems.common.exceptions.OpenemsException in project openems by OpenEMS.

the class WebsocketApiServer method _onOpen.

/**
 * Open event of websocket.
 */
@Override
protected void _onOpen(WebSocket websocket, ClientHandshake handshake) {
    // generate UUID for this websocket (browser tab)
    UUID uuid = UUID.randomUUID();
    // get token from cookie or generate new token
    String token;
    Optional<String> cookieTokenOpt = getFieldFromHandshakeCookie(handshake, "token");
    if (cookieTokenOpt.isPresent()) {
        token = cookieTokenOpt.get();
    } else {
        // Generate token (source: http://stackoverflow.com/a/41156)
        SecureRandom sr = SecureRandomSingleton.getInstance();
        token = new BigInteger(TOKEN_LENGTH, sr).toString(32);
    }
    // create new Handler and store it
    UiEdgeWebsocketHandler handler = new UiEdgeWebsocketHandler(websocket, apiWorker, token, uuid);
    this.handlers.put(uuid, handler);
    websocket.setAttachment(uuid);
    // login using token from the cookie
    if (cookieTokenOpt.isPresent()) {
        User user = this.sessionTokens.get(token);
        if (user != null) {
            // send reply and log
            try {
                this.handleAuthenticationSuccessful(handler, user);
                log.info("User [" + user.getName() + "] logged in by token");
                return;
            } catch (OpenemsException e) {
                WebSocketUtils.sendNotificationOrLogError(websocket, new JsonObject(), /* empty message id */
                LogBehaviour.WRITE_TO_LOG, Notification.ERROR, e.getMessage());
            }
        }
    }
    // if we are here, automatic authentication was not possible -> notify client
    WebSocketUtils.sendNotificationOrLogError(websocket, new JsonObject(), /* empty message id */
    LogBehaviour.WRITE_TO_LOG, Notification.EDGE_AUTHENTICATION_BY_TOKEN_FAILED, cookieTokenOpt.orElse(""));
}
Also used : User(io.openems.api.security.User) SecureRandom(java.security.SecureRandom) BigInteger(java.math.BigInteger) JsonObject(com.google.gson.JsonObject) OpenemsException(io.openems.common.exceptions.OpenemsException) UUID(java.util.UUID)

Example 18 with OpenemsException

use of io.openems.common.exceptions.OpenemsException in project openems by OpenEMS.

the class WebsocketApiServer method authenticate.

/**
 * Authenticates a user according to the "authenticate" message. Stores the User if valid.
 *
 * @param jAuthenticateElement
 * @param handler
 * @throws OpenemsException
 */
private void authenticate(JsonObject jAuthenticate, WebSocket websocket) throws OpenemsException {
    if (jAuthenticate.has("mode")) {
        String mode = JsonUtils.getAsString(jAuthenticate, "mode");
        switch(mode) {
            case "login":
                try {
                    /*
					 * Authenticate using password (and optionally username)
					 */
                    String password = JsonUtils.getAsString(jAuthenticate, "password");
                    Optional<String> usernameOpt = JsonUtils.getAsOptionalString(jAuthenticate, "username");
                    Optional<User> userOpt;
                    if (usernameOpt.isPresent()) {
                        userOpt = User.authenticate(usernameOpt.get(), password);
                    } else {
                        userOpt = User.authenticate(password);
                    }
                    if (!userOpt.isPresent()) {
                        throw new OpenemsException("Authentication failed");
                    }
                    // authentication successful
                    User user = userOpt.get();
                    UiEdgeWebsocketHandler handler = getHandlerOrCloseWebsocket(websocket);
                    this.sessionTokens.put(handler.getSessionToken(), user);
                    this.handleAuthenticationSuccessful(handler, user);
                } catch (OpenemsException e) {
                    /*
					 * send authentication failed reply
					 */
                    JsonObject jReply = DefaultMessages.uiLogoutReply();
                    WebSocketUtils.send(websocket, jReply);
                    log.info(e.getMessage());
                    return;
                }
                break;
            case "logout":
                /*
				 * Logout and close session
				 */
                String sessionToken = "none";
                String username = "UNKNOWN";
                try {
                    UiEdgeWebsocketHandler handler = this.getHandlerOrCloseWebsocket(websocket);
                    Optional<User> thisUserOpt = handler.getUserOpt();
                    if (thisUserOpt.isPresent()) {
                        username = thisUserOpt.get().getName();
                        handler.unsetUser();
                    }
                    sessionToken = handler.getSessionToken();
                    this.sessionTokens.remove(sessionToken);
                    log.info("User [" + username + "] logged out. Invalidated token [" + sessionToken + "]");
                    // find and close all websockets for this user
                    if (thisUserOpt.isPresent()) {
                        User thisUser = thisUserOpt.get();
                        for (UiEdgeWebsocketHandler h : this.handlers.values()) {
                            if (h.getUserOpt().isPresent()) {
                                User otherUser = h.getUserOpt().get();
                                if (otherUser.equals(thisUser)) {
                                    JsonObject jReply = DefaultMessages.uiLogoutReply();
                                    h.send(jReply);
                                    h.dispose();
                                }
                            }
                        }
                    }
                    JsonObject jReply = DefaultMessages.uiLogoutReply();
                    WebSocketUtils.send(websocket, jReply);
                } catch (OpenemsException e) {
                    WebSocketUtils.sendNotificationOrLogError(websocket, new JsonObject(), /* empty message id */
                    LogBehaviour.WRITE_TO_LOG, Notification.ERROR, "Unable to close session [" + sessionToken + "]: " + e.getMessage());
                }
        }
    }
}
Also used : User(io.openems.api.security.User) JsonObject(com.google.gson.JsonObject) OpenemsException(io.openems.common.exceptions.OpenemsException)

Example 19 with OpenemsException

use of io.openems.common.exceptions.OpenemsException in project openems by OpenEMS.

the class WebsocketApiServer method _onMessage.

@Override
protected void _onMessage(WebSocket websocket, JsonObject jMessage) {
    /*
		 * Authenticate
		 */
    Optional<JsonObject> jAuthenticateOpt = JsonUtils.getAsOptionalJsonObject(jMessage, "authenticate");
    if (jAuthenticateOpt.isPresent()) {
        // authenticate by username/password
        try {
            authenticate(jAuthenticateOpt.get(), websocket);
        } catch (OpenemsException e) {
            WebSocketUtils.sendNotificationOrLogError(websocket, new JsonObject(), /* empty message id */
            LogBehaviour.WRITE_TO_LOG, Notification.ERROR, e.getMessage());
        }
        return;
    }
    // get handler
    UiEdgeWebsocketHandler handler;
    try {
        handler = getHandlerOrCloseWebsocket(websocket);
    } catch (OpenemsException e) {
        WebSocketUtils.sendNotificationOrLogError(websocket, new JsonObject(), /* empty message id */
        LogBehaviour.WRITE_TO_LOG, Notification.ERROR, "onMessage Error: " + e.getMessage());
        return;
    }
    // get session Token from handler
    String token = handler.getSessionToken();
    if (!this.sessionTokens.containsKey(token)) {
        WebSocketUtils.sendNotificationOrLogError(websocket, new JsonObject(), /* empty message id */
        LogBehaviour.WRITE_TO_LOG, Notification.ERROR, "Token [" + token + "] is not anymore valid.");
        websocket.close();
        return;
    }
    // From here authentication was successful
    /*
		 * Rest -> forward to websocket handler
		 */
    handler.onMessage(jMessage);
}
Also used : JsonObject(com.google.gson.JsonObject) OpenemsException(io.openems.common.exceptions.OpenemsException)

Example 20 with OpenemsException

use of io.openems.common.exceptions.OpenemsException in project openems by OpenEMS.

the class WebsocketApiServer method getHandlerOrCloseWebsocket.

private UiEdgeWebsocketHandler getHandlerOrCloseWebsocket(WebSocket websocket) throws OpenemsException {
    Optional<UiEdgeWebsocketHandler> handlerOpt = getHandlerOpt(websocket);
    UUID uuid = websocket.getAttachment();
    UiEdgeWebsocketHandler handler = this.handlers.get(uuid);
    if (!handlerOpt.isPresent()) {
        // no handler! close websocket
        websocket.close();
        throw new OpenemsException("Websocket had no Handler. Closing websocket.");
    }
    return handler;
}
Also used : OpenemsException(io.openems.common.exceptions.OpenemsException) UUID(java.util.UUID)

Aggregations

OpenemsException (io.openems.common.exceptions.OpenemsException)52 JsonObject (com.google.gson.JsonObject)25 JsonElement (com.google.gson.JsonElement)11 Edge (io.openems.backend.metadata.api.Edge)8 HashMap (java.util.HashMap)8 JsonArray (com.google.gson.JsonArray)7 Channel (io.openems.api.channel.Channel)7 ConfigChannel (io.openems.api.channel.ConfigChannel)5 IOException (java.io.IOException)5 ArrayList (java.util.ArrayList)5 WriteChannel (io.openems.api.channel.WriteChannel)4 User (io.openems.api.security.User)4 Role (io.openems.common.session.Role)4 WriteJsonObject (io.openems.core.utilities.api.WriteJsonObject)4 JsonParser (com.google.gson.JsonParser)3 ChannelDoc (io.openems.api.doc.ChannelDoc)3 ConfigException (io.openems.api.exception.ConfigException)3 User (io.openems.backend.metadata.api.User)3 Map (java.util.Map)3 UUID (java.util.UUID)3