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