Adding changes to common modules to accomodate ui restructuring

revert-70aa11f8
Ace 9 years ago
parent 03f323d6e2
commit b8635db485

@ -1,5 +1,5 @@
/* /*
* Copyright (c) 2016, WSO2 Inc. (http://www.wso2.org) All Rights Reserved. * Copyright (c) 2015, WSO2 Inc. (http://www.wso2.org) All Rights Reserved.
* *
* WSO2 Inc. licenses this file to you under the Apache License, * WSO2 Inc. licenses this file to you under the Apache License,
* Version 2.0 (the "License"); you may not use this file except * Version 2.0 (the "License"); you may not use this file except
@ -10,34 +10,38 @@
* *
* Unless required by applicable law or agreed to in writing, * Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an * software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND,
* KIND, either express or implied. See the License for the * either express or implied. See the License for the
* specific language governing permissions and limitations * specific language governing permissions and limitations
* under the License. * under the License.
*/ */
/** /**
* This backendServiceInvoker contains the wrappers for back end jaggary calls. * This backendServiceInvoker contains the wrappers for back end jaggery calls.
*/ */
var backendServiceInvoker = function () { var backendServiceInvoker = function () {
var log = new Log("/app/modules/backend-service-invoker.js"); var log = new Log("/app/modules/backend-service-invoker.js");
var publicXMLHTTPInvokers = {}; var publicXMLHTTPInvokers = {};
var publicHTTPClientInvokers = {};
var privateMethods = {}; var privateMethods = {};
var publicWSInvokers = {}; var publicWSInvokers = {};
var publicHTTPClientInvokers = {};
var IS_OAUTH_ENABLED = true;
var TOKEN_EXPIRED = "Access token expired"; var TOKEN_EXPIRED = "Access token expired";
var TOKEN_INVALID = "Invalid input. Access token validation failed"; var TOKEN_INVALID = "Invalid input. Access token validation failed";
var devicemgtProps = require("/app/conf/devicemgt-props.js").config();
var constants = require("/app/modules/constants.js"); var constants = require("/app/modules/constants.js");
var tokenUtil = require("/app/modules/api-wrapper-util.js").apiWrapperUtil; var userModule = require("/app/modules/user.js")["userModule"];
var devicemgtProps = require('/app/conf/devicemgt-props.js').config(); var tokenUtil = require("/app/modules/api-wrapper-util.js")["apiWrapperUtil"];
/** /**
* This methoad reads the token pair from the session and return the access token. * This method reads the token pair from the session and return the access token.
* If the token pair s not set in the session this will send a redirect to the login page. * If the token pair s not set in the session this will send a redirect to the login page.
*/ */
privateMethods.getAccessToken = function () { privateMethods.getAccessToken = function () {
var tokenPair = session.get(constants.ACCESS_TOKEN_PAIR_IDENTIFIER); var tokenPair = session.get(constants["ACCESS_TOKEN_PAIR_IDENTIFIER"]);
if (tokenPair) { if (tokenPair) {
return tokenPair.accessToken; return tokenPair.accessToken;
} else { } else {
@ -46,152 +50,119 @@ var backendServiceInvoker = function () {
}; };
/** /**
* This method add Oauth authentication header to outgoing XMLHTTP Requests if Oauth authentication is enabled. * ---------------------------------------------------------------------------
* @param method HTTP request type. * Start of XML-HTTP-REQUEST based Interceptor implementations
* @param url target url. * ---------------------------------------------------------------------------
* @param payload payload/data which need to be send. */
* @param successCallback a function to be called if the respond if successful.
* @param errorCallback a function to be called if en error is reserved. /**
* This method add Oauth authentication header to outgoing XML-HTTP Requests if Oauth authentication is enabled.
* @param httpMethod HTTP request type.
* @param requestPayload payload/data if exists which is needed to be send.
* @param endpoint Backend REST API url.
* @param responseCallback a function to be called with response retrieved.
* @param count a counter which hold the number of recursive execution * @param count a counter which hold the number of recursive execution
*/ */
privateMethods.execute = function (method, url, successCallback, errorCallback, payload, count, contentType, acceptType) { privateMethods.execute = function (httpMethod, requestPayload, endpoint, responseCallback, count) {
var xmlHttpRequest = new XMLHttpRequest(); var xmlHttpRequest = new XMLHttpRequest();
xmlHttpRequest.open(method, url);
if(!contentType){ xmlHttpRequest.open(httpMethod, endpoint);
contentType = constants.APPLICATION_JSON; xmlHttpRequest.setRequestHeader(constants["CONTENT_TYPE_IDENTIFIER"], constants["APPLICATION_JSON"]);
} xmlHttpRequest.setRequestHeader(constants["ACCEPT_IDENTIFIER"], constants["APPLICATION_JSON"]);
if(!acceptType){
acceptType = constants.APPLICATION_JSON; if (devicemgtProps["isOAuthEnabled"]) {
}
xmlHttpRequest.setRequestHeader(constants.CONTENT_TYPE_IDENTIFIER, contentType);
xmlHttpRequest.setRequestHeader(constants.ACCEPT_IDENTIFIER, acceptType);
xmlHttpRequest.setRequestHeader(constants.REFERER, String(privateMethods.getClientDomain()));
if (IS_OAUTH_ENABLED) {
var accessToken = privateMethods.getAccessToken(); var accessToken = privateMethods.getAccessToken();
if (!accessToken) { if (!accessToken) {
response.sendRedirect(devicemgtProps["httpsURL"] + "/devicemgt/login"); userModule.logout(function () {
response.sendRedirect(devicemgtProps["appContext"] + "login");
});
} else { } else {
xmlHttpRequest.setRequestHeader(constants.AUTHORIZATION_HEADER, constants.BEARER_PREFIX + accessToken); xmlHttpRequest.
setRequestHeader(constants["AUTHORIZATION_HEADER"], constants["BEARER_PREFIX"] + accessToken);
} }
} }
if (payload) {
xmlHttpRequest.send(payload); if (requestPayload) {
xmlHttpRequest.send(requestPayload);
} else { } else {
xmlHttpRequest.send(); xmlHttpRequest.send();
} }
if ((xmlHttpRequest.status >= 200 && xmlHttpRequest.status < 300) || xmlHttpRequest.status == 302) { log.debug("Service Invoker-URL: " + endpoint);
if (xmlHttpRequest.responseText != null) { log.debug("Service Invoker-Method: " + httpMethod);
return successCallback(parse(xmlHttpRequest.responseText));
} else { log.info("Request : " + httpMethod + " " + endpoint);
return successCallback({"status": xmlHttpRequest.status, "messageFromServer": "Operation Completed"}); log.info("Request payload if any : " + stringify(requestPayload));
} log.info("Response status : " + xmlHttpRequest.status);
} else if (xmlHttpRequest.status == 401 && (xmlHttpRequest.responseText == TOKEN_EXPIRED || log.info("Response payload if any : " + xmlHttpRequest.responseText);
//log.info("Response headers : " + xmlHttpRequest.getAllResponseHeaders());
if (xmlHttpRequest.status == 401 && (xmlHttpRequest.responseText == TOKEN_EXPIRED ||
xmlHttpRequest.responseText == TOKEN_INVALID ) && count < 5) { xmlHttpRequest.responseText == TOKEN_INVALID ) && count < 5) {
tokenUtil.refreshToken(); tokenUtil.refreshToken();
return privateMethods.execute(method, url, successCallback, errorCallback, payload, (count + 1)); return privateMethods.execute(httpMethod, requestPayload, endpoint, responseCallback, ++count);
} else if (xmlHttpRequest.status == 500) {
return errorCallback(xmlHttpRequest);
} else { } else {
return errorCallback(xmlHttpRequest); return responseCallback(xmlHttpRequest);
} }
}; };
/** /**
* This method add Oauth authentication header to outgoing XMLHTTP Requests if Oauth authentication is enabled. * This method add Oauth authentication header to outgoing XML-HTTP Requests if Oauth authentication is enabled.
* @param method HTTP request type. * @param httpMethod HTTP request type.
* @param url target url. * @param requestPayload payload/data if exists which is needed to be send.
* @param payload payload/data which need to be send. * @param endpoint Backend REST API url.
* @param successCallback a function to be called if the respond if successful. * @param responseCallback a function to be called with response retrieved.
* @param errorCallback a function to be called if en error is reserved.
*/ */
privateMethods.initiateXMLHTTPRequest = function (method, url, successCallback, errorCallback, payload, contentType, acceptType) { privateMethods.initiateXMLHTTPRequest = function (httpMethod, requestPayload, endpoint, responseCallback) {
if (privateMethods.getAccessToken()) { return privateMethods.execute(httpMethod, requestPayload, endpoint, responseCallback, 0);
return privateMethods.execute(method, url, successCallback, errorCallback, payload, 0, contentType, acceptType);
}
}; };
/** /**
* This method add Oauth authentication header to outgoing HTTPClient Requests if Oauth authentication is enabled. * This method invokes return initiateXMLHttpRequest for get calls
* @param method HTTP request type. * @param endpoint Backend REST API url.
* @param url target url. * @param responseCallback a function to be called with response retrieved.
* @param payload payload/data which need to be send.
* @param successCallback a function to be called if the respond if successful.
* @param errorCallback a function to be called if en error is reserved.
*/ */
privateMethods.initiateHTTPClientRequest = function (method, url, successCallback, errorCallback, payload, contentType, acceptType) { publicXMLHTTPInvokers.get = function (endpoint, responseCallback) {
var HttpClient = Packages.org.apache.commons.httpclient.HttpClient; var requestPayload = null;
var httpMethodObject; return privateMethods.initiateXMLHTTPRequest(constants["HTTP_GET"], requestPayload, endpoint, responseCallback);
switch (method) { };
case constants.HTTP_POST:
var PostMethod = Packages.org.apache.commons.httpclient.methods.PostMethod;
httpMethodObject = new PostMethod(url);
break;
case constants.HTTP_PUT:
var PutMethod = Packages.org.apache.commons.httpclient.methods.PutMethod;
httpMethodObject = new PutMethod(url);
break;
case constants.HTTP_GET:
var GetMethod = Packages.org.apache.commons.httpclient.methods.GetMethod;
httpMethodObject = new GetMethod(url);
break;
case constants.HTTP_DELETE:
var DeleteMethod = Packages.org.apache.commons.httpclient.methods.DeleteMethod;
httpMethodObject = new DeleteMethod(url);
break;
default:
throw new IllegalArgumentException("Invalid HTTP request type: " + method);
}
var Header = Packages.org.apache.commons.httpclient.Header;
var header = new Header();
header.setName(constants.CONTENT_TYPE_IDENTIFIER);
header.setValue(contentType);
httpMethodObject.addRequestHeader(header);
header = new Header();
header.setName(constants.ACCEPT_IDENTIFIER);
header.setValue(acceptType);
httpMethodObject.addRequestHeader(header);
header = new Header();
header.setName(constants.REFERER);
header.setValue(String(privateMethods.getClientDomain()));
httpMethodObject.addRequestHeader(header);
if (IS_OAUTH_ENABLED) {
var accessToken = privateMethods.getAccessToken();
if (accessToken) {
header = new Header();
header.setName(constants.AUTHORIZATION_HEADER);
header.setValue(constants.BEARER_PREFIX + accessToken);
httpMethodObject.addRequestHeader(header);
} else {
response.sendRedirect(devicemgtProps["httpsURL"] + "/devicemgt/login");
}
} /**
if (payload) { * This method invokes return initiateXMLHttpRequest for post calls
var stringRequestEntity = new StringRequestEntity(stringify(payload)); * @param endpoint Backend REST API url.
httpMethodObject.setRequestEntity(stringRequestEntity); * @param requestPayload payload/data if exists which is needed to be send.
} * @param responseCallback a function to be called with response retrieved.
var client = new HttpClient(); */
try { publicXMLHTTPInvokers.post = function (endpoint, requestPayload, responseCallback) {
client.executeMethod(httpMethodObject); return privateMethods.initiateXMLHTTPRequest(constants["HTTP_POST"], requestPayload, endpoint, responseCallback);
var status = httpMethodObject.getStatusCode(); };
if (status == 200) {
var responseContentDispositionHeader = httpMethodObject.getResponseHeader(constants.CONTENT_DISPOSITION_IDENTIFIER); /**
if (responseContentDispositionHeader) { * This method invokes return initiateXMLHttpRequest for put calls
return successCallback(httpMethodObject.getResponseBodyAsStream(), httpMethodObject.getResponseHeaders()); * @param endpoint Backend REST API url.
} else { * @param requestPayload payload/data if exists which is needed to be send.
return successCallback(httpMethodObject.getResponseBody()); * @param responseCallback a function to be called with response retrieved.
} */
} else { publicXMLHTTPInvokers.put = function (endpoint, requestPayload, responseCallback) {
return errorCallback(httpMethodObject.getResponseBody()); return privateMethods.initiateXMLHTTPRequest(constants["HTTP_PUT"], requestPayload, endpoint, responseCallback);
} };
} catch (e) {
return errorCallback(response); /**
} finally { * This method invokes return initiateXMLHttpRequest for delete calls
httpMethodObject.releaseConnection(); * @param endpoint Backend REST API url.
} * @param responseCallback a function to be called with response retrieved.
*/
publicXMLHTTPInvokers.delete = function (endpoint, responseCallback) {
var requestPayload = null;
return privateMethods.initiateXMLHTTPRequest(constants["HTTP_DELETE"], requestPayload, endpoint, responseCallback);
}; };
/**
* ---------------------------------------------------------------------------
* Start of WS-REQUEST based Interceptor implementations
* ---------------------------------------------------------------------------
*/
/** /**
* This method add Oauth authentication header to outgoing WS Requests if Oauth authentication is enabled. * This method add Oauth authentication header to outgoing WS Requests if Oauth authentication is enabled.
* @param action * @param action
@ -202,32 +173,26 @@ var backendServiceInvoker = function () {
* @param soapVersion soapVersion which need to used. * @param soapVersion soapVersion which need to used.
*/ */
privateMethods.initiateWSRequest = function (action, endpoint, successCallback, errorCallback, soapVersion, payload) { privateMethods.initiateWSRequest = function (action, endpoint, successCallback, errorCallback, soapVersion, payload) {
var ws = require('ws'); var ws = require("ws");
var wsRequest = new ws.WSRequest(); var wsRequest = new ws.WSRequest();
var options = []; var options = [];
if (IS_OAUTH_ENABLED) { if (devicemgtProps["isOAuthEnabled"]) {
var accessToken = privateMethods.getAccessToken(); var accessToken = privateMethods.getAccessToken();
if (accessToken) { if (accessToken) {
var authenticationHeaderName = String(constants.AUTHORIZATION_HEADER); var authenticationHeaderName = String(constants["AUTHORIZATION_HEADER"]);
var authenticationHeaderValue = String(constants.BEARER_PREFIX + accessToken); var authenticationHeaderValue = String(constants["BEARER_PREFIX"] + accessToken);
var headers = []; var headers = [];
var oAuthAuthenticationData = {}; var oAuthAuthenticationData = {};
oAuthAuthenticationData.name = authenticationHeaderName; oAuthAuthenticationData.name = authenticationHeaderName;
oAuthAuthenticationData.value = authenticationHeaderValue; oAuthAuthenticationData.value = authenticationHeaderValue;
headers.push(oAuthAuthenticationData); headers.push(oAuthAuthenticationData);
var referrerData = {};
referrerData.name = constants.REFERER;
referrerData.value = String(privateMethods.getClientDomain());
headers.push(referrerData);
options.HTTPHeaders = headers; options.HTTPHeaders = headers;
} else { } else {
response.sendRedirect(devicemgtProps["httpsURL"] + "/devicemgt/login"); response.sendRedirect(devicemgtProps["appContext"] + "login");
} }
} }
options.useSOAP = soapVersion; options.useSOAP = soapVersion;
options.useWSA = constants.WEB_SERVICE_ADDRESSING_VERSION; options.useWSA = constants["WEB_SERVICE_ADDRESSING_VERSION"];
options.action = action; options.action = action;
var wsResponse; var wsResponse;
try { try {
@ -245,68 +210,104 @@ var backendServiceInvoker = function () {
}; };
/** /**
* This method invokes return initiateXMLHttpRequest for get calls * This method invokes return initiateWSRequest for soap calls
* @param url target url. * @param action describes particular soap action.
* @param requestPayload SOAP request payload which is needed to be send.
* @param endpoint service end point to be triggered.
* @param successCallback a function to be called if the respond if successful. * @param successCallback a function to be called if the respond if successful.
* @param errorCallback a function to be called if en error is reserved. * @param errorCallback a function to be called if en error is reserved.
* @param soapVersion soapVersion which need to used.
*/ */
publicXMLHTTPInvokers.get = function (url, successCallback, errorCallback, contentType, acceptType) { publicWSInvokers.soapRequest = function (action, requestPayload, endpoint, successCallback, errorCallback, soapVersion) {
return privateMethods.initiateXMLHTTPRequest(constants.HTTP_GET, url, successCallback, errorCallback, contentType, acceptType); return privateMethods.initiateWSRequest(action, endpoint, successCallback, errorCallback, soapVersion, requestPayload);
}; };
/** /**
* This method invokes return initiateXMLHttpRequest for post calls * ---------------------------------------------------------------------------
* @param url target url. * Start of HTTP-CLIENT-REQUEST based Interceptor implementations
* @param payload payload/data which need to be send. * ---------------------------------------------------------------------------
* @param successCallback a function to be called if the respond if successful.
* @param errorCallback a function to be called if en error is reserved.
*/ */
publicXMLHTTPInvokers.post = function (url, payload, successCallback, errorCallback, contentType, acceptType) {
return privateMethods.initiateXMLHTTPRequest(constants.HTTP_POST, url, successCallback, errorCallback, payload, contentType, acceptType);
};
/** /**
* This method invokes return initiateXMLHttpRequest for put calls * This method add Oauth authentication header to outgoing HTTPClient Requests if Oauth authentication is enabled.
* @param method HTTP request type.
* @param url target url. * @param url target url.
* @param payload payload/data which need to be send. * @param payload payload/data which need to be send.
* @param successCallback a function to be called if the respond if successful. * @param successCallback a function to be called if the respond if successful.
* @param errorCallback a function to be called if en error is reserved. * @param errorCallback a function to be called if en error is reserved.
*/ */
publicXMLHTTPInvokers.put = function (url, payload, successCallback, errorCallback, contentType, acceptType) { privateMethods.initiateHTTPClientRequest = function (method, url, successCallback, errorCallback, payload) {
return privateMethods.initiateXMLHTTPRequest(constants.HTTP_PUT, url, successCallback, errorCallback, payload, contentType, acceptType); var HttpClient = Packages.org.apache.commons.httpclient.HttpClient;
}; var httpMethodObject;
switch (method) {
/** case constants["HTTP_GET"]:
* This method invokes return initiateXMLHttpRequest for delete calls var GetMethod = Packages.org.apache.commons.httpclient.methods.GetMethod;
* @param url target url. httpMethodObject = new GetMethod(url);
* @param successCallback a function to be called if the respond if successful. break;
* @param errorCallback a function to be called if en error is reserved. case constants["HTTP_POST"]:
*/ var PostMethod = Packages.org.apache.commons.httpclient.methods.PostMethod;
publicXMLHTTPInvokers.delete = function (url, successCallback, errorCallback, contentType, acceptType) { httpMethodObject = new PostMethod(url);
return privateMethods.initiateXMLHTTPRequest(constants.HTTP_DELETE, url, successCallback, errorCallback, contentType, acceptType); break;
}; case constants["HTTP_PUT"]:
var PutMethod = Packages.org.apache.commons.httpclient.methods.PutMethod;
httpMethodObject = new PutMethod(url);
break;
case constants["HTTP_DELETE"]:
var DeleteMethod = Packages.org.apache.commons.httpclient.methods.DeleteMethod;
httpMethodObject = new DeleteMethod(url);
break;
default:
throw new IllegalArgumentException("Invalid HTTP request method: " + method);
}
var Header = Packages.org.apache.commons.httpclient.Header;
var header = new Header();
header.setName(constants["CONTENT_TYPE_IDENTIFIER"]);
header.setValue(constants["APPLICATION_JSON"]);
httpMethodObject.addRequestHeader(header);
header = new Header();
header.setName(constants["ACCEPT_IDENTIFIER"]);
header.setValue(constants["APPLICATION_JSON"]);
httpMethodObject.addRequestHeader(header);
/** if (devicemgtProps["isOAuthEnabled"]) {
* This method invokes return initiateWSRequest for soap calls var accessToken = privateMethods.getAccessToken();
* @param endpoint service end point to be triggered. if (accessToken) {
* @param payload soap payload which need to be send. header = new Header();
* @param successCallback a function to be called if the respond if successful. header.setName(constants["AUTHORIZATION_HEADER"]);
* @param errorCallback a function to be called if en error is reserved. header.setValue(constants["BEARER_PREFIX"] + accessToken);
* @param soapVersion soapVersion which need to used. httpMethodObject.addRequestHeader(header);
*/ } else {
publicWSInvokers.soapRequest = function (action, endpoint, payload, successCallback, errorCallback, soapVersion) { response.sendRedirect(devicemgtProps["appContext"] + "login");
return privateMethods.initiateWSRequest(action, endpoint, successCallback, errorCallback, soapVersion, payload); }
}
var stringRequestEntity = new StringRequestEntity(stringify(payload));
httpMethodObject.setRequestEntity(stringRequestEntity);
var client = new HttpClient();
try {
client.executeMethod(httpMethodObject);
var status = httpMethodObject.getStatusCode();
if (status == 200) {
return successCallback(httpMethodObject.getResponseBody());
} else {
return errorCallback(httpMethodObject.getResponseBody());
}
} catch (e) {
return errorCallback(response);
} finally {
method.releaseConnection();
}
}; };
/** /**
* This method invokes return initiateHTTPClientRequest for get calls * This method invokes return initiateHTTPClientRequest for get calls
* @param url target url. * @param url target url.
* @param successCallback a function to be called if the respond if successful. * @param successCallback a function to be called if the respond if successful.
* @param errorCallback a function to be called if en error is reserved. * @param errorCallback a function to be called if en error is reserved.
*/ */
publicHTTPClientInvokers.get = function (url, successCallback, errorCallback, contentType, acceptType) { publicHTTPClientInvokers.get = function (url, successCallback, errorCallback) {
return privateMethods.initiateHTTPClientRequest(constants.HTTP_GET, url, successCallback, errorCallback, null, contentType, acceptType); var requestPayload = null;
return privateMethods.
initiateHTTPClientRequest(constants["HTTP_GET"], url, successCallback, errorCallback, requestPayload);
}; };
/** /**
@ -316,9 +317,9 @@ var backendServiceInvoker = function () {
* @param successCallback a function to be called if the respond if successful. * @param successCallback a function to be called if the respond if successful.
* @param errorCallback a function to be called if en error is reserved. * @param errorCallback a function to be called if en error is reserved.
*/ */
publicHTTPClientInvokers.post = function (url, payload, successCallback, errorCallback, contentType, acceptType) { publicHTTPClientInvokers.post = function (url, payload, successCallback, errorCallback) {
return privateMethods. return privateMethods.
initiateHTTPClientRequest(constants.HTTP_POST, url, successCallback, errorCallback, payload, contentType, acceptType); initiateHTTPClientRequest(constants["HTTP_POST"], url, successCallback, errorCallback, payload);
}; };
/** /**
@ -328,8 +329,9 @@ var backendServiceInvoker = function () {
* @param successCallback a function to be called if the respond if successful. * @param successCallback a function to be called if the respond if successful.
* @param errorCallback a function to be called if en error is reserved. * @param errorCallback a function to be called if en error is reserved.
*/ */
publicHTTPClientInvokers.put = function (url, payload, successCallback, errorCallback, contentType, acceptType) { publicHTTPClientInvokers.put = function (url, payload, successCallback, errorCallback) {
return privateMethods.initiateHTTPClientRequest(constants.HTTP_PUT, url, successCallback, errorCallback, payload, contentType, acceptType); return privateMethods.
initiateHTTPClientRequest(constants["HTTP_PUT"], url, successCallback, errorCallback, payload);
}; };
/** /**
@ -338,23 +340,16 @@ var backendServiceInvoker = function () {
* @param successCallback a function to be called if the respond if successful. * @param successCallback a function to be called if the respond if successful.
* @param errorCallback a function to be called if en error is reserved. * @param errorCallback a function to be called if en error is reserved.
*/ */
publicHTTPClientInvokers.delete = function (url, successCallback, errorCallback, contentType, acceptType) { publicHTTPClientInvokers.delete = function (url, successCallback, errorCallback) {
return privateMethods.initiateHTTPClientRequest(constants.HTTP_DELETE, url, successCallback, errorCallback, contentType, acceptType); var requestPayload = null;
return privateMethods.
initiateHTTPClientRequest(constants["HTTP_DELETE"], url, successCallback, errorCallback, requestPayload);
}; };
/** var publicMethods = {};
* This method fetch the current logged user from the session and returns publicMethods.XMLHttp = publicXMLHTTPInvokers;
* the tenant domain name of the user publicMethods.WS = publicWSInvokers;
* @returns {tenantDomain} publicMethods.HttpClient = publicHTTPClientInvokers;
*/
privateMethods.getClientDomain = function () {
var user = session.get(constants.USER_SESSION_KEY);
return user.domain;
}
var publicInvokers = {}; return publicMethods;
publicInvokers.XMLHttp = publicXMLHTTPInvokers;
publicInvokers.WS = publicWSInvokers;
publicInvokers.HttpClient = publicHTTPClientInvokers;
return publicInvokers;
}(); }();

@ -25,11 +25,12 @@ var util = function () {
var carbon = require('carbon'); var carbon = require('carbon');
var constants = require("/app/modules/constants.js"); var constants = require("/app/modules/constants.js");
var adminUser = devicemgtProps["adminUser"]; var adminUser = devicemgtProps["adminUser"];
var clientName = devicemgtProps["clientName"];
module.getDyanmicCredentials = function (owner) { module.getDyanmicCredentials = function (owner) {
var payload = { var payload = {
"callbackUrl": devicemgtProps.callBackUrl, "callbackUrl": devicemgtProps.callBackUrl,
"clientName": "devicemgt", "clientName": clientName,
"tokenScope": "admin", "tokenScope": "admin",
"owner": adminUser, "owner": adminUser,
"applicationType": "webapp", "applicationType": "webapp",
@ -79,7 +80,7 @@ var util = function () {
*/ */
module.getTokenWithPasswordGrantType = function (username, password, encodedClientKeys, scope) { module.getTokenWithPasswordGrantType = function (username, password, encodedClientKeys, scope) {
var xhr = new XMLHttpRequest(); var xhr = new XMLHttpRequest();
var tokenEndpoint = devicemgtProps.idPServer + "/token"; var tokenEndpoint = devicemgtProps.idPServer;
xhr.open("POST", tokenEndpoint, false); xhr.open("POST", tokenEndpoint, false);
xhr.setRequestHeader("Content-Type", "application/x-www-form-urlencoded"); xhr.setRequestHeader("Content-Type", "application/x-www-form-urlencoded");
xhr.setRequestHeader("Authorization", "Basic " + encodedClientKeys); xhr.setRequestHeader("Authorization", "Basic " + encodedClientKeys);
@ -119,7 +120,7 @@ var util = function () {
encodedExtractedAssertion = this.encode(extractedAssertion); encodedExtractedAssertion = this.encode(extractedAssertion);
var xhr = new XMLHttpRequest(); var xhr = new XMLHttpRequest();
var tokenEndpoint = devicemgtProps.idPServer + "/token"; var tokenEndpoint = devicemgtProps.idPServer;
xhr.open("POST", tokenEndpoint, false); xhr.open("POST", tokenEndpoint, false);
xhr.setRequestHeader("Content-Type", "application/x-www-form-urlencoded"); xhr.setRequestHeader("Content-Type", "application/x-www-form-urlencoded");
xhr.setRequestHeader("Authorization", "Basic " + clientKeys); xhr.setRequestHeader("Authorization", "Basic " + clientKeys);
@ -140,7 +141,7 @@ var util = function () {
module.refreshToken = function (tokenPair, clientData, scope) { module.refreshToken = function (tokenPair, clientData, scope) {
var xhr = new XMLHttpRequest(); var xhr = new XMLHttpRequest();
var tokenEndpoint = devicemgtProps.idPServer + "/token"; var tokenEndpoint = devicemgtProps.idPServer;
xhr.open("POST", tokenEndpoint, false); xhr.open("POST", tokenEndpoint, false);
xhr.setRequestHeader("Content-Type", "application/x-www-form-urlencoded"); xhr.setRequestHeader("Content-Type", "application/x-www-form-urlencoded");
xhr.setRequestHeader("Authorization", "Basic " + clientData); xhr.setRequestHeader("Authorization", "Basic " + clientData);

@ -1,5 +1,5 @@
/* /*
* Copyright (c) 2016, WSO2 Inc. (http://www.wso2.org) All Rights Reserved. * Copyright (c) 2015, WSO2 Inc. (http://www.wso2.org) All Rights Reserved.
* *
* WSO2 Inc. licenses this file to you under the Apache License, * WSO2 Inc. licenses this file to you under the Apache License,
* Version 2.0 (the "License"); you may not use this file except * Version 2.0 (the "License"); you may not use this file except
@ -10,63 +10,62 @@
* *
* Unless required by applicable law or agreed to in writing, * Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an * software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND,
* KIND, either express or implied. See the License for the * either express or implied. See the License for the
* specific language governing permissions and limitations * specific language governing permissions and limitations
* under the License. * under the License.
*/ */
var invokerUtil = function () { var invokerUtil = function () {
var module = {}; var publicMethods = {};
var privateMethods = {};
var END_POINT = window.location.origin+"/devicemgt/api/invoker/execute/"; privateMethods.execute = function (requestMethod, requestURL, requestPayload, successCallback, errorCallback) {
var restAPIRequestDetails = {};
restAPIRequestDetails["requestMethod"] = requestMethod;
restAPIRequestDetails["requestURL"] = requestURL;
restAPIRequestDetails["requestPayload"] = JSON.stringify(requestPayload);
var appContext = devicemgtProps["appContext"];
module.get = function (url, successCallback, errorCallback, contentType, acceptType) { var request = {
var payload = null; url: appContext + "api/invoker/execute/",
execute("GET", url, payload, successCallback, errorCallback, contentType, acceptType);
};
module.post = function (url, payload, successCallback, errorCallback, contentType, acceptType) {
execute("POST", url, payload, successCallback, errorCallback, contentType, acceptType);
};
module.put = function (url, payload, successCallback, errorCallback, contentType, acceptType) {
execute("PUT", url, payload, successCallback, errorCallback, contentType, acceptType);
};
module.delete = function (url, successCallback, errorCallback, contentType, acceptType) {
var payload = null;
execute("DELETE", url, payload, successCallback, errorCallback, contentType, acceptType);
};
function execute (methoad, url, payload, successCallback, errorCallback, contentType, acceptType) {
if(contentType == undefined){
contentType = "application/json";
}
if(acceptType == undefined){
acceptType = "application/json";
}
var data = {
url: END_POINT,
type: "POST", type: "POST",
contentType: contentType, contentType: "application/json",
accept: acceptType, data: JSON.stringify(restAPIRequestDetails),
success: successCallback accept: "application/json",
}; success: successCallback,
var paramValue = {}; error: function (jqXHR) {
paramValue.actionMethod = methoad; if (jqXHR.status == 401) {
paramValue.actionUrl = url;
paramValue.actionPayload = payload;
if(contentType == "application/json"){
paramValue.actionPayload = JSON.stringify(payload);
}
data.data = JSON.stringify(paramValue);
$.ajax(data).fail(function (jqXHR) {
if (jqXHR.status == "401") {
console.log("Unauthorized access attempt!"); console.log("Unauthorized access attempt!");
$(modalPopupContent).html($('#error-msg').html()); $(modalPopupContent).html($("#error-msg").html());
showPopup(); showPopup();
} else { } else {
errorCallback(jqXHR); errorCallback(jqXHR);
} }
}); }
};
$.ajax(request);
};
publicMethods.get = function (requestURL, successCallback, errorCallback) {
var requestPayload = null;
privateMethods.execute("GET", requestURL, requestPayload, successCallback, errorCallback);
};
publicMethods.post = function (requestURL, requestPayload, successCallback, errorCallback) {
privateMethods.execute("POST", requestURL, requestPayload, successCallback, errorCallback);
}; };
return module;
publicMethods.put = function (requestURL, requestPayload, successCallback, errorCallback) {
privateMethods.execute("PUT", requestURL, requestPayload, successCallback, errorCallback);
};
publicMethods.delete = function (requestURL, successCallback, errorCallback) {
var requestPayload = null;
privateMethods.execute("DELETE", requestURL, requestPayload, successCallback, errorCallback);
};
return publicMethods;
}(); }();

Loading…
Cancel
Save