Refactor ui request interceptor

Related to: entgra/product-iots#103
feature/appm-store/pbac
Madawa Soysa 5 years ago
parent aaf4e5dcf2
commit f15fdae8a5

@ -58,8 +58,6 @@ import java.io.IOException;
import java.util.Enumeration; import java.util.Enumeration;
import java.util.List; import java.util.List;
import static io.entgra.ui.request.interceptor.util.HandlerUtil.execute;
@MultipartConfig @MultipartConfig
@WebServlet( @WebServlet(
name = "RequestHandlerServlet", name = "RequestHandlerServlet",
@ -84,7 +82,7 @@ public class InvokerHandler extends HttpServlet {
HttpPost postRequest = new HttpPost(generateBackendRequestURL(req)); HttpPost postRequest = new HttpPost(generateBackendRequestURL(req));
generateRequestEntity(req, postRequest); generateRequestEntity(req, postRequest);
postRequest.setHeader(HttpHeaders.AUTHORIZATION, HandlerConstants.BEARER + authData.getAccessToken()); postRequest.setHeader(HttpHeaders.AUTHORIZATION, HandlerConstants.BEARER + authData.getAccessToken());
ProxyResponse proxyResponse = execute(postRequest); ProxyResponse proxyResponse = HandlerUtil.execute(postRequest);
if (HandlerConstants.TOKEN_IS_EXPIRED.equals(proxyResponse.getExecutorResponse())) { if (HandlerConstants.TOKEN_IS_EXPIRED.equals(proxyResponse.getExecutorResponse())) {
proxyResponse = retryRequestWithRefreshedToken(req, resp, postRequest); proxyResponse = retryRequestWithRefreshedToken(req, resp, postRequest);
@ -113,7 +111,7 @@ public class InvokerHandler extends HttpServlet {
HttpGet getRequest = new HttpGet(generateBackendRequestURL(req)); HttpGet getRequest = new HttpGet(generateBackendRequestURL(req));
copyRequestHeaders(req, getRequest, false); copyRequestHeaders(req, getRequest, false);
getRequest.setHeader(HttpHeaders.AUTHORIZATION, HandlerConstants.BEARER + authData.getAccessToken()); getRequest.setHeader(HttpHeaders.AUTHORIZATION, HandlerConstants.BEARER + authData.getAccessToken());
ProxyResponse proxyResponse = execute(getRequest); ProxyResponse proxyResponse = HandlerUtil.execute(getRequest);
if (HandlerConstants.TOKEN_IS_EXPIRED.equals(proxyResponse.getExecutorResponse())) { if (HandlerConstants.TOKEN_IS_EXPIRED.equals(proxyResponse.getExecutorResponse())) {
proxyResponse = retryRequestWithRefreshedToken(req, resp, getRequest); proxyResponse = retryRequestWithRefreshedToken(req, resp, getRequest);
if (proxyResponse == null) { if (proxyResponse == null) {
@ -139,7 +137,7 @@ public class InvokerHandler extends HttpServlet {
HttpPut putRequest = new HttpPut(generateBackendRequestURL(req)); HttpPut putRequest = new HttpPut(generateBackendRequestURL(req));
generateRequestEntity(req, putRequest); generateRequestEntity(req, putRequest);
putRequest.setHeader(HttpHeaders.AUTHORIZATION, HandlerConstants.BEARER + authData.getAccessToken()); putRequest.setHeader(HttpHeaders.AUTHORIZATION, HandlerConstants.BEARER + authData.getAccessToken());
ProxyResponse proxyResponse = execute(putRequest); ProxyResponse proxyResponse = HandlerUtil.execute(putRequest);
if (HandlerConstants.TOKEN_IS_EXPIRED.equals(proxyResponse.getExecutorResponse())) { if (HandlerConstants.TOKEN_IS_EXPIRED.equals(proxyResponse.getExecutorResponse())) {
proxyResponse = retryRequestWithRefreshedToken(req, resp, putRequest); proxyResponse = retryRequestWithRefreshedToken(req, resp, putRequest);
@ -168,7 +166,7 @@ public class InvokerHandler extends HttpServlet {
HttpDelete deleteRequest = new HttpDelete(generateBackendRequestURL(req)); HttpDelete deleteRequest = new HttpDelete(generateBackendRequestURL(req));
copyRequestHeaders(req, deleteRequest, false); copyRequestHeaders(req, deleteRequest, false);
deleteRequest.setHeader(HttpHeaders.AUTHORIZATION, HandlerConstants.BEARER + authData.getAccessToken()); deleteRequest.setHeader(HttpHeaders.AUTHORIZATION, HandlerConstants.BEARER + authData.getAccessToken());
ProxyResponse proxyResponse = execute(deleteRequest); ProxyResponse proxyResponse = HandlerUtil.execute(deleteRequest);
if (HandlerConstants.TOKEN_IS_EXPIRED.equals(proxyResponse.getExecutorResponse())) { if (HandlerConstants.TOKEN_IS_EXPIRED.equals(proxyResponse.getExecutorResponse())) {
proxyResponse = retryRequestWithRefreshedToken(req, resp, deleteRequest); proxyResponse = retryRequestWithRefreshedToken(req, resp, deleteRequest);
if (proxyResponse == null) { if (proxyResponse == null) {
@ -202,7 +200,7 @@ public class InvokerHandler extends HttpServlet {
List<FileItem> fileItemList = servletFileUpload.parseRequest(req); List<FileItem> fileItemList = servletFileUpload.parseRequest(req);
MultipartEntityBuilder entityBuilder = MultipartEntityBuilder.create(); MultipartEntityBuilder entityBuilder = MultipartEntityBuilder.create();
entityBuilder.setMode(HttpMultipartMode.BROWSER_COMPATIBLE); entityBuilder.setMode(HttpMultipartMode.BROWSER_COMPATIBLE);
for (FileItem item : fileItemList) { for (FileItem item: fileItemList) {
if (!item.isFormField()) { if (!item.isFormField()) {
entityBuilder.addPart(item.getFieldName(), new InputStreamBody(item.getInputStream(), entityBuilder.addPart(item.getFieldName(), new InputStreamBody(item.getInputStream(),
ContentType.create(item.getContentType()), item.getName())); ContentType.create(item.getContentType()), item.getName()));
@ -321,7 +319,7 @@ public class InvokerHandler extends HttpServlet {
HttpRequestBase httpRequest) throws IOException { HttpRequestBase httpRequest) throws IOException {
if (refreshToken(req, resp)) { if (refreshToken(req, resp)) {
httpRequest.setHeader(HttpHeaders.AUTHORIZATION, HandlerConstants.BEARER + authData.getAccessToken()); httpRequest.setHeader(HttpHeaders.AUTHORIZATION, HandlerConstants.BEARER + authData.getAccessToken());
ProxyResponse proxyResponse = 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(req, resp, serverUrl, platform, proxyResponse);
@ -363,7 +361,7 @@ public class InvokerHandler extends HttpServlet {
encodedClientApp); encodedClientApp);
tokenEndpoint.setHeader(HttpHeaders.CONTENT_TYPE, ContentType.APPLICATION_FORM_URLENCODED.toString()); tokenEndpoint.setHeader(HttpHeaders.CONTENT_TYPE, ContentType.APPLICATION_FORM_URLENCODED.toString());
ProxyResponse tokenResultResponse = 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(req, resp, serverUrl, platform, tokenResultResponse);

@ -50,8 +50,6 @@ import javax.servlet.http.HttpSession;
import java.io.IOException; import java.io.IOException;
import java.util.Base64; import java.util.Base64;
import static io.entgra.ui.request.interceptor.util.HandlerUtil.execute;
@MultipartConfig @MultipartConfig
@WebServlet("/login") @WebServlet("/login")
public class LoginHandler extends HttpServlet { public class LoginHandler extends HttpServlet {
@ -78,12 +76,12 @@ public class LoginHandler extends HttpServlet {
httpSession.invalidate(); httpSession.invalidate();
} }
httpSession = req.getSession(true); httpSession = req.getSession(true);
//setting session to expiry in 5 mins //setting session to expiry in 5 minutes
httpSession.setMaxInactiveInterval(Math.toIntExact(HandlerConstants.TIMEOUT)); httpSession.setMaxInactiveInterval(Math.toIntExact(HandlerConstants.TIMEOUT));
HttpGet uiConfigEndpoint = new HttpGet(uiConfigUrl); HttpGet uiConfigEndpoint = new HttpGet(uiConfigUrl);
JsonParser jsonParser = new JsonParser(); JsonParser jsonParser = new JsonParser();
ProxyResponse uiConfigResponse = execute(uiConfigEndpoint); ProxyResponse uiConfigResponse = HandlerUtil.execute(uiConfigEndpoint);
String executorResponse = uiConfigResponse.getExecutorResponse(); String executorResponse = uiConfigResponse.getExecutorResponse();
if (!StringUtils.isEmpty(executorResponse) && executorResponse if (!StringUtils.isEmpty(executorResponse) && executorResponse
.contains(HandlerConstants.EXECUTOR_EXCEPTION_PREFIX)) { .contains(HandlerConstants.EXECUTOR_EXCEPTION_PREFIX)) {
@ -126,7 +124,7 @@ public class LoginHandler extends HttpServlet {
apiRegEndpoint.setHeader(HTTP.CONTENT_TYPE, ContentType.APPLICATION_JSON.toString()); apiRegEndpoint.setHeader(HTTP.CONTENT_TYPE, ContentType.APPLICATION_JSON.toString());
apiRegEndpoint.setEntity(constructAppRegPayload(tags)); apiRegEndpoint.setEntity(constructAppRegPayload(tags));
ProxyResponse clientAppResponse = execute(apiRegEndpoint); ProxyResponse clientAppResponse = HandlerUtil.execute(apiRegEndpoint);
String clientAppResult = clientAppResponse.getData(); String clientAppResult = clientAppResponse.getData();
if (!StringUtils.isEmpty(clientAppResult) && getTokenAndPersistInSession(req, resp, if (!StringUtils.isEmpty(clientAppResult) && getTokenAndPersistInSession(req, resp,
@ -141,11 +139,11 @@ public class LoginHandler extends HttpServlet {
HandlerUtil.handleError(req, resp, serverUrl, platform, null); HandlerUtil.handleError(req, resp, serverUrl, platform, null);
} }
} catch (IOException e) { } catch (IOException e) {
log.error("Error occured while sending the response into the socket. ", e); log.error("Error occurred while sending the response into the socket. ", e);
} catch (JsonSyntaxException e) { } catch (JsonSyntaxException e) {
log.error("Error occured while parsing the response. ", e); log.error("Error occurred while parsing the response. ", e);
} catch (LoginException e) { } catch (LoginException e) {
log.error("Error occured while getting token data. ", e); log.error("Error occurred while getting token data. ", e);
} }
} }
@ -203,7 +201,7 @@ public class LoginHandler extends HttpServlet {
} }
return false; return false;
} catch (IOException e) { } catch (IOException e) {
throw new LoginException("Error occured while sending the response into the socket", e); throw new LoginException("Error occurred while sending the response into the socket", e);
} }
} }
@ -216,8 +214,8 @@ public class LoginHandler extends HttpServlet {
if (scopes != null && scopes.size() > 0) { if (scopes != null && scopes.size() > 0) {
StringBuilder builder = new StringBuilder(); StringBuilder builder = new StringBuilder();
for (JsonElement scope : scopes) { for (JsonElement scope : scopes) {
String tmpscope = scope.getAsString() + " "; String tmpScope = scope.getAsString() + " ";
builder.append(tmpscope); builder.append(tmpScope);
} }
return builder.toString(); return builder.toString();
} else { } else {
@ -248,7 +246,7 @@ public class LoginHandler extends HttpServlet {
" Invalid login request. Username or Password is not received for login request."); " Invalid login request. Username or Password is not received for login request.");
} }
} catch (IOException e) { } catch (IOException e) {
throw new LoginException("Error Occured while redirecting to default error page.", e); throw new LoginException("Error occurred while redirecting to default error page.", e);
} }
} }
@ -271,13 +269,13 @@ public class LoginHandler extends HttpServlet {
* @param encodedClientApp - Base64 encoded clientId:clientSecret. * @param encodedClientApp - Base64 encoded clientId:clientSecret.
* @param scopes - Scopes which are retrieved by reading application-mgt configuration * @param scopes - Scopes which are retrieved by reading application-mgt configuration
* @return Invoke token endpoint and return the response as string. * @return Invoke token endpoint and return the response as string.
* @throws IOException IO exception throws if an error occured 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(serverUrl + HandlerConstants.TOKEN_ENDPOINT); HttpPost tokenEndpoint = new HttpPost(serverUrl + HandlerConstants.TOKEN_ENDPOINT);
tokenEndpoint.setHeader("Authorization", "Basic " + encodedClientApp); tokenEndpoint.setHeader(HttpHeaders.AUTHORIZATION, HandlerConstants.BASIC + encodedClientApp);
tokenEndpoint.setHeader("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);
if (scopeString != null) { if (scopeString != null) {
@ -290,6 +288,6 @@ public class LoginHandler extends HttpServlet {
"grant_type=password&username=" + username + "&password=" + password + "&scope=" + scopeString, "grant_type=password&username=" + username + "&password=" + password + "&scope=" + scopeString,
ContentType.APPLICATION_FORM_URLENCODED); ContentType.APPLICATION_FORM_URLENCODED);
tokenEndpoint.setEntity(tokenEPPayload); tokenEndpoint.setEntity(tokenEPPayload);
return execute(tokenEndpoint); return HandlerUtil.execute(tokenEndpoint);
} }
} }

@ -23,9 +23,11 @@ import com.google.gson.JsonObject;
import org.apache.commons.lang.StringUtils; 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.Consts;
import org.apache.http.HttpResponse; import org.apache.http.HttpResponse;
import org.apache.http.HttpStatus; import org.apache.http.HttpStatus;
import org.apache.http.client.methods.HttpRequestBase; import org.apache.http.client.methods.HttpRequestBase;
import org.apache.http.entity.ContentType;
import org.apache.http.impl.client.CloseableHttpClient; import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients; import org.apache.http.impl.client.HttpClients;
import org.json.JSONException; import org.json.JSONException;
@ -79,7 +81,7 @@ public class HandlerUtil {
if (jsonString.contains("Access token expired") || jsonString if (jsonString.contains("Access token expired") || jsonString
.contains("Invalid input. Access token validation failed")) { .contains("Invalid input. Access token validation failed")) {
proxyResponse.setCode(statusCode); proxyResponse.setCode(statusCode);
proxyResponse.setExecutorResponse("ACCESS_TOKEN_IS_EXPIRED"); proxyResponse.setExecutorResponse(HandlerConstants.TOKEN_IS_EXPIRED);
return proxyResponse; return proxyResponse;
} else { } else {
proxyResponse.setCode(statusCode); proxyResponse.setCode(statusCode);
@ -161,8 +163,8 @@ public class HandlerUtil {
} }
resp.setStatus(proxyResponse.getCode()); resp.setStatus(proxyResponse.getCode());
resp.setContentType("application/json"); resp.setContentType(ContentType.APPLICATION_JSON.getMimeType());
resp.setCharacterEncoding("UTF-8"); resp.setCharacterEncoding(Consts.UTF_8.name());
if (httpSession != null) { if (httpSession != null) {
JsonObject uiConfig = (JsonObject) httpSession.getAttribute(HandlerConstants.UI_CONFIG_KEY); JsonObject uiConfig = (JsonObject) httpSession.getAttribute(HandlerConstants.UI_CONFIG_KEY);
@ -192,13 +194,13 @@ public class HandlerUtil {
public static void handleSuccess(HttpServletRequest req, HttpServletResponse resp, String serverUrl, public static void handleSuccess(HttpServletRequest req, HttpServletResponse resp, String serverUrl,
String platform, ProxyResponse proxyResponse) throws IOException { String platform, ProxyResponse proxyResponse) throws IOException {
if (proxyResponse == null){ if (proxyResponse == null){
handleError(req,resp,serverUrl,platform,proxyResponse); handleError(req, resp, serverUrl, platform, null);
return; return;
} }
resp.setStatus(proxyResponse.getCode()); resp.setStatus(proxyResponse.getCode());
resp.setContentType("application/json"); resp.setContentType(ContentType.APPLICATION_JSON.getMimeType());
resp.setCharacterEncoding("UTF-8"); resp.setCharacterEncoding(Consts.UTF_8.name());
JSONObject response = new JSONObject(); JSONObject response = new JSONObject();
String redirectUrl = proxyResponse.getUrl(); String redirectUrl = proxyResponse.getUrl();

Loading…
Cancel
Save