Merging emm module changes to devicemgt iot app

revert-70aa11f8
Ace 8 years ago
parent 624e7df688
commit cf887a2e93

@ -46,25 +46,25 @@ 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;
}
xmlHttpRequest.setRequestHeader(constants.CONTENT_TYPE_IDENTIFIER, contentType);
xmlHttpRequest.setRequestHeader(constants.ACCEPT_IDENTIFIER, acceptType);
if (IS_OAUTH_ENABLED) { if (IS_OAUTH_ENABLED) {
var accessToken = privateMethods.getAccessToken(); var accessToken = privateMethods.getAccessToken();
if (!accessToken) { if (!accessToken) {
@ -73,43 +73,145 @@ var backendServiceInvoker = function () {
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) {
if (xmlHttpRequest.responseText != null) { if (xmlHttpRequest.status == 401 && (xmlHttpRequest.responseText == TOKEN_EXPIRED ||
return successCallback(parse(xmlHttpRequest.responseText)); xmlHttpRequest.responseText == TOKEN_INVALID ) && count < 5) {
} else {
return successCallback({"status": xmlHttpRequest.status, "messageFromServer": "Operation Completed"});
}
} else if (xmlHttpRequest.status == 401 && (xmlHttpRequest.responseText == TOKEN_EXPIRED ||
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 responseCallback a function to be called with response retrieved.
*/
privateMethods.initiateXMLHTTPRequest = function (httpMethod, requestPayload, endpoint, responseCallback) {
return privateMethods.execute(httpMethod, requestPayload, endpoint, responseCallback, 0);
};
/**
* This method invokes return initiateXMLHttpRequest for get calls
* @param endpoint Backend REST API url.
* @param responseCallback a function to be called with response retrieved.
*/
publicXMLHTTPInvokers.get = function (endpoint, responseCallback) {
var requestPayload = null;
return privateMethods.initiateXMLHTTPRequest(constants["HTTP_GET"], requestPayload, endpoint, responseCallback);
};
/**
* This method invokes return initiateXMLHttpRequest for post calls
* @param endpoint Backend REST API url.
* @param requestPayload payload/data if exists which is needed to be send.
* @param responseCallback a function to be called with response retrieved.
*/
publicXMLHTTPInvokers.post = function (endpoint, requestPayload, responseCallback) {
return privateMethods.initiateXMLHTTPRequest(constants["HTTP_POST"], requestPayload, endpoint, responseCallback);
};
/**
* This method invokes return initiateXMLHttpRequest for put calls
* @param endpoint Backend REST API url.
* @param requestPayload payload/data if exists which is needed to be send.
* @param responseCallback a function to be called with response retrieved.
*/
publicXMLHTTPInvokers.put = function (endpoint, requestPayload, responseCallback) {
return privateMethods.initiateXMLHTTPRequest(constants["HTTP_PUT"], requestPayload, endpoint, responseCallback);
};
/**
* This method invokes return initiateXMLHttpRequest for delete calls
* @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.
* @param action
* @param endpoint service end point to be triggered.
* @param payload soap payload 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.
* @param soapVersion soapVersion which need to used.
*/ */
privateMethods.initiateXMLHTTPRequest = function (method, url, successCallback, errorCallback, payload, contentType, acceptType) { privateMethods.initiateWSRequest = function (action, endpoint, successCallback, errorCallback, soapVersion, payload) {
if (privateMethods.getAccessToken()) { var ws = require('ws');
return privateMethods.execute(method, url, successCallback, errorCallback, payload, 0, contentType, acceptType); var wsRequest = new ws.WSRequest();
var options = [];
if (IS_OAUTH_ENABLED) {
var accessToken = privateMethods.getAccessToken();
if (accessToken) {
var authenticationHeaderName = String(constants.AUTHORIZATION_HEADER);
var authenticationHeaderValue = String(constants.BEARER_PREFIX + accessToken);
var headers = [];
var oAuthAuthenticationData = {};
oAuthAuthenticationData.name = authenticationHeaderName;
oAuthAuthenticationData.value = authenticationHeaderValue;
headers.push(oAuthAuthenticationData);
options.HTTPHeaders = headers;
} else {
response.sendRedirect(devicemgtProps["httpsURL"] + "/devicemgt/login");
}
} }
options.useSOAP = soapVersion;
options.useWSA = constants.WEB_SERVICE_ADDRESSING_VERSION;
options.action = action;
var wsResponse;
try {
wsRequest.open(options, endpoint, false);
if (payload) {
wsRequest.send(payload);
} else {
wsRequest.send();
}
wsResponse = wsRequest.responseE4X;
} catch (e) {
return errorCallback(e);
}
return successCallback(wsResponse);
};
/**
* This method invokes return initiateWSRequest for soap calls
* @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 errorCallback a function to be called if en error is reserved.
* @param soapVersion soapVersion which need to used.
*/
publicWSInvokers.soapRequest = function (action, endpoint, payload, successCallback, errorCallback, soapVersion) {
return privateMethods.initiateWSRequest(action, endpoint, successCallback, errorCallback, soapVersion, payload);
}; };
/**
* ---------------------------------------------------------------------------
* Start of HTTP-CLIENT-REQUEST based Interceptor implementations
* ---------------------------------------------------------------------------
*/
/** /**
* This method add Oauth authentication header to outgoing HTTPClient Requests if Oauth authentication is enabled. * This method add Oauth authentication header to outgoing HTTPClient Requests if Oauth authentication is enabled.
* @param method HTTP request type. * @param method HTTP request type.
@ -118,7 +220,7 @@ 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.
*/ */
privateMethods.initiateHTTPClientRequest = function (method, url, successCallback, errorCallback, payload, contentType, acceptType) { privateMethods.initiateHTTPClientRequest = function (method, url, successCallback, errorCallback, payload) {
var HttpClient = Packages.org.apache.commons.httpclient.HttpClient; var HttpClient = Packages.org.apache.commons.httpclient.HttpClient;
var httpMethodObject; var httpMethodObject;
switch (method) { switch (method) {
@ -144,11 +246,9 @@ var backendServiceInvoker = function () {
var Header = Packages.org.apache.commons.httpclient.Header; var Header = Packages.org.apache.commons.httpclient.Header;
var header = new Header(); var header = new Header();
header.setName(constants.CONTENT_TYPE_IDENTIFIER); header.setName(constants.CONTENT_TYPE_IDENTIFIER);
header.setValue(contentType);
httpMethodObject.addRequestHeader(header); httpMethodObject.addRequestHeader(header);
header = new Header(); header = new Header();
header.setName(constants.ACCEPT_IDENTIFIER); header.setName(constants.ACCEPT_IDENTIFIER);
header.setValue(acceptType);
httpMethodObject.addRequestHeader(header); httpMethodObject.addRequestHeader(header);
if (IS_OAUTH_ENABLED) { if (IS_OAUTH_ENABLED) {
var accessToken = privateMethods.getAccessToken(); var accessToken = privateMethods.getAccessToken();
@ -160,7 +260,6 @@ var backendServiceInvoker = function () {
} else { } else {
response.sendRedirect(devicemgtProps["httpsURL"] + "/devicemgt/login"); response.sendRedirect(devicemgtProps["httpsURL"] + "/devicemgt/login");
} }
} }
if (payload) { if (payload) {
var stringRequestEntity = new StringRequestEntity(stringify(payload)); var stringRequestEntity = new StringRequestEntity(stringify(payload));
@ -187,115 +286,16 @@ var backendServiceInvoker = function () {
} }
}; };
/**
* This method add Oauth authentication header to outgoing WS Requests if Oauth authentication is enabled.
* @param action
* @param endpoint service end point to be triggered.
* @param payload soap payload 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.
* @param soapVersion soapVersion which need to used.
*/
privateMethods.initiateWSRequest = function (action, endpoint, successCallback, errorCallback, soapVersion, payload) {
var ws = require('ws');
var wsRequest = new ws.WSRequest();
var options = [];
if (IS_OAUTH_ENABLED) {
var accessToken = privateMethods.getAccessToken();
if (accessToken) {
var authenticationHeaderName = String(constants.AUTHORIZATION_HEADER);
var authenticationHeaderValue = String(constants.BEARER_PREFIX + accessToken);
var headers = [];
var oAuthAuthenticationData = {};
oAuthAuthenticationData.name = authenticationHeaderName;
oAuthAuthenticationData.value = authenticationHeaderValue;
headers.push(oAuthAuthenticationData);
options.HTTPHeaders = headers;
} else {
response.sendRedirect(devicemgtProps["httpsURL"] + "/devicemgt/login");
}
}
options.useSOAP = soapVersion;
options.useWSA = constants.WEB_SERVICE_ADDRESSING_VERSION;
options.action = action;
var wsResponse;
try {
wsRequest.open(options, endpoint, false);
if (payload) {
wsRequest.send(payload);
} else {
wsRequest.send();
}
wsResponse = wsRequest.responseE4X;
} catch (e) {
return errorCallback(e);
}
return successCallback(wsResponse);
};
/**
* This method invokes return initiateXMLHttpRequest for get calls
* @param url target url.
* @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.get = function (url, successCallback, errorCallback, contentType, acceptType) {
return privateMethods.initiateXMLHTTPRequest(constants.HTTP_GET, url, successCallback, errorCallback, contentType, acceptType);
};
/**
* This method invokes return initiateXMLHttpRequest for post calls
* @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.
*/
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
* @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.
*/
publicXMLHTTPInvokers.put = function (url, payload, successCallback, errorCallback, contentType, acceptType) {
return privateMethods.initiateXMLHTTPRequest(constants.HTTP_PUT, url, successCallback, errorCallback, payload, contentType, acceptType);
};
/**
* This method invokes return initiateXMLHttpRequest for delete calls
* @param url target url.
* @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.delete = function (url, successCallback, errorCallback, contentType, acceptType) {
return privateMethods.initiateXMLHTTPRequest(constants.HTTP_DELETE, url, successCallback, errorCallback, contentType, acceptType);
};
/**
* This method invokes return initiateWSRequest for soap calls
* @param endpoint service end point to be triggered.
* @param payload soap payload 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.
* @param soapVersion soapVersion which need to used.
*/
publicWSInvokers.soapRequest = function (action, endpoint, payload, successCallback, errorCallback, soapVersion) {
return privateMethods.initiateWSRequest(action, endpoint, successCallback, errorCallback, soapVersion, payload);
};
/** /**
* 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, contentType, acceptType); var requestPayload = null;
return privateMethods.
initiateHTTPClientRequest(constants["HTTP_GET"], url, successCallback, errorCallback, requestPayload);
}; };
/** /**
@ -305,9 +305,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);
}; };
/** /**
@ -317,8 +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.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);
}; };
/** /**
@ -327,13 +328,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 publicInvokers = {}; var publicMethods = {};
publicInvokers.XMLHttp = publicXMLHTTPInvokers; publicMethods.XMLHttp = publicXMLHTTPInvokers;
publicInvokers.WS = publicWSInvokers; publicMethods.WS = publicWSInvokers;
publicInvokers.HttpClient = publicHTTPClientInvokers; publicMethods.HttpClient = publicHTTPClientInvokers;
return publicInvokers;
}(); return publicMethods;
}();

@ -36,7 +36,8 @@ deviceModule = function () {
var publicMethods = {}; var publicMethods = {};
var privateMethods = {}; var privateMethods = {};
var deviceCloudService = devicemgtProps["httpsURL"] + "/common/device_manager"; //var deviceCloudService = devicemgtProps["httpsURL"] + "/common/device_manager";
var deviceManagementService = utility.getDeviceManagementService();
privateMethods.validateAndReturn = function (value) { privateMethods.validateAndReturn = function (value) {
return (value == undefined || value == null) ? constants.UNSPECIFIED : value; return (value == undefined || value == null) ? constants.UNSPECIFIED : value;
@ -97,6 +98,61 @@ deviceModule = function () {
} }
}; };
/*
@Deprecated
*/
publicMethods.listDevicesForUser = function (username) {
var carbonUser = session.get(constants.USER_SESSION_KEY);
var utility = require('/modules/utility.js').utility;
if (!carbonUser) {
log.error("User object was not found in the session");
throw constants.ERRORS.USER_NOT_FOUND;
}
try {
utility.startTenantFlow(carbonUser);
var deviceManagementService = utility.getDeviceManagementService();
var devices = deviceManagementService.getDeviceListOfUser(username);
var deviceList = [];
var i, device, propertiesList, deviceObject;
for (i = 0; i < devices.size(); i++) {
device = devices.get(i);
propertiesList = DeviceManagerUtil.convertDevicePropertiesToMap(device.getProperties());
deviceObject = {};
deviceObject[constants.DEVICE_IDENTIFIER] =
privateMethods.validateAndReturn(device.getDeviceIdentifier());
deviceObject[constants.DEVICE_NAME] =
privateMethods.validateAndReturn(device.getName());
deviceObject[constants.DEVICE_OWNERSHIP] =
privateMethods.validateAndReturn(device.getEnrolmentInfo().getOwnership());
deviceObject[constants.DEVICE_OWNER] =
privateMethods.validateAndReturn(device.getEnrolmentInfo().getOwner());
deviceObject[constants.DEVICE_TYPE] =
privateMethods.validateAndReturn(device.getType());
deviceObject[constants.DEVICE_PROPERTIES] = {};
if (device.getType() == constants.PLATFORM_IOS) {
deviceObject[constants.DEVICE_PROPERTIES][constants.DEVICE_MODEL] =
privateMethods.validateAndReturn(propertiesList.get(constants.DEVICE_PRODUCT));
deviceObject[constants.DEVICE_PROPERTIES][constants.DEVICE_VENDOR] = constants.VENDOR_APPLE;
} else {
deviceObject[constants.DEVICE_PROPERTIES][constants.DEVICE_MODEL] =
privateMethods.validateAndReturn(propertiesList.get(constants.DEVICE_MODEL));
deviceObject[constants.DEVICE_PROPERTIES][constants.DEVICE_VENDOR] =
privateMethods.validateAndReturn(propertiesList.get(constants.DEVICE_VENDOR));
}
deviceObject[constants.DEVICE_PROPERTIES][constants.DEVICE_OS_VERSION] =
privateMethods.validateAndReturn(propertiesList.get(constants.DEVICE_OS_VERSION));
deviceList.push(deviceObject);
}
return deviceList;
} catch (e) {
throw e;
} finally {
utility.endTenantFlow();
}
};
/* /*
@Deprecated @Deprecated
*/ */
@ -216,36 +272,36 @@ deviceModule = function () {
try { try {
utility.startTenantFlow(carbonUser); utility.startTenantFlow(carbonUser);
var url = devicemgtProps["httpsURL"] + constants.ADMIN_SERVICE_CONTEXT + "/devices/view?type=" + deviceType + "&id=" + deviceId; var url = devicemgtProps["httpsURL"] + constants.ADMIN_SERVICE_CONTEXT + "/api/device-mgt/v1.0/devices/" + deviceType + "/" + deviceId;
return serviceInvokers.XMLHttp.get( return serviceInvokers.XMLHttp.get(
url, function (responsePayload) { url,
var device = responsePayload.responseContent; function (backendResponse) {
if (device) { var response = {};
var propertiesList = device["properties"]; if (backendResponse.status == 200 && backendResponse.responseText) {
var properties = {}; response["status"] = "success";
if (propertiesList){ var device = parse(backendResponse.responseText);
for (var i = 0; i < propertiesList.length; i++) { var propertiesList = device["properties"];
properties[propertiesList[i]["name"]] = propertiesList[i]["value"]; var properties = {};
} for (var i = 0; i < propertiesList.length; i++) {
} properties[propertiesList[i]["name"]] =
var deviceObject = {}; propertiesList[i]["value"];
deviceObject[constants["DEVICE_IDENTIFIER"]] = device["deviceIdentifier"];
deviceObject[constants["DEVICE_NAME"]] = device["name"];
deviceObject[constants["DEVICE_OWNERSHIP"]] = device["enrolmentInfo"]["ownership"];
deviceObject[constants["DEVICE_OWNER"]] = device["enrolmentInfo"]["owner"];
deviceObject[constants["DEVICE_STATUS"]] = device["enrolmentInfo"]["status"];
deviceObject[constants["DEVICE_TYPE"]] = device["type"];
if (device["type"] == constants["PLATFORM_IOS"]) {
properties[constants["DEVICE_MODEL"]] = properties[constants["DEVICE_PRODUCT"]];
delete properties[constants["DEVICE_PRODUCT"]];
properties[constants["DEVICE_VENDOR"]] = constants["VENDOR_APPLE"];
}
deviceObject[constants["DEVICE_PROPERTIES"]] = properties;
return deviceObject;
} }
}, var deviceObject = {};
function (responsePayload) { deviceObject[constants["DEVICE_IDENTIFIER"]] = device["deviceIdentifier"];
var response = {}; deviceObject[constants["DEVICE_NAME"]] = device["name"];
deviceObject[constants["DEVICE_OWNERSHIP"]] = device["enrolmentInfo"]["ownership"];
deviceObject[constants["DEVICE_OWNER"]] = device["enrolmentInfo"]["owner"];
deviceObject[constants["DEVICE_STATUS"]] = device["enrolmentInfo"]["status"];
deviceObject[constants["DEVICE_TYPE"]] = device["type"];
if (device["type"] == constants["PLATFORM_IOS"]) {
properties[constants["DEVICE_MODEL"]] = properties[constants["DEVICE_PRODUCT"]];
delete properties[constants["DEVICE_PRODUCT"]];
properties[constants["DEVICE_VENDOR"]] = constants["VENDOR_APPLE"];
}
deviceObject[constants["DEVICE_PROPERTIES"]] = properties;
response["content"] = deviceObject;
return response;
} else {
response["status"] = "error"; response["status"] = "error";
return response; return response;
} }

@ -32,13 +32,11 @@ var invokerRequestWrapper = function () {
var response = serviceInvokers.XMLHttp.get(url, function (responsePayload) { var response = serviceInvokers.XMLHttp.get(url, function (responsePayload) {
var response = {}; var response = {};
response.content = responsePayload["responseContent"]; response.content = responsePayload["responseContent"];
response.status = "success"; if (responsePayload.status == 200) {
return response; response.status = "success";
}, } else {
function (responsePayload) { response.status = "error";
var response = {}; }
response.content = responsePayload;
response.status = "error";
return response; return response;
}); });
return response; return response;

@ -31,73 +31,91 @@ policyModule = function () {
var publicMethods = {}; var publicMethods = {};
var privateMethods = {}; var privateMethods = {};
privateMethods.handleGetAllPoliciesError = function (responsePayload) { privateMethods.handleGetAllPoliciesResponse = function (backendResponse) {
var response = {}; var response = {};
response.status = "error"; if (backendResponse.status = 200) {
/* responsePayload == "Scope validation failed" var isUpdated = false;
Here the response.context("Scope validation failed") is used other then response.status(401). var policyListFromRestEndpoint = parse(backendResponse.responseText)["policies"];
Reason for this is IDP return 401 as the status in 4 different situations such as, var policyListToView = [];
1. UnAuthorized. var i, policyObjectFromRestEndpoint, policyObjectToView;
2. Scope Validation Failed. for (i = 0; i < policyListFromRestEndpoint.length; i++) {
3. Permission Denied. // get list object
4. Access Token Expired. policyObjectFromRestEndpoint = policyListFromRestEndpoint[i];
5. Access Token Invalid. // populate list object values to view-object
In these cases in order to identify the correct situation we have to compare the unique value from status and policyObjectToView = {};
context which is context. policyObjectToView["id"] = policyObjectFromRestEndpoint["id"];
*/ policyObjectToView["priorityId"] = policyObjectFromRestEndpoint["priorityId"];
if (responsePayload == "Scope validation failed") { policyObjectToView["name"] = policyObjectFromRestEndpoint["policyName"];
response.content = "Permission Denied"; policyObjectToView["platform"] = policyObjectFromRestEndpoint["profile"]["deviceType"]["name"];
} else { policyObjectToView["ownershipType"] = policyObjectFromRestEndpoint["ownershipType"];
response.content = responsePayload;
} var assignedRoleCount = policyObjectFromRestEndpoint["roles"].length;
return response; var assignedUserCount = policyObjectFromRestEndpoint["users"].length;
};
if (assignedRoleCount == 0) {
policyObjectToView["roles"] = "None";
} else if (assignedRoleCount == 1) {
policyObjectToView["roles"] = policyObjectFromRestEndpoint["roles"][0];
} else if (assignedRoleCount > 1) {
policyObjectToView["roles"] = policyObjectFromRestEndpoint["roles"][0] + ", ...";
}
if (assignedUserCount == 0) {
policyObjectToView["users"] = "None";
} else if (assignedUserCount == 1) {
policyObjectToView["users"] = policyObjectFromRestEndpoint["users"][0];
} else if (assignedUserCount > 1) {
policyObjectToView["users"] = policyObjectFromRestEndpoint["users"][0] + ", ...";
}
privateMethods.handleGetAllPoliciesSuccess = function (responsePayload) { policyObjectToView["compliance"] = policyObjectFromRestEndpoint["compliance"];
var isUpdated = false;
var policyListFromRestEndpoint = responsePayload["responseContent"];
var policyListToView = [];
var i, policyObjectFromRestEndpoint, policyObjectToView;
for (i = 0; i < policyListFromRestEndpoint.length; i++) {
// get list object
policyObjectFromRestEndpoint = policyListFromRestEndpoint[i];
// populate list object values to view-object
policyObjectToView = {};
policyObjectToView["id"] = policyObjectFromRestEndpoint["id"];
policyObjectToView["priorityId"] = policyObjectFromRestEndpoint["priorityId"];
policyObjectToView["name"] = policyObjectFromRestEndpoint["policyName"];
policyObjectToView["platform"] = policyObjectFromRestEndpoint["profile"]["deviceType"]["name"];
policyObjectToView["icon"] = utility.getDeviceThumb(policyObjectToView["platform"]);
policyObjectToView["ownershipType"] = policyObjectFromRestEndpoint["ownershipType"];
policyObjectToView["roles"] = privateMethods.
getElementsInAString(policyObjectFromRestEndpoint["roles"]);
policyObjectToView["users"] = privateMethods.
getElementsInAString(policyObjectFromRestEndpoint["users"]);
policyObjectToView["compliance"] = policyObjectFromRestEndpoint["compliance"];
if (policyObjectFromRestEndpoint["active"] == true && policyObjectFromRestEndpoint["updated"] == true) { if (policyObjectFromRestEndpoint["active"] == true &&
policyObjectToView["status"] = "Active/Updated"; policyObjectFromRestEndpoint["updated"] == true) {
isUpdated = true; policyObjectToView["status"] = "Active/Updated";
} else if (policyObjectFromRestEndpoint["active"] == true && isUpdated = true;
policyObjectFromRestEndpoint["updated"] == false) { } else if (policyObjectFromRestEndpoint["active"] == true &&
policyObjectToView["status"] = "Active"; policyObjectFromRestEndpoint["updated"] == false) {
} else if (policyObjectFromRestEndpoint["active"] == false && policyObjectToView["status"] = "Active";
policyObjectFromRestEndpoint["updated"] == true) { } else if (policyObjectFromRestEndpoint["active"] == false &&
policyObjectToView["status"] = "Inactive/Updated"; policyObjectFromRestEndpoint["updated"] == true) {
isUpdated = true; policyObjectToView["status"] = "Inactive/Updated";
} else if (policyObjectFromRestEndpoint["active"] == false && isUpdated = true;
policyObjectFromRestEndpoint["updated"] == false) { } else if (policyObjectFromRestEndpoint["active"] == false &&
policyObjectToView["status"] = "Inactive"; policyObjectFromRestEndpoint["updated"] == false) {
policyObjectToView["status"] = "Inactive";
}
// push view-objects to list
policyListToView.push(policyObjectToView);
} }
// push view-objects to list // generate response
policyListToView.push(policyObjectToView); response.updated = isUpdated;
response.status = "success";
response.content = policyListToView;
log.info(stringify(policyListToView));
return response;
} else {
response.status = "error";
/* backendResponse.responseText == "Scope validation failed"
Here the response.context("Scope validation failed") is used other then response.status(401).
Reason for this is IDP return 401 as the status in 4 different situations such as,
1. UnAuthorized.
2. Scope Validation Failed.
3. Permission Denied.
4. Access Token Expired.
5. Access Token Invalid.
In these cases in order to identify the correct situation we have to compare the unique value from status and
context which is context.
*/
if (backendResponse.responseText == "Scope validation failed") {
response.content = "Permission Denied";
} else {
response.content = backendResponse.responseText;
}
return response;
} }
// generate response
var response = {};
response.updated = isUpdated;
response.status = "success";
response.content = policyListToView;
return response;
}; };
publicMethods.addPolicy = function (policyName, deviceType, policyDefinition, policyDescription, publicMethods.addPolicy = function (policyName, deviceType, policyDefinition, policyDescription,
@ -155,9 +173,8 @@ policyModule = function () {
throw constants["ERRORS"]["USER_NOT_FOUND"]; throw constants["ERRORS"]["USER_NOT_FOUND"];
} }
try { try {
var url = devicemgtProps["httpsURL"] + constants.ADMIN_SERVICE_CONTEXT + "/policies"; var url = devicemgtProps["httpsURL"] + constants.ADMIN_SERVICE_CONTEXT + "/policies?offset=0&limit=100";
return serviceInvokers.XMLHttp. return serviceInvokers.XMLHttp.get(url, privateMethods.handleGetAllPoliciesResponse);
get(url, privateMethods.handleGetAllPoliciesSuccess, privateMethods.handleGetAllPoliciesError);
} catch (e) { } catch (e) {
throw e; throw e;
} }

@ -66,22 +66,18 @@ var userModule = function () {
*/ */
privateMethods.callBackend = function (url, method) { privateMethods.callBackend = function (url, method) {
if (constants.HTTP_GET == method) { if (constants.HTTP_GET == method) {
var response = serviceInvokers.XMLHttp.get(url, function (responsePayload) { return serviceInvokers.XMLHttp.get(url,
var response = {}; function (backendResponse) {
response.content = responsePayload["responseContent"]; var response = {};
if (responsePayload["responseContent"] == null && responsePayload != null) { response.content = backendResponse.responseText;
response.content = responsePayload; if (backendResponse.status == 200) {
response.status = "success";
} else {
response.status = "error";
}
return response;
} }
response.status = "success"; );
return response;
},
function (responsePayload) {
var response = {};
response.content = responsePayload;
response.status = "error";
return response;
});
return response;
} else { } else {
log.error("Programming error : This method only support HTTP GET requests."); log.error("Programming error : This method only support HTTP GET requests.");
} }
@ -382,9 +378,12 @@ var userModule = function () {
} }
try { try {
utility.startTenantFlow(carbonUser); utility.startTenantFlow(carbonUser);
var url = devicemgtProps["httpsURL"] + constants.ADMIN_SERVICE_CONTEXT + "/users"; var url = devicemgtProps["httpsURL"] + constants.ADMIN_SERVICE_CONTEXT + "/users?offset=0&limit=100";
return privateMethods.callBackend(url, constants.HTTP_GET); var response = privateMethods.callBackend(url, constants["HTTP_GET"]);
if (response.status == "success") {
response.content = parse(response.content).users;
}
return response;
} catch (e) { } catch (e) {
throw e; throw e;
} finally { } finally {
@ -409,8 +408,10 @@ var userModule = function () {
var carbonUser = privateMethods.getCarbonUser(); var carbonUser = privateMethods.getCarbonUser();
try { try {
utility.startTenantFlow(carbonUser); utility.startTenantFlow(carbonUser);
var url = devicemgtProps["httpsURL"] + constants.ADMIN_SERVICE_CONTEXT + "/users/view?username=" + username; var url = devicemgtProps["httpsURL"] + constants.ADMIN_SERVICE_CONTEXT + "/users/" +
var response = privateMethods.callBackend(url, constants.HTTP_GET); encodeURIComponent(username);
var response = privateMethods.callBackend(url, constants["HTTP_GET"]);
response["content"] = parse(response.content);
response["userDomain"] = carbonUser.domain; response["userDomain"] = carbonUser.domain;
return response; return response;
} catch (e) { } catch (e) {
@ -420,17 +421,17 @@ var userModule = function () {
} }
}; };
/** /**
* TODO: comment * Returns a set of roles assigned to a particular user
* @param username * @param username
* @returns {*} * @returns {object} a response object with status and content on success.
*/ */
publicMethods.getRolesByUsername = function (username) { publicMethods.getRolesByUsername = function (username) {
var carbonUser = privateMethods.getCarbonUser(); var carbonUser = privateMethods.getCarbonUser();
try { try {
utility.startTenantFlow(carbonUser); utility.startTenantFlow(carbonUser);
var url = devicemgtProps["httpsURL"] + constants.ADMIN_SERVICE_CONTEXT + "/users/roles?username=" + username; var url = devicemgtProps["httpsURL"] + constants.ADMIN_SERVICE_CONTEXT + + "/users/" +
var response = privateMethods.callBackend(url, constants.HTTP_GET); encodeURIComponent(username) + "/roles";
return response; return privateMethods.callBackend(url, constants["HTTP_GET"]);
} catch (e) { } catch (e) {
throw e; throw e;
} finally { } finally {
@ -464,6 +465,7 @@ var userModule = function () {
*/ */
/** /**
* Get User Roles from user store (Internal roles not included). * Get User Roles from user store (Internal roles not included).
* @returns {object} a response object with status and content on success.
*/ */
publicMethods.getRoles = function () { publicMethods.getRoles = function () {
var carbonUser = session.get(constants["USER_SESSION_KEY"]); var carbonUser = session.get(constants["USER_SESSION_KEY"]);
@ -475,7 +477,11 @@ var userModule = function () {
try { try {
utility.startTenantFlow(carbonUser); utility.startTenantFlow(carbonUser);
var url = devicemgtProps["httpsURL"] + constants.ADMIN_SERVICE_CONTEXT + "/roles"; var url = devicemgtProps["httpsURL"] + constants.ADMIN_SERVICE_CONTEXT + "/roles";
return privateMethods.callBackend(url, constants.HTTP_GET); var response = privateMethods.callBackend(url, constants["HTTP_GET"]);
if (response.status == "success") {
response.content = parse(response.content).roles;
}
return response;
} catch (e) { } catch (e) {
throw e; throw e;
} finally { } finally {
@ -488,8 +494,10 @@ var userModule = function () {
*/ */
/** /**
* Get User Roles from user store (Internal roles not included). * Get User Roles from user store (Internal roles not included).
* @returns {object} a response object with status and content on success.
*/ */
publicMethods.getRolesByUserStore = function (userStore) { publicMethods.getRolesByUserStore = function () {
var ROLE_LIMIT = devicemgtProps.pageSize;
var carbonUser = session.get(constants["USER_SESSION_KEY"]); var carbonUser = session.get(constants["USER_SESSION_KEY"]);
var utility = require('/app/modules/utility.js')["utility"]; var utility = require('/app/modules/utility.js')["utility"];
if (!carbonUser) { if (!carbonUser) {
@ -498,8 +506,12 @@ var userModule = function () {
} }
try { try {
utility.startTenantFlow(carbonUser); utility.startTenantFlow(carbonUser);
var url = devicemgtProps["httpsURL"] + constants.ADMIN_SERVICE_CONTEXT + "/roles/" + encodeURIComponent(userStore); var url = devicemgtProps["httpsURL"] + constants.ADMIN_SERVICE_CONTEXT + "/roles?limit=" + ROLE_LIMIT;
return privateMethods.callBackend(url, constants.HTTP_GET); var response = privateMethods.callBackend(url, constants["HTTP_GET"]);
if (response.status == "success") {
response.content = parse(response.content).roles;
}
return response;
} catch (e) { } catch (e) {
throw e; throw e;
} finally { } finally {
@ -520,7 +532,11 @@ var userModule = function () {
try { try {
utility.startTenantFlow(carbonUser); utility.startTenantFlow(carbonUser);
var url = devicemgtProps["httpsURL"] + constants.ADMIN_SERVICE_CONTEXT + "/devices/types"; var url = devicemgtProps["httpsURL"] + constants.ADMIN_SERVICE_CONTEXT + "/devices/types";
return privateMethods.callBackend(url, constants.HTTP_GET); var response = privateMethods.callBackend(url, constants["HTTP_GET"]);
if (response.status == "success") {
response.content = parse(response.content);
}
return response;
} catch (e) { } catch (e) {
throw e; throw e;
} finally { } finally {
@ -542,8 +558,9 @@ var userModule = function () {
} }
try { try {
utility.startTenantFlow(carbonUser); utility.startTenantFlow(carbonUser);
var url = devicemgtProps["httpsURL"] + constants.ADMIN_SERVICE_CONTEXT + "/roles/role?rolename=" + encodeURIComponent(roleName); var url = devicemgtProps["httpsURL"] + constants.ADMIN_SERVICE_CONTEXT + "/roles/" + encodeURIComponent(roleName);
var response = privateMethods.callBackend(url, constants.HTTP_GET); var response = privateMethods.callBackend(url, constants["HTTP_GET"]);
response.content = parse(response.content);
return response; return response;
} catch (e) { } catch (e) {
throw e; throw e;
@ -683,6 +700,9 @@ var userModule = function () {
if (publicMethods.isAuthorized("/permission/admin/device-mgt/admin/platform-configs/view")) { if (publicMethods.isAuthorized("/permission/admin/device-mgt/admin/platform-configs/view")) {
permissions["TENANT_CONFIGURATION"] = true; permissions["TENANT_CONFIGURATION"] = true;
} }
if (publicMethods.isAuthorized("/permission/admin/device-mgt/user/devices/list")) {
permissions["LIST_OWN_DEVICES"] = true;
}
return permissions; return permissions;
}; };

Loading…
Cancel
Save