Search in sources :

Example 1 with User

use of io.openems.api.security.User in project openems by OpenEMS.

the class Config method getUsersJson.

private JsonObject getUsersJson() {
    JsonObject jUsers = new JsonObject();
    for (User user : User.getUsers()) {
        JsonObject jUser = new JsonObject();
        jUser.addProperty("password", user.getPasswordBase64());
        jUser.addProperty("salt", user.getSaltBase64());
        jUsers.add(user.getName(), jUser);
    }
    return jUsers;
}
Also used : User(io.openems.api.security.User) JsonObject(com.google.gson.JsonObject)

Example 2 with User

use of io.openems.api.security.User in project openems by OpenEMS.

the class OpenemsVerifier method verify.

@Override
public int verify(Request request, Response response) {
    if (request.getChallengeResponse() == null) {
        log.warn("Authentication failed: No authentication data available.");
        return RESULT_MISSING;
    } else {
        String username = getIdentifier(request, response);
        String password = new String(getSecret(request, response));
        Optional<User> userOpt = User.authenticate(username, password);
        if (userOpt.isPresent()) {
            User user = userOpt.get();
            request.getClientInfo().setUser(new org.restlet.security.User(user.getName()));
            request.getChallengeResponse().setIdentifier(user.getName());
            return RESULT_VALID;
        } else {
            log.warn("Authentication failed.");
            return RESULT_INVALID;
        }
    }
}
Also used : User(io.openems.api.security.User)

Example 3 with User

use of io.openems.api.security.User 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 4 with User

use of io.openems.api.security.User 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 5 with User

use of io.openems.api.security.User 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)

Aggregations

User (io.openems.api.security.User)6 JsonObject (com.google.gson.JsonObject)4 OpenemsException (io.openems.common.exceptions.OpenemsException)4 JsonParser (com.google.gson.JsonParser)1 BigInteger (java.math.BigInteger)1 SecureRandom (java.security.SecureRandom)1 UUID (java.util.UUID)1 ResourceException (org.restlet.resource.ResourceException)1