Improve functionality of UI interceptor

feature/appm-store/pbac
lasanthaDLPDS 5 years ago
parent 173fdd53ae
commit b5ee0bdb8c

@ -21,7 +21,6 @@ import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory; import org.apache.commons.logging.LogFactory;
import org.wso2.carbon.device.application.mgt.api.services.ConfigRetrieveAPI; import org.wso2.carbon.device.application.mgt.api.services.ConfigRetrieveAPI;
import org.wso2.carbon.device.application.mgt.common.config.UIConfiguration; import org.wso2.carbon.device.application.mgt.common.config.UIConfiguration;
import org.wso2.carbon.device.application.mgt.common.exception.LifecycleManagementException;
import org.wso2.carbon.device.application.mgt.common.services.AppmDataHandler; import org.wso2.carbon.device.application.mgt.common.services.AppmDataHandler;
import org.wso2.carbon.device.application.mgt.core.util.APIUtil; import org.wso2.carbon.device.application.mgt.core.util.APIUtil;

@ -20,7 +20,6 @@ package org.wso2.carbon.device.application.mgt.common;
public class ProxyResponse { public class ProxyResponse {
private int code; private int code;
private String url;
private String data; private String data;
private String executorResponse; private String executorResponse;
@ -28,10 +27,6 @@ public class ProxyResponse {
public void setCode(int code) { this.code = code; } public void setCode(int code) { this.code = code; }
public String getUrl() { return url; }
public void setUrl(String url) { this.url = url; }
public String getData() { return data; } public String getData() { return data; }
public void setData(String data) { this.data = data; } public void setData(String data) { this.data = data; }

@ -55,6 +55,7 @@ import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse; import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession; import javax.servlet.http.HttpSession;
import java.io.IOException; import java.io.IOException;
import java.util.Arrays;
import java.util.Enumeration; import java.util.Enumeration;
import java.util.List; import java.util.List;
@ -91,10 +92,10 @@ public class InvokerHandler extends HttpServlet {
} }
if (proxyResponse.getExecutorResponse().contains(HandlerConstants.EXECUTOR_EXCEPTION_PREFIX)) { if (proxyResponse.getExecutorResponse().contains(HandlerConstants.EXECUTOR_EXCEPTION_PREFIX)) {
log.error("Error occurred while invoking the API endpoint."); log.error("Error occurred while invoking the API endpoint.");
HandlerUtil.handleError(req, resp, serverUrl, platform, proxyResponse); HandlerUtil.handleError(resp, proxyResponse);
return; return;
} }
HandlerUtil.handleSuccess(req, resp, serverUrl, platform, proxyResponse); HandlerUtil.handleSuccess(resp, proxyResponse);
} }
} catch (FileUploadException e) { } catch (FileUploadException e) {
log.error("Error occurred when processing Multipart POST request.", e); log.error("Error occurred when processing Multipart POST request.", e);
@ -119,10 +120,10 @@ public class InvokerHandler extends HttpServlet {
} }
if (proxyResponse.getExecutorResponse().contains(HandlerConstants.EXECUTOR_EXCEPTION_PREFIX)) { if (proxyResponse.getExecutorResponse().contains(HandlerConstants.EXECUTOR_EXCEPTION_PREFIX)) {
log.error("Error occurred while invoking the API endpoint."); log.error("Error occurred while invoking the API endpoint.");
HandlerUtil.handleError(req, resp, serverUrl, platform, proxyResponse); HandlerUtil.handleError(resp, proxyResponse);
return; return;
} }
HandlerUtil.handleSuccess(req, resp, serverUrl, platform, proxyResponse); HandlerUtil.handleSuccess(resp, proxyResponse);
} }
} catch (IOException e) { } catch (IOException e) {
log.error("Error occurred when processing GET request.", e); log.error("Error occurred when processing GET request.", e);
@ -146,10 +147,10 @@ public class InvokerHandler extends HttpServlet {
} }
if (proxyResponse.getExecutorResponse().contains(HandlerConstants.EXECUTOR_EXCEPTION_PREFIX)) { if (proxyResponse.getExecutorResponse().contains(HandlerConstants.EXECUTOR_EXCEPTION_PREFIX)) {
log.error("Error occurred while invoking the API endpoint."); log.error("Error occurred while invoking the API endpoint.");
HandlerUtil.handleError(req, resp, serverUrl, platform, proxyResponse); HandlerUtil.handleError(resp, proxyResponse);
return; return;
} }
HandlerUtil.handleSuccess(req, resp, serverUrl, platform, proxyResponse); HandlerUtil.handleSuccess(resp, proxyResponse);
} }
} catch (FileUploadException e) { } catch (FileUploadException e) {
log.error("Error occurred when processing Multipart PUT request.", e); log.error("Error occurred when processing Multipart PUT request.", e);
@ -174,10 +175,10 @@ public class InvokerHandler extends HttpServlet {
} }
if (proxyResponse.getExecutorResponse().contains(HandlerConstants.EXECUTOR_EXCEPTION_PREFIX)) { if (proxyResponse.getExecutorResponse().contains(HandlerConstants.EXECUTOR_EXCEPTION_PREFIX)) {
log.error("Error occurred while invoking the API endpoint."); log.error("Error occurred while invoking the API endpoint.");
HandlerUtil.handleError(req, resp, serverUrl, platform, proxyResponse); HandlerUtil.handleError(resp, proxyResponse);
return; return;
} }
HandlerUtil.handleSuccess(req, resp, serverUrl, platform, proxyResponse); HandlerUtil.handleSuccess(resp, proxyResponse);
} }
} catch (IOException e) { } catch (IOException e) {
log.error("Error occurred when processing DELETE request.", e); log.error("Error occurred when processing DELETE request.", e);
@ -228,7 +229,13 @@ public class InvokerHandler extends HttpServlet {
*/ */
private String generateBackendRequestURL(HttpServletRequest req) { private String generateBackendRequestURL(HttpServletRequest req) {
StringBuilder urlBuilder = new StringBuilder(); StringBuilder urlBuilder = new StringBuilder();
urlBuilder.append(serverUrl).append(HandlerConstants.API_COMMON_CONTEXT).append(req.getPathInfo()); String endpointUrl = Arrays.stream(HandlerConstants.SKIPPING_API_CONTEXT)
.anyMatch(contextPath -> contextPath.contains(req.getPathInfo())) ?
serverUrl :
req.getScheme() + HandlerConstants.SCHEME_SEPARATOR + System.getProperty("iot.gateway.host")
+ HandlerConstants.COLON + HandlerUtil.getGatewayPort(req.getScheme());
urlBuilder.append(endpointUrl).append(HandlerConstants.API_COMMON_CONTEXT).append(req.getPathInfo());
if (StringUtils.isNotEmpty(req.getQueryString())) { if (StringUtils.isNotEmpty(req.getQueryString())) {
urlBuilder.append("?").append(req.getQueryString()); urlBuilder.append("?").append(req.getQueryString());
} }
@ -275,7 +282,7 @@ public class InvokerHandler extends HttpServlet {
if (session == null) { if (session == null) {
log.error("Unauthorized, You are not logged in. Please log in to the portal"); log.error("Unauthorized, You are not logged in. Please log in to the portal");
handleError(req, resp, HttpStatus.SC_UNAUTHORIZED); handleError(resp, HttpStatus.SC_UNAUTHORIZED);
return false; return false;
} }
@ -283,13 +290,13 @@ public class InvokerHandler extends HttpServlet {
platform = (String) session.getAttribute(HandlerConstants.PLATFORM); platform = (String) session.getAttribute(HandlerConstants.PLATFORM);
if (authData == null) { if (authData == null) {
log.error("Unauthorized, Access token not found in the current session"); log.error("Unauthorized, Access token not found in the current session");
handleError(req, resp, HttpStatus.SC_UNAUTHORIZED); handleError(resp, HttpStatus.SC_UNAUTHORIZED);
return false; return false;
} }
if (req.getMethod() == null) { if (req.getMethod() == null) {
log.error("Bad Request, Request method is empty"); log.error("Bad Request, Request method is empty");
handleError(req, resp, HttpStatus.SC_BAD_REQUEST); handleError(resp, HttpStatus.SC_BAD_REQUEST);
return false; return false;
} }
return true; return true;
@ -311,7 +318,7 @@ public class InvokerHandler extends HttpServlet {
ProxyResponse proxyResponse = HandlerUtil.execute(httpRequest); ProxyResponse proxyResponse = HandlerUtil.execute(httpRequest);
if (proxyResponse.getExecutorResponse().contains(HandlerConstants.EXECUTOR_EXCEPTION_PREFIX)) { if (proxyResponse.getExecutorResponse().contains(HandlerConstants.EXECUTOR_EXCEPTION_PREFIX)) {
log.error("Error occurred while invoking the API after refreshing the token."); log.error("Error occurred while invoking the API after refreshing the token.");
HandlerUtil.handleError(req, resp, serverUrl, platform, proxyResponse); HandlerUtil.handleError(resp, proxyResponse);
return null; return null;
} }
return proxyResponse; return proxyResponse;
@ -337,7 +344,7 @@ public class InvokerHandler extends HttpServlet {
HttpSession session = req.getSession(false); HttpSession session = req.getSession(false);
if (session == null) { if (session == null) {
log.error("Couldn't find a session, hence it is required to login and proceed."); log.error("Couldn't find a session, hence it is required to login and proceed.");
handleError(req, resp, HttpStatus.SC_UNAUTHORIZED); handleError(resp, HttpStatus.SC_UNAUTHORIZED);
return false; return false;
} }
@ -354,7 +361,7 @@ public class InvokerHandler extends HttpServlet {
ProxyResponse tokenResultResponse = HandlerUtil.execute(tokenEndpoint); ProxyResponse tokenResultResponse = HandlerUtil.execute(tokenEndpoint);
if (tokenResultResponse.getExecutorResponse().contains(HandlerConstants.EXECUTOR_EXCEPTION_PREFIX)) { if (tokenResultResponse.getExecutorResponse().contains(HandlerConstants.EXECUTOR_EXCEPTION_PREFIX)) {
log.error("Error occurred while refreshing access token."); log.error("Error occurred while refreshing access token.");
HandlerUtil.handleError(req, resp, serverUrl, platform, tokenResultResponse); HandlerUtil.handleError(resp, tokenResultResponse);
return false; return false;
} }
@ -378,24 +385,23 @@ public class InvokerHandler extends HttpServlet {
} }
log.error("Error Occurred in token renewal process."); log.error("Error Occurred in token renewal process.");
handleError(req, resp, HttpStatus.SC_INTERNAL_SERVER_ERROR); handleError(resp, HttpStatus.SC_INTERNAL_SERVER_ERROR);
return false; return false;
} }
/** /**
* Handle error requests * Handle error requests
* *
* @param req {@link HttpServletRequest}
* @param resp {@link HttpServletResponse} * @param resp {@link HttpServletResponse}
* @param errorCode HTTP error status code * @param errorCode HTTP error status code
* @throws IOException If error occurred when trying to send the error response. * @throws IOException If error occurred when trying to send the error response.
*/ */
private static void handleError(HttpServletRequest req, HttpServletResponse resp, int errorCode) private static void handleError(HttpServletResponse resp, int errorCode)
throws IOException { throws IOException {
ProxyResponse proxyResponse = new ProxyResponse(); ProxyResponse proxyResponse = new ProxyResponse();
proxyResponse.setCode(errorCode); proxyResponse.setCode(errorCode);
proxyResponse.setExecutorResponse( proxyResponse.setExecutorResponse(
HandlerConstants.EXECUTOR_EXCEPTION_PREFIX + HandlerUtil.getStatusKey(errorCode)); HandlerConstants.EXECUTOR_EXCEPTION_PREFIX + HandlerUtil.getStatusKey(errorCode));
HandlerUtil.handleError(req, resp, serverUrl, platform, proxyResponse); HandlerUtil.handleError(resp, proxyResponse);
} }
} }

@ -56,14 +56,13 @@ public class LoginHandler extends HttpServlet {
private static String username; private static String username;
private static String password; private static String password;
private static String platform; private static String gatewayUrl;
private static String serverUrl;
private static String uiConfigUrl; private static String uiConfigUrl;
@Override @Override
protected void doPost(HttpServletRequest req, HttpServletResponse resp) { protected void doPost(HttpServletRequest req, HttpServletResponse resp) {
try { try {
validateLoginRequest(req, resp); validateLoginRequest(req);
HttpSession httpSession = req.getSession(false); HttpSession httpSession = req.getSession(false);
if (httpSession != null) { if (httpSession != null) {
httpSession.invalidate(); httpSession.invalidate();
@ -79,14 +78,14 @@ public class LoginHandler extends HttpServlet {
if (!StringUtils.isEmpty(executorResponse) && executorResponse if (!StringUtils.isEmpty(executorResponse) && executorResponse
.contains(HandlerConstants.EXECUTOR_EXCEPTION_PREFIX)) { .contains(HandlerConstants.EXECUTOR_EXCEPTION_PREFIX)) {
log.error("Error occurred while getting UI configurations by invoking " + uiConfigUrl); log.error("Error occurred while getting UI configurations by invoking " + uiConfigUrl);
HandlerUtil.handleError(req, resp, serverUrl, platform, uiConfigResponse); HandlerUtil.handleError(resp, uiConfigResponse);
return; return;
} }
String uiConfig = uiConfigResponse.getData(); String uiConfig = uiConfigResponse.getData();
if (uiConfig == null){ if (uiConfig == null){
log.error("UI config retrieval is failed, and didn't find UI configuration for App manager."); log.error("UI config retrieval is failed, and didn't find UI configuration for App manager.");
HandlerUtil.handleError(req, resp, serverUrl, platform, null); HandlerUtil.handleError(resp, null);
return; return;
} }
JsonElement uiConfigJsonElement = jsonParser.parse(uiConfigResponse.getData()); JsonElement uiConfigJsonElement = jsonParser.parse(uiConfigResponse.getData());
@ -94,12 +93,12 @@ public class LoginHandler extends HttpServlet {
if (uiConfigJsonElement.isJsonObject()) { if (uiConfigJsonElement.isJsonObject()) {
uiConfigJsonObject = uiConfigJsonElement.getAsJsonObject(); uiConfigJsonObject = uiConfigJsonElement.getAsJsonObject();
httpSession.setAttribute(HandlerConstants.UI_CONFIG_KEY, uiConfigJsonObject); httpSession.setAttribute(HandlerConstants.UI_CONFIG_KEY, uiConfigJsonObject);
httpSession.setAttribute(HandlerConstants.PLATFORM, serverUrl); httpSession.setAttribute(HandlerConstants.PLATFORM, gatewayUrl);
} }
if (uiConfigJsonObject == null) { if (uiConfigJsonObject == null) {
log.error( log.error(
"Either UI config json element is not an json object or converting rom json element to json object is failed."); "Either UI config json element is not an json object or converting rom json element to json object is failed.");
HandlerUtil.handleError(req, resp, serverUrl, platform, null); HandlerUtil.handleError(resp, null);
return; return;
} }
@ -111,7 +110,7 @@ public class LoginHandler extends HttpServlet {
log.debug("SSO is enabled"); log.debug("SSO is enabled");
} else { } else {
// default login // default login
HttpPost apiRegEndpoint = new HttpPost(serverUrl + HandlerConstants.APP_REG_ENDPOINT); HttpPost apiRegEndpoint = new HttpPost(gatewayUrl + HandlerConstants.APP_REG_ENDPOINT);
apiRegEndpoint.setHeader(HttpHeaders.AUTHORIZATION, HandlerConstants.BASIC + Base64.getEncoder() apiRegEndpoint.setHeader(HttpHeaders.AUTHORIZATION, HandlerConstants.BASIC + Base64.getEncoder()
.encodeToString((username + HandlerConstants.COLON + password).getBytes())); .encodeToString((username + HandlerConstants.COLON + password).getBytes()));
apiRegEndpoint.setHeader(HTTP.CONTENT_TYPE, ContentType.APPLICATION_JSON.toString()); apiRegEndpoint.setHeader(HTTP.CONTENT_TYPE, ContentType.APPLICATION_JSON.toString());
@ -120,18 +119,17 @@ public class LoginHandler extends HttpServlet {
ProxyResponse clientAppResponse = HandlerUtil.execute(apiRegEndpoint); ProxyResponse clientAppResponse = HandlerUtil.execute(apiRegEndpoint);
if (clientAppResponse.getCode() == HttpStatus.SC_UNAUTHORIZED){ if (clientAppResponse.getCode() == HttpStatus.SC_UNAUTHORIZED){
HandlerUtil.handleError(req, resp, serverUrl, platform, clientAppResponse); HandlerUtil.handleError(resp, clientAppResponse);
return; return;
} }
if (clientAppResponse.getCode() == HttpStatus.SC_CREATED && getTokenAndPersistInSession(req, resp, if (clientAppResponse.getCode() == HttpStatus.SC_CREATED && getTokenAndPersistInSession(req, resp,
clientAppResponse.getData(), scopes)) { clientAppResponse.getData(), scopes)) {
ProxyResponse proxyResponse = new ProxyResponse(); ProxyResponse proxyResponse = new ProxyResponse();
proxyResponse.setCode(HttpStatus.SC_OK); proxyResponse.setCode(HttpStatus.SC_OK);
proxyResponse.setUrl(serverUrl + HandlerConstants.PATH_SEPARATOR + platform); HandlerUtil.handleSuccess(resp, proxyResponse);
HandlerUtil.handleSuccess(req, resp, serverUrl, platform, proxyResponse);
return; return;
} }
HandlerUtil.handleError(req, resp, serverUrl, platform, null); HandlerUtil.handleError(resp, null);
} }
} catch (IOException e) { } catch (IOException e) {
log.error("Error occurred while sending the response into the socket. ", e); log.error("Error occurred while sending the response into the socket. ", e);
@ -165,13 +163,13 @@ public class LoginHandler extends HttpServlet {
if (tokenResultResponse.getExecutorResponse().contains(HandlerConstants.EXECUTOR_EXCEPTION_PREFIX)) { if (tokenResultResponse.getExecutorResponse().contains(HandlerConstants.EXECUTOR_EXCEPTION_PREFIX)) {
log.error("Error occurred while invoking the API to get token data."); log.error("Error occurred while invoking the API to get token data.");
HandlerUtil.handleError(req, resp, serverUrl, platform, tokenResultResponse); HandlerUtil.handleError(resp, tokenResultResponse);
return false; return false;
} }
String tokenResult = tokenResultResponse.getData(); String tokenResult = tokenResultResponse.getData();
if (tokenResult == null){ if (tokenResult == null){
log.error("Invalid token response is received."); log.error("Invalid token response is received.");
HandlerUtil.handleError(req, resp, serverUrl, platform, tokenResultResponse); HandlerUtil.handleError(resp, tokenResultResponse);
return false; return false;
} }
@ -222,28 +220,21 @@ public class LoginHandler extends HttpServlet {
* @param req - {@link HttpServletRequest} * @param req - {@link HttpServletRequest}
* Define username and password static parameters. * Define username and password static parameters.
*/ */
private static void validateLoginRequest(HttpServletRequest req, HttpServletResponse resp) throws LoginException { private static void validateLoginRequest(HttpServletRequest req) throws LoginException {
String gatewayCarbonPort = System.getProperty("iot.gateway.carbon.https.port");
if (HandlerConstants.HTTP_PROTOCOL.equals(req.getScheme())){
gatewayCarbonPort = System.getProperty("iot.gateway.carbon.http.port");
}
username = req.getParameter("username"); username = req.getParameter("username");
password = req.getParameter("password"); password = req.getParameter("password");
platform = req.getParameter(HandlerConstants.PLATFORM); gatewayUrl = req.getScheme() + HandlerConstants.SCHEME_SEPARATOR + System.getProperty("iot.gateway.host")
serverUrl = req.getScheme() + HandlerConstants.SCHEME_SEPARATOR + req.getServerName() + HandlerConstants.COLON + HandlerConstants.COLON + HandlerUtil.getGatewayPort(req.getScheme());
+ System.getProperty("iot.gateway.https.port");
uiConfigUrl = req.getScheme() + HandlerConstants.SCHEME_SEPARATOR + req.getServerName() + HandlerConstants.COLON uiConfigUrl = req.getScheme() + HandlerConstants.SCHEME_SEPARATOR + req.getServerName() + HandlerConstants.COLON
+ System.getProperty("iot.gateway.carbon.https.port") + HandlerConstants.UI_CONFIG_ENDPOINT; + gatewayCarbonPort + HandlerConstants.UI_CONFIG_ENDPOINT;
try {
if (platform == null) {
resp.sendRedirect(serverUrl + HandlerConstants.DEFAULT_ERROR_CALLBACK);
throw new LoginException("Invalid login request. Platform parameter is Null.");
}
if (username == null || password == null) { if (username == null || password == null) {
resp.sendRedirect(serverUrl + HandlerConstants.PATH_SEPARATOR + platform String msg = "Invalid login request. Username or Password is not received for login request.";
+ HandlerConstants.DEFAULT_ERROR_CALLBACK); log.error(msg);
throw new LoginException( throw new LoginException(msg);
" Invalid login request. Username or Password is not received for login request.");
}
} catch (IOException e) {
throw new LoginException("Error occurred while redirecting to default error page.", e);
} }
} }
@ -271,8 +262,7 @@ public class LoginHandler extends HttpServlet {
* @throws IOException IO exception throws if an error occurred when invoking token endpoint * @throws IOException IO exception throws if an error occurred when invoking token endpoint
*/ */
private ProxyResponse getTokenResult(String encodedClientApp, JsonArray scopes) throws IOException { private ProxyResponse getTokenResult(String encodedClientApp, JsonArray scopes) throws IOException {
HttpPost tokenEndpoint = new HttpPost(gatewayUrl + HandlerConstants.TOKEN_ENDPOINT);
HttpPost tokenEndpoint = new HttpPost(serverUrl + HandlerConstants.TOKEN_ENDPOINT);
tokenEndpoint.setHeader(HttpHeaders.AUTHORIZATION, HandlerConstants.BASIC + encodedClientApp); tokenEndpoint.setHeader(HttpHeaders.AUTHORIZATION, HandlerConstants.BASIC + encodedClientApp);
tokenEndpoint.setHeader(HttpHeaders.CONTENT_TYPE, ContentType.APPLICATION_FORM_URLENCODED.toString()); tokenEndpoint.setHeader(HttpHeaders.CONTENT_TYPE, ContentType.APPLICATION_FORM_URLENCODED.toString());
String scopeString = getScopeString(scopes); String scopeString = getScopeString(scopes);

@ -38,9 +38,6 @@ public class LogoutHandler extends HttpServlet {
@Override @Override
protected void doPost(HttpServletRequest req, HttpServletResponse resp) { protected void doPost(HttpServletRequest req, HttpServletResponse resp) {
String serverUrl = req.getScheme() + HandlerConstants.SCHEME_SEPARATOR + req.getServerName()
+ HandlerConstants.COLON + req.getServerPort();
String platform = req.getParameter(HandlerConstants.PLATFORM);
HttpSession httpSession = req.getSession(false); HttpSession httpSession = req.getSession(false);
if (httpSession != null) { if (httpSession != null) {
httpSession.invalidate(); httpSession.invalidate();
@ -50,9 +47,8 @@ public class LogoutHandler extends HttpServlet {
ProxyResponse proxyResponse = new ProxyResponse(); ProxyResponse proxyResponse = new ProxyResponse();
proxyResponse.setCode(HttpStatus.SC_OK); proxyResponse.setCode(HttpStatus.SC_OK);
proxyResponse.setUrl(serverUrl + HandlerConstants.PATH_SEPARATOR + platform + HandlerConstants.LOGIN_PAGE);
try { try {
HandlerUtil.handleSuccess(req, resp, serverUrl, platform, proxyResponse); HandlerUtil.handleSuccess(resp, proxyResponse);
} catch (IOException e) { } catch (IOException e) {
log.error("Error occurred when processing logout request.", e); log.error("Error occurred when processing logout request.", e);
} }

@ -25,7 +25,6 @@ import com.google.gson.JsonSyntaxException;
import io.entgra.ui.request.interceptor.beans.AuthData; import io.entgra.ui.request.interceptor.beans.AuthData;
import io.entgra.ui.request.interceptor.util.HandlerConstants; import io.entgra.ui.request.interceptor.util.HandlerConstants;
import io.entgra.ui.request.interceptor.util.HandlerUtil; import io.entgra.ui.request.interceptor.util.HandlerUtil;
import org.apache.commons.lang.StringUtils;
import org.apache.commons.logging.Log; import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory; import org.apache.commons.logging.LogFactory;
import org.apache.http.HttpHeaders; import org.apache.http.HttpHeaders;
@ -52,24 +51,18 @@ public class UserHandler extends HttpServlet {
@Override @Override
protected void doPost(HttpServletRequest req, HttpServletResponse resp) { protected void doPost(HttpServletRequest req, HttpServletResponse resp) {
try { try {
String platform = req.getParameter(HandlerConstants.PLATFORM);
String serverUrl = String serverUrl =
req.getScheme() + HandlerConstants.SCHEME_SEPARATOR + req.getServerName() + HandlerConstants.COLON req.getScheme() + HandlerConstants.SCHEME_SEPARATOR + System.getProperty("iot.gateway.host")
+ System.getProperty("iot.gateway.https.port"); + HandlerConstants.COLON + HandlerUtil.getGatewayPort(req.getScheme());
if (StringUtils.isBlank(platform)) {
sendUnAuthorizeResponse(req, resp, serverUrl, platform);
return;
}
HttpSession httpSession = req.getSession(false); HttpSession httpSession = req.getSession(false);
if (httpSession == null) { if (httpSession == null) {
sendUnAuthorizeResponse(req, resp, serverUrl, platform); sendUnAuthorizeResponse(resp);
return; return;
} }
AuthData authData = (AuthData) httpSession.getAttribute(HandlerConstants.SESSION_AUTH_DATA_KEY); AuthData authData = (AuthData) httpSession.getAttribute(HandlerConstants.SESSION_AUTH_DATA_KEY);
if (authData == null) { if (authData == null) {
sendUnAuthorizeResponse(req, resp, serverUrl, platform); sendUnAuthorizeResponse(resp);
return; return;
} }
@ -84,13 +77,13 @@ public class UserHandler extends HttpServlet {
if (tokenStatus.getExecutorResponse().contains(HandlerConstants.EXECUTOR_EXCEPTION_PREFIX)) { if (tokenStatus.getExecutorResponse().contains(HandlerConstants.EXECUTOR_EXCEPTION_PREFIX)) {
log.error("Error occurred while invoking the API to get token status."); log.error("Error occurred while invoking the API to get token status.");
HandlerUtil.handleError(req, resp, serverUrl, platform, tokenStatus); HandlerUtil.handleError(resp, tokenStatus);
return; return;
} }
String tokenData = tokenStatus.getData(); String tokenData = tokenStatus.getData();
if (tokenData == null) { if (tokenData == null) {
log.error("Invalid token data is received."); log.error("Invalid token data is received.");
HandlerUtil.handleError(req, resp, serverUrl, platform, tokenStatus); HandlerUtil.handleError(resp, tokenStatus);
return; return;
} }
JsonParser jsonParser = new JsonParser(); JsonParser jsonParser = new JsonParser();
@ -98,14 +91,14 @@ public class UserHandler extends HttpServlet {
if (jTokenResult.isJsonObject()) { if (jTokenResult.isJsonObject()) {
JsonObject jTokenResultAsJsonObject = jTokenResult.getAsJsonObject(); JsonObject jTokenResultAsJsonObject = jTokenResult.getAsJsonObject();
if (!jTokenResultAsJsonObject.get("active").getAsBoolean()) { if (!jTokenResultAsJsonObject.get("active").getAsBoolean()) {
sendUnAuthorizeResponse(req, resp, serverUrl, platform); sendUnAuthorizeResponse(resp);
return; return;
} }
ProxyResponse proxyResponse = new ProxyResponse(); ProxyResponse proxyResponse = new ProxyResponse();
proxyResponse.setCode(HttpStatus.SC_OK); proxyResponse.setCode(HttpStatus.SC_OK);
proxyResponse.setData( proxyResponse.setData(
jTokenResultAsJsonObject.get("username").getAsString().replaceAll("@carbon.super", "")); jTokenResultAsJsonObject.get("username").getAsString().replaceAll("@carbon.super", ""));
HandlerUtil.handleSuccess(req, resp, serverUrl, platform, proxyResponse); HandlerUtil.handleSuccess(resp, proxyResponse);
} }
} catch (IOException e) { } catch (IOException e) {
log.error("Error occurred while sending the response into the socket. ", e); log.error("Error occurred while sending the response into the socket. ", e);
@ -117,17 +110,14 @@ public class UserHandler extends HttpServlet {
/** /**
* Send UnAuthorized Response to the user * Send UnAuthorized Response to the user
* *
* @param req HttpServletRequest object
* @param resp HttpServletResponse object * @param resp HttpServletResponse object
* @param serverUrl Url of the server
* @param platform Requested platform
*/ */
private void sendUnAuthorizeResponse(HttpServletRequest req, HttpServletResponse resp, String serverUrl, String platform) private void sendUnAuthorizeResponse(HttpServletResponse resp)
throws IOException { throws IOException {
ProxyResponse proxyResponse = new ProxyResponse(); ProxyResponse proxyResponse = new ProxyResponse();
proxyResponse.setCode(HttpStatus.SC_UNAUTHORIZED); proxyResponse.setCode(HttpStatus.SC_UNAUTHORIZED);
proxyResponse.setExecutorResponse( proxyResponse.setExecutorResponse(
HandlerConstants.EXECUTOR_EXCEPTION_PREFIX + HandlerUtil.getStatusKey(HttpStatus.SC_UNAUTHORIZED)); HandlerConstants.EXECUTOR_EXCEPTION_PREFIX + HandlerUtil.getStatusKey(HttpStatus.SC_UNAUTHORIZED));
HandlerUtil.handleError(req, resp, serverUrl, platform, proxyResponse); HandlerUtil.handleError(resp, proxyResponse);
} }
} }

@ -34,15 +34,15 @@ public class HandlerConstants {
public static final String PLATFORM = "platform"; public static final String PLATFORM = "platform";
public static final String USERNAME = "username"; public static final String USERNAME = "username";
public static final String PASSWORD = "password"; public static final String PASSWORD = "password";
public static final String DEFAULT_ERROR_CALLBACK = "/pages/error/default";
public static final String ERROR_CALLBACK_KEY = "errorCallback";
public static final String API_COMMON_CONTEXT = "/api"; public static final String API_COMMON_CONTEXT = "/api";
public static final String EXECUTOR_EXCEPTION_PREFIX = "ExecutorException-"; public static final String EXECUTOR_EXCEPTION_PREFIX = "ExecutorException-";
public static final String TOKEN_IS_EXPIRED = "ACCESS_TOKEN_IS_EXPIRED"; public static final String TOKEN_IS_EXPIRED = "ACCESS_TOKEN_IS_EXPIRED";
public static final String SCHEME_SEPARATOR = "://"; public static final String SCHEME_SEPARATOR = "://";
public static final String COLON = ":"; public static final String COLON = ":";
public static final String PATH_SEPARATOR = "/"; public static final String HTTP_PROTOCOL = "http";
public static final String[] SKIPPING_API_CONTEXT = {"artifact", "conf"};
public static final int INTERNAL_ERROR_CODE = 500; public static final int INTERNAL_ERROR_CODE = 500;
public static final long TIMEOUT = 1200; public static final long TIMEOUT = 1200;

@ -58,6 +58,8 @@ public class HandlerUtil {
ProxyResponse proxyResponse = new ProxyResponse(); ProxyResponse proxyResponse = new ProxyResponse();
if (response == null) { if (response == null) {
log.error("Received null response for http request : " + httpRequest.getMethod() + " " + httpRequest
.getURI().toString());
proxyResponse.setCode(HandlerConstants.INTERNAL_ERROR_CODE); proxyResponse.setCode(HandlerConstants.INTERNAL_ERROR_CODE);
proxyResponse.setExecutorResponse(HandlerConstants.EXECUTOR_EXCEPTION_PREFIX + getStatusKey( proxyResponse.setExecutorResponse(HandlerConstants.EXECUTOR_EXCEPTION_PREFIX + getStatusKey(
HandlerConstants.INTERNAL_ERROR_CODE)); HandlerConstants.INTERNAL_ERROR_CODE));
@ -84,6 +86,9 @@ public class HandlerUtil {
proxyResponse.setExecutorResponse(HandlerConstants.TOKEN_IS_EXPIRED); proxyResponse.setExecutorResponse(HandlerConstants.TOKEN_IS_EXPIRED);
return proxyResponse; return proxyResponse;
} else { } else {
log.error(
"Received " + statusCode + " response for http request : " + httpRequest.getMethod()
+ " " + httpRequest.getURI().toString() + ". Error message: " + jsonString);
proxyResponse.setCode(statusCode); proxyResponse.setCode(statusCode);
proxyResponse.setData(jsonString); proxyResponse.setData(jsonString);
proxyResponse.setExecutorResponse( proxyResponse.setExecutorResponse(
@ -91,6 +96,9 @@ public class HandlerUtil {
return proxyResponse; return proxyResponse;
} }
} }
log.error("Received " + statusCode +
" response for http request : " + httpRequest.getMethod() + " " + httpRequest.getURI()
.toString() + ". Error message: " + jsonString);
proxyResponse.setCode(statusCode); proxyResponse.setCode(statusCode);
proxyResponse.setData(jsonString); proxyResponse.setData(jsonString);
proxyResponse proxyResponse
@ -147,10 +155,7 @@ public class HandlerUtil {
* @param resp {@link HttpServletResponse} * @param resp {@link HttpServletResponse}
* Return Error Response. * Return Error Response.
*/ */
public static void handleError(HttpServletRequest req, HttpServletResponse resp, String serverUrl, public static void handleError(HttpServletResponse resp, ProxyResponse proxyResponse) throws IOException {
String platform, ProxyResponse proxyResponse) throws IOException {
HttpSession httpSession = req.getSession(true);
Gson gson = new Gson(); Gson gson = new Gson();
if (proxyResponse == null){ if (proxyResponse == null){
proxyResponse = new ProxyResponse(); proxyResponse = new ProxyResponse();
@ -158,27 +163,10 @@ public class HandlerUtil {
proxyResponse.setExecutorResponse(HandlerConstants.EXECUTOR_EXCEPTION_PREFIX + HandlerUtil proxyResponse.setExecutorResponse(HandlerConstants.EXECUTOR_EXCEPTION_PREFIX + HandlerUtil
.getStatusKey(HandlerConstants.INTERNAL_ERROR_CODE)); .getStatusKey(HandlerConstants.INTERNAL_ERROR_CODE));
} }
if (platform == null){
platform = "default";
}
resp.setStatus(proxyResponse.getCode()); resp.setStatus(proxyResponse.getCode());
resp.setContentType(ContentType.APPLICATION_JSON.getMimeType()); resp.setContentType(ContentType.APPLICATION_JSON.getMimeType());
resp.setCharacterEncoding(Consts.UTF_8.name()); resp.setCharacterEncoding(Consts.UTF_8.name());
if (httpSession != null) {
JsonObject uiConfig = (JsonObject) httpSession.getAttribute(HandlerConstants.UI_CONFIG_KEY);
if (uiConfig == null){
proxyResponse.setUrl(serverUrl + "/" + platform + HandlerConstants.DEFAULT_ERROR_CALLBACK);
} else{
proxyResponse.setUrl(serverUrl + uiConfig.get(HandlerConstants.ERROR_CALLBACK_KEY).getAsJsonObject()
.get(proxyResponse.getExecutorResponse().split(HandlerConstants.EXECUTOR_EXCEPTION_PREFIX)[1])
.getAsString());
}
} else {
proxyResponse.setUrl(serverUrl + "/" + platform + HandlerConstants.DEFAULT_ERROR_CALLBACK);
}
proxyResponse.setExecutorResponse(null); proxyResponse.setExecutorResponse(null);
try (PrintWriter writer = resp.getWriter()) { try (PrintWriter writer = resp.getWriter()) {
writer.write(gson.toJson(proxyResponse)); writer.write(gson.toJson(proxyResponse));
@ -190,24 +178,17 @@ public class HandlerUtil {
* @param resp {@link HttpServletResponse} * @param resp {@link HttpServletResponse}
* Return Success Response. * Return Success Response.
*/ */
public static void handleSuccess(HttpServletRequest req, HttpServletResponse resp, String serverUrl, public static void handleSuccess(HttpServletResponse resp, ProxyResponse proxyResponse) throws IOException {
String platform, ProxyResponse proxyResponse) throws IOException {
if (proxyResponse == null){ if (proxyResponse == null){
handleError(req, resp, serverUrl, platform, null); handleError(resp, null);
return; return;
} }
resp.setStatus(proxyResponse.getCode()); resp.setStatus(proxyResponse.getCode());
resp.setContentType(ContentType.APPLICATION_JSON.getMimeType()); resp.setContentType(ContentType.APPLICATION_JSON.getMimeType());
resp.setCharacterEncoding(Consts.UTF_8.name()); resp.setCharacterEncoding(Consts.UTF_8.name());
JSONObject response = new JSONObject(); JSONObject response = new JSONObject();
String redirectUrl = proxyResponse.getUrl();
String responseData = proxyResponse.getData(); String responseData = proxyResponse.getData();
if (!StringUtils.isEmpty(redirectUrl)){
response.put("url", redirectUrl);
}
if (!StringUtils.isEmpty(responseData)){ if (!StringUtils.isEmpty(responseData)){
try { try {
JSONObject responseDataJsonObj = new JSONObject(responseData); JSONObject responseDataJsonObj = new JSONObject(responseData);
@ -223,4 +204,17 @@ public class HandlerUtil {
} }
} }
/**
* Get gatway port according to request recieved scheme
* @param scheme https or https
* @return {@link String} gateway port
*/
public static String getGatewayPort(String scheme) {
String gatewayPort = System.getProperty("iot.gateway.https.port");
if (HandlerConstants.HTTP_PROTOCOL.equals(scheme)) {
gatewayPort = System.getProperty("iot.gateway.http.port");
}
return gatewayPort;
}
} }

Loading…
Cancel
Save