This commit is contained in:
amalka.subasinghe 2023-10-24 15:59:12 +05:30
commit f285628994
1538 changed files with 1981 additions and 277119 deletions

View File

@ -19,23 +19,18 @@
package io.entgra.device.mgt.core.apimgt.extension.rest.api;
import io.entgra.device.mgt.core.apimgt.extension.rest.api.dto.APIApplicationKey;
import io.entgra.device.mgt.core.apimgt.extension.rest.api.dto.APIInfo.*;
import io.entgra.device.mgt.core.apimgt.extension.rest.api.dto.AccessTokenInfo;
import io.entgra.device.mgt.core.apimgt.extension.rest.api.exceptions.APIServicesException;
import io.entgra.device.mgt.core.apimgt.extension.rest.api.exceptions.BadRequestException;
import io.entgra.device.mgt.core.apimgt.extension.rest.api.exceptions.UnexpectedResponseException;
import io.entgra.device.mgt.core.apimgt.extension.rest.api.dto.APIInfo.APIInfo;
import io.entgra.device.mgt.core.apimgt.extension.rest.api.dto.APIInfo.Scope;
import io.entgra.device.mgt.core.apimgt.extension.rest.api.dto.APIInfo.Mediation;
import io.entgra.device.mgt.core.apimgt.extension.rest.api.dto.APIInfo.Documentation;
import io.entgra.device.mgt.core.apimgt.extension.rest.api.dto.APIInfo.APIRevision;
import io.entgra.device.mgt.core.apimgt.extension.rest.api.dto.APIInfo.APIRevisionDeployment;
import org.json.JSONObject;
import java.util.List;
public interface PublisherRESTAPIServices {
JSONObject getScopes(APIApplicationKey apiApplicationKey, AccessTokenInfo accessTokenInfo)
Scope[] getScopes(APIApplicationKey apiApplicationKey, AccessTokenInfo accessTokenInfo)
throws APIServicesException, BadRequestException, UnexpectedResponseException;
boolean isSharedScopeNameExists(APIApplicationKey apiApplicationKey, AccessTokenInfo accessTokenInfo, String key)
@ -47,13 +42,13 @@ public interface PublisherRESTAPIServices {
boolean updateSharedScope(APIApplicationKey apiApplicationKey, AccessTokenInfo accessTokenInfo, Scope scope)
throws APIServicesException, BadRequestException, UnexpectedResponseException;
JSONObject getApi(APIApplicationKey apiApplicationKey, AccessTokenInfo accessTokenInfo, String apiUuid)
APIInfo getApi(APIApplicationKey apiApplicationKey, AccessTokenInfo accessTokenInfo, String apiUuid)
throws APIServicesException, BadRequestException, UnexpectedResponseException;
JSONObject getApis(APIApplicationKey apiApplicationKey, AccessTokenInfo accessTokenInfo)
APIInfo[] getApis(APIApplicationKey apiApplicationKey, AccessTokenInfo accessTokenInfo)
throws APIServicesException, BadRequestException, UnexpectedResponseException;
JSONObject addAPI(APIApplicationKey apiApplicationKey, AccessTokenInfo accessTokenInfo, APIInfo api)
APIInfo addAPI(APIApplicationKey apiApplicationKey, AccessTokenInfo accessTokenInfo, APIInfo api)
throws APIServicesException, BadRequestException, UnexpectedResponseException;
boolean updateApi(APIApplicationKey apiApplicationKey, AccessTokenInfo accessTokenInfo, APIInfo api)
@ -63,7 +58,7 @@ public interface PublisherRESTAPIServices {
String asyncApiDefinition)
throws APIServicesException, BadRequestException, UnexpectedResponseException;
JSONObject getAllApiSpecificMediationPolicies(APIApplicationKey apiApplicationKey, AccessTokenInfo accessTokenInfo,
MediationPolicy[] getAllApiSpecificMediationPolicies(APIApplicationKey apiApplicationKey, AccessTokenInfo accessTokenInfo,
String apiUuid)
throws APIServicesException, BadRequestException, UnexpectedResponseException;
@ -79,11 +74,11 @@ public interface PublisherRESTAPIServices {
String uuid, String action)
throws APIServicesException, BadRequestException, UnexpectedResponseException;
JSONObject getAPIRevisions(APIApplicationKey apiApplicationKey, AccessTokenInfo accessTokenInfo, String uuid,
APIRevision[] getAPIRevisions(APIApplicationKey apiApplicationKey, AccessTokenInfo accessTokenInfo, String uuid,
Boolean deploymentStatus)
throws APIServicesException, BadRequestException, UnexpectedResponseException;
JSONObject addAPIRevision(APIApplicationKey apiApplicationKey, AccessTokenInfo accessTokenInfo,
APIRevision addAPIRevision(APIApplicationKey apiApplicationKey, AccessTokenInfo accessTokenInfo,
APIRevision apiRevision)
throws APIServicesException, BadRequestException, UnexpectedResponseException;
@ -91,15 +86,15 @@ public interface PublisherRESTAPIServices {
String apiRevisionId, List<APIRevisionDeployment> apiRevisionDeploymentList)
throws APIServicesException, BadRequestException, UnexpectedResponseException;
abstract boolean undeployAPIRevisionDeployment(APIApplicationKey apiApplicationKey, AccessTokenInfo accessTokenInfo,
JSONObject apiRevisionDeployment, String uuid)
boolean undeployAPIRevisionDeployment(APIApplicationKey apiApplicationKey, AccessTokenInfo accessTokenInfo,
APIRevision apiRevisionDeployment, String uuid)
throws APIServicesException, BadRequestException, UnexpectedResponseException;
boolean deleteAPIRevision(APIApplicationKey apiApplicationKey, AccessTokenInfo accessTokenInfo,
JSONObject apiRevision, String uuid)
APIRevision apiRevision, String uuid)
throws APIServicesException, BadRequestException, UnexpectedResponseException;
JSONObject getDocumentations(APIApplicationKey apiApplicationKey, AccessTokenInfo accessTokenInfo,
Documentation[] getDocumentations(APIApplicationKey apiApplicationKey, AccessTokenInfo accessTokenInfo,
String uuid)
throws APIServicesException, BadRequestException, UnexpectedResponseException;
@ -107,7 +102,7 @@ public interface PublisherRESTAPIServices {
String uuid, String documentID)
throws APIServicesException, BadRequestException, UnexpectedResponseException;
io.entgra.device.mgt.core.apimgt.extension.rest.api.dto.APIInfo.Documentation addDocumentation(APIApplicationKey apiApplicationKey, AccessTokenInfo accessTokenInfo,
Documentation addDocumentation(APIApplicationKey apiApplicationKey, AccessTokenInfo accessTokenInfo,
String uuid, Documentation documentation)
throws APIServicesException, BadRequestException, UnexpectedResponseException;

View File

@ -21,18 +21,12 @@ package io.entgra.device.mgt.core.apimgt.extension.rest.api;
import com.google.gson.Gson;
import io.entgra.device.mgt.core.apimgt.extension.rest.api.constants.Constants;
import io.entgra.device.mgt.core.apimgt.extension.rest.api.dto.APIApplicationKey;
import io.entgra.device.mgt.core.apimgt.extension.rest.api.dto.APIInfo.APIInfo;
import io.entgra.device.mgt.core.apimgt.extension.rest.api.dto.APIInfo.Scope;
import io.entgra.device.mgt.core.apimgt.extension.rest.api.dto.APIInfo.Mediation;
import io.entgra.device.mgt.core.apimgt.extension.rest.api.dto.APIInfo.Documentation;
import io.entgra.device.mgt.core.apimgt.extension.rest.api.dto.APIInfo.APIRevision;
import io.entgra.device.mgt.core.apimgt.extension.rest.api.dto.APIInfo.APIRevisionDeployment;
import io.entgra.device.mgt.core.apimgt.extension.rest.api.dto.APIInfo.*;
import io.entgra.device.mgt.core.apimgt.extension.rest.api.dto.AccessTokenInfo;
import io.entgra.device.mgt.core.apimgt.extension.rest.api.exceptions.APIServicesException;
import io.entgra.device.mgt.core.apimgt.extension.rest.api.exceptions.BadRequestException;
import io.entgra.device.mgt.core.apimgt.extension.rest.api.exceptions.UnexpectedResponseException;
import io.entgra.device.mgt.core.apimgt.extension.rest.api.util.HttpsTrustManagerUtils;
import io.entgra.device.mgt.core.apimgt.extension.rest.api.util.ScopeUtils;
import okhttp3.*;
import okhttp3.Request.Builder;
import org.apache.commons.httpclient.HttpStatus;
@ -56,7 +50,7 @@ public class PublisherRESTAPIServicesImpl implements PublisherRESTAPIServices {
+ Constants.COLON + port;
@Override
public JSONObject getScopes(APIApplicationKey apiApplicationKey, AccessTokenInfo accessTokenInfo)
public Scope[] getScopes(APIApplicationKey apiApplicationKey, AccessTokenInfo accessTokenInfo)
throws APIServicesException, BadRequestException, UnexpectedResponseException {
String getAllScopesUrl = endPointPrefix + Constants.GET_ALL_SCOPES;
@ -70,8 +64,8 @@ public class PublisherRESTAPIServicesImpl implements PublisherRESTAPIServices {
try {
Response response = client.newCall(request).execute();
if (HttpStatus.SC_OK == response.code()) {
JSONObject jsonObject = new JSONObject(response.body().string());
return jsonObject;
JSONArray scopeList = (JSONArray) new JSONObject(response.body().string()).get("list");
return gson.fromJson(scopeList.toString(), Scope[].class);
} else if (HttpStatus.SC_UNAUTHORIZED == response.code()) {
APIApplicationServices apiApplicationServices = new APIApplicationServicesImpl();
AccessTokenInfo refreshedAccessToken = apiApplicationServices.
@ -124,7 +118,7 @@ public class PublisherRESTAPIServicesImpl implements PublisherRESTAPIServices {
log.error(msg);
throw new BadRequestException(msg);
} else if (HttpStatus.SC_NOT_FOUND == response.code()) {
String msg = "Shared scope key not found";
String msg = "Shared scope key not found : " + key;
log.info(msg);
return false;
} else {
@ -144,14 +138,21 @@ public class PublisherRESTAPIServicesImpl implements PublisherRESTAPIServices {
String addNewSharedScopeEndPoint = endPointPrefix + Constants.SCOPE_API_ENDPOINT;
ScopeUtils scopeUtil = new ScopeUtils();
scopeUtil.setKey(scope.getKey());
scopeUtil.setName(scope.getName());
scopeUtil.setDescription(scope.getDescription());
scopeUtil.setRoles(scope.getRoles());
String scopeString = scopeUtil.toJSON();
JSONArray bindings = new JSONArray();
if (scope.getBindings() != null) {
for (String str : scope.getBindings()) {
bindings.put(str);
}
}
RequestBody requestBody = RequestBody.create(JSON, scopeString);
JSONObject payload = new JSONObject();
payload.put("name", (scope.getName() != null ? scope.getName() : ""));
payload.put("displayName", (scope.getDisplayName() != null ? scope.getDisplayName() : ""));
payload.put("description", (scope.getDescription() != null ? scope.getDescription() : ""));
payload.put("bindings", (bindings != null ? bindings : ""));
payload.put("usageCount", (scope.getUsageCount() != 0 ? scope.getUsageCount() : 0));
RequestBody requestBody = RequestBody.create(JSON, payload.toString());
Request request = new Request.Builder()
.url(addNewSharedScopeEndPoint)
.addHeader(Constants.AUTHORIZATION_HEADER_NAME, Constants.AUTHORIZATION_HEADER_PREFIX_BEARER
@ -191,14 +192,21 @@ public class PublisherRESTAPIServicesImpl implements PublisherRESTAPIServices {
String updateScopeUrl = endPointPrefix + Constants.SCOPE_API_ENDPOINT + scope.getId();
ScopeUtils scopeUtil = new ScopeUtils();
scopeUtil.setKey(scope.getKey());
scopeUtil.setName(scope.getName());
scopeUtil.setDescription(scope.getDescription());
scopeUtil.setRoles(scope.getRoles());
String scopeString = scopeUtil.toJSON();
JSONArray bindings = new JSONArray();
if (scope.getBindings() != null) {
for (String str : scope.getBindings()) {
bindings.put(str);
}
}
RequestBody requestBody = RequestBody.create(JSON, scopeString);
JSONObject payload = new JSONObject();
payload.put("name", (scope.getName() != null ? scope.getName() : ""));
payload.put("displayName", (scope.getDisplayName() != null ? scope.getDisplayName() : ""));
payload.put("description", (scope.getDescription() != null ? scope.getDescription() : ""));
payload.put("bindings", (bindings != null ? bindings : ""));
payload.put("usageCount", (scope.getUsageCount() != 0 ? scope.getUsageCount() : 0));
RequestBody requestBody = RequestBody.create(JSON, payload.toString());
Request request = new Request.Builder()
.url(updateScopeUrl)
.addHeader(Constants.AUTHORIZATION_HEADER_NAME, Constants.AUTHORIZATION_HEADER_PREFIX_BEARER
@ -233,7 +241,7 @@ public class PublisherRESTAPIServicesImpl implements PublisherRESTAPIServices {
}
@Override
public JSONObject getApi(APIApplicationKey apiApplicationKey, AccessTokenInfo accessTokenInfo, String apiUuid)
public APIInfo getApi(APIApplicationKey apiApplicationKey, AccessTokenInfo accessTokenInfo, String apiUuid)
throws APIServicesException, BadRequestException, UnexpectedResponseException {
String getAllApi = endPointPrefix + Constants.API_ENDPOINT + apiUuid;
@ -247,8 +255,7 @@ public class PublisherRESTAPIServicesImpl implements PublisherRESTAPIServices {
try {
Response response = client.newCall(request).execute();
if (HttpStatus.SC_OK == response.code()) {
JSONObject jsonObject = new JSONObject(response.body().string());
return jsonObject;
return gson.fromJson(response.body().string(), APIInfo.class);
} else if (HttpStatus.SC_UNAUTHORIZED == response.code()) {
APIApplicationServices apiApplicationServices = new APIApplicationServicesImpl();
AccessTokenInfo refreshedAccessToken = apiApplicationServices.
@ -272,7 +279,7 @@ public class PublisherRESTAPIServicesImpl implements PublisherRESTAPIServices {
}
@Override
public JSONObject getApis(APIApplicationKey apiApplicationKey, AccessTokenInfo accessTokenInfo)
public APIInfo[] getApis(APIApplicationKey apiApplicationKey, AccessTokenInfo accessTokenInfo)
throws APIServicesException, BadRequestException, UnexpectedResponseException {
String getAllApis = endPointPrefix + Constants.GET_ALL_APIS;
@ -286,8 +293,8 @@ public class PublisherRESTAPIServicesImpl implements PublisherRESTAPIServices {
try {
Response response = client.newCall(request).execute();
if (HttpStatus.SC_OK == response.code()) {
JSONObject jsonObject = new JSONObject(response.body().string());
return jsonObject;
JSONArray apiList = (JSONArray) new JSONObject(response.body().string()).get("list");
return gson.fromJson(apiList.toString(), APIInfo[].class);
} else if (HttpStatus.SC_UNAUTHORIZED == response.code()) {
APIApplicationServices apiApplicationServices = new APIApplicationServicesImpl();
AccessTokenInfo refreshedAccessToken = apiApplicationServices.
@ -311,59 +318,111 @@ public class PublisherRESTAPIServicesImpl implements PublisherRESTAPIServices {
}
@Override
public JSONObject addAPI(APIApplicationKey apiApplicationKey, AccessTokenInfo accessTokenInfo, APIInfo api)
public APIInfo addAPI(APIApplicationKey apiApplicationKey, AccessTokenInfo accessTokenInfo, APIInfo api)
throws APIServicesException, BadRequestException, UnexpectedResponseException {
String addAPIEndPoint = endPointPrefix + Constants.API_ENDPOINT;
String apiString = "{\n" +
" \"name\": \"" + api.getName() + "\",\n" +
" \"description\":\"" + api.getDescription() + "\",\n" +
" \"context\":\"" + api.getContext() + "\",\n" +
" \"version\":\"" + api.getVersion() + "\",\n" +
" \"provider\":\"" + api.getProvider() + "\",\n" +
" \"lifeCycleStatus\":\"" + api.getLifeCycleStatus() + "\",\n" +
" \"wsdlInfo\": " + api.getWsdlInfo() + ",\n" +
" \"wsdlUrl\":" + api.getWsdlUrl() + ",\n" +
" \"responseCachingEnabled\": " + api.isResponseCachingEnabled() + ",\n" +
" \"cacheTimeout\": " + api.getCacheTimeout() + ",\n" +
" \"hasThumbnail\": " + api.isHasThumbnail() + ",\n" +
" \"isDefaultVersion\": " + api.isDefaultVersion() + ",\n" +
" \"isRevision\": " + api.isRevision() + ",\n" +
" \"revisionedApiId\": " + api.getRevisionedApiId() + ",\n" +
" \"revisionId\": " + api.getRevisionId() + ",\n" +
" \"enableSchemaValidation\": " + api.isEnableSchemaValidation() + ",\n" +
" \"type\": \"" + api.getType() + "\",\n" +
" \"transport\": " + gson.toJson(api.getTransport()) + ",\n" +
" \"tags\": " + gson.toJson(api.getTags()) + ",\n" +
" \"policies\": " + gson.toJson(api.getPolicies()) + ",\n" +
" \"apiThrottlingPolicy\": " + api.getApiThrottlingPolicy() + ",\n" +
" \"authorizationHeader\": \"" + api.getAuthorizationHeader() + "\",\n" +
" \"visibility\": \"" + api.getVisibility() + "\",\n" +
" \"mediationPolicies\": " + (api.getInSequence() != null ? "[{\"name\": \"" + api.getInSequence() + "\",\"type\": \"in\"}]" : null) + ",\n" +
" \"subscriptionAvailability\": \"" + api.getSubscriptionAvailability() + "\",\n" +
" \"subscriptionAvailableTenants\": [],\n" +
" \"additionalProperties\": [],\n" +
" \"monetization\": " + api.getMonetization() + ",\n" +
" \"corsConfiguration\": " + gson.toJson(api.getCorsConfiguration()) + ",\n" +
" \"websubSubscriptionConfiguration\": {\n" +
" \"enable\": false,\n" +
" \"secret\": \"\",\n" +
" \"signingAlgorithm\": \"SHA1\",\n" +
" \"signatureHeader\": \"x-hub-signature\"\n" +
" },\n" +
" \"workflowStatus\": null,\n" +
" \"endpointConfig\": " + api.getEndpointConfig().toString() + ",\n" +
" \"endpointImplementationType\": \"ENDPOINT\",\n" +
" \"scopes\": " + api.getScopes().toString() + ",\n" +
" \"operations\": " + (api.getOperations() != null ? api.getOperations().toString() : null) + ",\n" +
" \"threatProtectionPolicies\": null,\n" +
" \"categories\": [],\n" +
" \"keyManagers\": " + gson.toJson(api.getKeyManagers()) + ",\n" +
" \"serviceInfo\": " + api.getServiceInfo() + "\n" +
"}";
JSONObject payload = new JSONObject();
payload.put("name", api.getName());
payload.put("description", api.getDescription());
payload.put("context", api.getContext());
payload.put("version", api.getVersion());
payload.put("provider", api.getProvider());
payload.put("lifeCycleStatus", api.getLifeCycleStatus());
payload.put("wsdlInfo", (api.getWsdlInfo() != null ? api.getWsdlInfo() : null));
payload.put("wsdlUrl", (api.getWsdlUrl() != null ? api.getWsdlUrl() : null));
payload.put("responseCachingEnabled", api.isResponseCachingEnabled());
payload.put("cacheTimeout", api.getCacheTimeout());
payload.put("hasThumbnail", api.isHasThumbnail());
payload.put("isDefaultVersion", api.isDefaultVersion());
payload.put("isRevision", api.isRevision());
payload.put("revisionedApiId", (api.getRevisionedApiId() != null ? api.getRevisionedApiId() : null));
payload.put("revisionId", api.getRevisionId());
payload.put("enableSchemaValidation", api.isEnableSchemaValidation());
payload.put("type", api.getType());
payload.put("apiThrottlingPolicy", api.getApiThrottlingPolicy());
payload.put("authorizationHeader", api.getAuthorizationHeader());
payload.put("visibility", api.getVisibility());
payload.put("subscriptionAvailability", (api.getSubscriptionAvailability() != null ? api.getSubscriptionAvailability() : ""));
RequestBody requestBody = RequestBody.create(JSON, apiString);
//Lists
if (api.getTransport() != null) {
JSONArray transport = new JSONArray();
for (String str : api.getTransport()) {
transport.put(str);
}
payload.put("transport", transport);
}
if (api.getTags() != null) {
JSONArray tags = new JSONArray();
for (String str : api.getTags()) {
tags.put(str);
}
payload.put("tags", tags);
}
if (api.getPolicies() != null) {
JSONArray policies = new JSONArray();
for (String str : api.getPolicies()) {
policies.put(str);
}
payload.put("policies", policies);
}
if (api.getMediationPolicies() != null) {
JSONArray mediationPolicies = new JSONArray();
for (MediationPolicy object : api.getMediationPolicies()) {
mediationPolicies.put(new JSONObject(gson.toJson(object)));
}
payload.put("mediationPolicies", mediationPolicies);
}
if (api.getSubscriptionAvailableTenants() != null) {
JSONArray subscriptionAvailableTenants = new JSONArray();
for (String str : api.getSubscriptionAvailableTenants()) {
subscriptionAvailableTenants.put(str);
}
payload.put("subscriptionAvailableTenants", subscriptionAvailableTenants);
}
if (api.getAdditionalProperties() != null) {
JSONArray additionalProperties = new JSONArray();
for (AdditionalProperties str : api.getAdditionalProperties()) {
additionalProperties.put(str);
}
payload.put("additionalProperties", additionalProperties);
}
if (api.getScopes() != null) {
JSONArray scopes = new JSONArray();
for (JSONObject object : api.getScopes()) {
scopes.put(object);
}
payload.put("scopes", scopes);
}
if (api.getOperations() != null) {
JSONArray operations = new JSONArray();
for (Operations operation : api.getOperations()) {
operations.put(new JSONObject(gson.toJson(operation)));
}
payload.put("operations", operations);
}
if (api.getCategories() != null) {
JSONArray categories = new JSONArray();
for (String str : api.getCategories()) {
categories.put(str);
}
payload.put("categories", categories);
}
//objects
payload.put("monetization", (api.getMonetization() != null ? new JSONObject(gson.toJson(api.getMonetization())) : null));
payload.put("corsConfiguration", (api.getCorsConfiguration() != null ? new JSONObject(gson.toJson(api.getCorsConfiguration())) : null));
payload.put("websubSubscriptionConfiguration", (api.getWebsubSubscriptionConfiguration() != null ? new JSONObject(gson.toJson(api.getWebsubSubscriptionConfiguration())) : null));
payload.put("workflowStatus", (api.getWorkflowStatus() != null ? api.getWorkflowStatus() : null));
payload.put("endpointConfig", (api.getEndpointConfig() != null ? api.getEndpointConfig() : null));
payload.put("endpointImplementationType", (api.getEndpointImplementationType() != null ? api.getEndpointImplementationType() : null));
payload.put("threatProtectionPolicies", (api.getThreatProtectionPolicies() != null ? api.getThreatProtectionPolicies() : null));
payload.put("serviceInfo", (api.getServiceInfo() != null ? new JSONObject(gson.toJson(api.getServiceInfo())) : null));
payload.put("advertiseInfo", (api.getAdvertiseInfo() != null ? new JSONObject(gson.toJson(api.getAdvertiseInfo())) : null));
RequestBody requestBody = RequestBody.create(JSON, payload.toString());
Request request = new Request.Builder()
.url(addAPIEndPoint)
.addHeader(Constants.AUTHORIZATION_HEADER_NAME, Constants.AUTHORIZATION_HEADER_PREFIX_BEARER
@ -374,8 +433,7 @@ public class PublisherRESTAPIServicesImpl implements PublisherRESTAPIServices {
try {
Response response = client.newCall(request).execute();
if (HttpStatus.SC_CREATED == response.code()) {
JSONObject jsonObject = new JSONObject(response.body().string());
return jsonObject;
return gson.fromJson(response.body().string(), APIInfo.class);
} else if (HttpStatus.SC_UNAUTHORIZED == response.code()) {
APIApplicationServices apiApplicationServices = new APIApplicationServicesImpl();
AccessTokenInfo refreshedAccessToken = apiApplicationServices.
@ -404,54 +462,106 @@ public class PublisherRESTAPIServicesImpl implements PublisherRESTAPIServices {
String updateAPIEndPoint = endPointPrefix + Constants.API_ENDPOINT + api.getId();
String apiString = "{\n" +
" \"name\": \"" + api.getName() + "\",\n" +
" \"description\":\"" + api.getDescription() + "\",\n" +
" \"context\":\"" + api.getContext() + "\",\n" +
" \"version\":\"" + api.getVersion() + "\",\n" +
" \"provider\":\"" + api.getProvider() + "\",\n" +
" \"lifeCycleStatus\":\"" + api.getLifeCycleStatus() + "\",\n" +
" \"wsdlInfo\": " + api.getWsdlInfo() + ",\n" +
" \"wsdlUrl\":" + api.getWsdlUrl() + ",\n" +
" \"responseCachingEnabled\": " + api.isResponseCachingEnabled() + ",\n" +
" \"cacheTimeout\": " + api.getCacheTimeout() + ",\n" +
" \"hasThumbnail\": " + api.isHasThumbnail() + ",\n" +
" \"isDefaultVersion\": " + api.isDefaultVersion() + ",\n" +
" \"isRevision\": " + api.isRevision() + ",\n" +
" \"revisionedApiId\": " + api.getRevisionedApiId() + ",\n" +
" \"revisionId\": " + api.getRevisionId() + ",\n" +
" \"enableSchemaValidation\": " + api.isEnableSchemaValidation() + ",\n" +
" \"type\": \"" + api.getType() + "\",\n" +
" \"transport\": " + gson.toJson(api.getTransport()) + ",\n" +
" \"tags\": " + gson.toJson(api.getTags()) + ",\n" +
" \"policies\": " + gson.toJson(api.getPolicies()) + ",\n" +
" \"apiThrottlingPolicy\": " + api.getApiThrottlingPolicy() + ",\n" +
" \"authorizationHeader\": \"" + api.getAuthorizationHeader() + "\",\n" +
" \"visibility\": \"" + api.getVisibility() + "\",\n" +
" \"mediationPolicies\": " + (api.getInSequence() != null ? "[{\"name\": \"" + api.getInSequence() + "\",\"type\": \"in\"}]" : null) + ",\n" +
" \"subscriptionAvailability\": \"" + api.getSubscriptionAvailability() + "\",\n" +
" \"subscriptionAvailableTenants\": [],\n" +
" \"additionalProperties\": [],\n" +
" \"monetization\": " + api.getMonetization() + ",\n" +
" \"corsConfiguration\": " + gson.toJson(api.getCorsConfiguration()) + ",\n" +
" \"websubSubscriptionConfiguration\": {\n" +
" \"enable\": false,\n" +
" \"secret\": \"\",\n" +
" \"signingAlgorithm\": \"SHA1\",\n" +
" \"signatureHeader\": \"x-hub-signature\"\n" +
" },\n" +
" \"workflowStatus\": null,\n" +
" \"endpointConfig\": " + api.getEndpointConfig().toString() + ",\n" +
" \"endpointImplementationType\": \"ENDPOINT\",\n" +
" \"scopes\": " + api.getScopes().toString() + ",\n" +
" \"operations\": " + (api.getOperations() != null? api.getOperations().toString() : null) + ",\n" +
" \"threatProtectionPolicies\": null,\n" +
" \"categories\": [],\n" +
" \"keyManagers\": " + gson.toJson(api.getKeyManagers()) + ",\n" +
" \"serviceInfo\": " + api.getServiceInfo() + "\n" +
"}";
JSONObject payload = new JSONObject();
payload.put("name", api.getName());
payload.put("description", api.getDescription());
payload.put("context", api.getContext());
payload.put("version", api.getVersion());
payload.put("provider", api.getProvider());
payload.put("lifeCycleStatus", api.getLifeCycleStatus());
payload.put("wsdlInfo", (api.getWsdlInfo() != null ? api.getWsdlInfo() : null));
payload.put("wsdlUrl", (api.getWsdlUrl() != null ? api.getWsdlUrl() : null));
payload.put("responseCachingEnabled", api.isResponseCachingEnabled());
payload.put("cacheTimeout", api.getCacheTimeout());
payload.put("hasThumbnail", api.isHasThumbnail());
payload.put("isDefaultVersion", api.isDefaultVersion());
payload.put("isRevision", api.isRevision());
payload.put("revisionedApiId", (api.getRevisionedApiId() != null ? api.getRevisionedApiId() : null));
payload.put("revisionId", api.getRevisionId());
payload.put("enableSchemaValidation", api.isEnableSchemaValidation());
payload.put("type", api.getType());
payload.put("apiThrottlingPolicy", api.getApiThrottlingPolicy());
payload.put("authorizationHeader", api.getAuthorizationHeader());
payload.put("visibility", api.getVisibility());
payload.put("subscriptionAvailability", (api.getSubscriptionAvailability() != null ? api.getSubscriptionAvailability() : ""));
RequestBody requestBody = RequestBody.create(JSON, apiString);
//Lists
if (api.getTransport() != null) {
JSONArray transport = new JSONArray();
for (String str : api.getTransport()) {
transport.put(str);
}
payload.put("transport", transport);
}
if (api.getTags() != null) {
JSONArray tags = new JSONArray();
for (String str : api.getTags()) {
tags.put(str);
}
payload.put("tags", tags);
}
if (api.getPolicies() != null) {
JSONArray policies = new JSONArray();
for (String str : api.getPolicies()) {
policies.put(str);
}
payload.put("policies", policies);
}
if (api.getMediationPolicies() != null) {
JSONArray mediationPolicies = new JSONArray();
for (MediationPolicy object : api.getMediationPolicies()) {
mediationPolicies.put(new JSONObject(gson.toJson(object)));
}
payload.put("mediationPolicies", mediationPolicies);
}
if (api.getSubscriptionAvailableTenants() != null) {
JSONArray subscriptionAvailableTenants = new JSONArray();
for (String str : api.getSubscriptionAvailableTenants()) {
subscriptionAvailableTenants.put(str);
}
payload.put("subscriptionAvailableTenants", subscriptionAvailableTenants);
}
if (api.getAdditionalProperties() != null) {
JSONArray additionalProperties = new JSONArray();
for (AdditionalProperties str : api.getAdditionalProperties()) {
additionalProperties.put(str);
}
payload.put("additionalProperties", additionalProperties);
}
if (api.getScopes() != null) {
JSONArray scopes = new JSONArray();
for (JSONObject object : api.getScopes()) {
scopes.put(object);
}
payload.put("scopes", scopes);
}
if (api.getOperations() != null) {
JSONArray operations = new JSONArray();
for (Operations operation : api.getOperations()) {
operations.put(new JSONObject(gson.toJson(operation)));
}
payload.put("operations", operations);
}
if (api.getCategories() != null) {
JSONArray categories = new JSONArray();
for (String str : api.getCategories()) {
categories.put(str);
}
payload.put("categories", categories);
}
//objects
payload.put("monetization", (api.getMonetization() != null ? new JSONObject(gson.toJson(api.getMonetization())) : null));
payload.put("corsConfiguration", (api.getCorsConfiguration() != null ? new JSONObject(gson.toJson(api.getCorsConfiguration())) : null));
payload.put("websubSubscriptionConfiguration", (api.getWebsubSubscriptionConfiguration() != null ? new JSONObject(gson.toJson(api.getWebsubSubscriptionConfiguration())) : null));
payload.put("workflowStatus", (api.getWorkflowStatus() != null ? api.getWorkflowStatus() : null));
payload.put("endpointConfig", (api.getEndpointConfig() != null ? api.getEndpointConfig() : null));
payload.put("endpointImplementationType", (api.getEndpointImplementationType() != null ? api.getEndpointImplementationType() : null));
payload.put("threatProtectionPolicies", (api.getThreatProtectionPolicies() != null ? api.getThreatProtectionPolicies() : null));
payload.put("serviceInfo", (api.getServiceInfo() != null ? new JSONObject(gson.toJson(api.getServiceInfo())) : null));
payload.put("advertiseInfo", (api.getAdvertiseInfo() != null ? new JSONObject(gson.toJson(api.getAdvertiseInfo())) : null));
RequestBody requestBody = RequestBody.create(JSON, payload.toString());
Request request = new Request.Builder()
.url(updateAPIEndPoint)
.addHeader(Constants.AUTHORIZATION_HEADER_NAME, Constants.AUTHORIZATION_HEADER_PREFIX_BEARER
@ -463,7 +573,6 @@ public class PublisherRESTAPIServicesImpl implements PublisherRESTAPIServices {
Response response = client.newCall(request).execute();
if (HttpStatus.SC_OK == response.code()) {
return true;
} else if (HttpStatus.SC_UNAUTHORIZED == response.code()) {
APIApplicationServices apiApplicationServices = new APIApplicationServicesImpl();
AccessTokenInfo refreshedAccessToken = apiApplicationServices.
@ -534,7 +643,7 @@ public class PublisherRESTAPIServicesImpl implements PublisherRESTAPIServices {
}
@Override
public JSONObject getAllApiSpecificMediationPolicies(APIApplicationKey apiApplicationKey, AccessTokenInfo accessTokenInfo,
public MediationPolicy[] getAllApiSpecificMediationPolicies(APIApplicationKey apiApplicationKey, AccessTokenInfo accessTokenInfo,
String apiUuid)
throws APIServicesException, BadRequestException, UnexpectedResponseException {
@ -549,8 +658,8 @@ public class PublisherRESTAPIServicesImpl implements PublisherRESTAPIServices {
try {
Response response = client.newCall(request).execute();
if (HttpStatus.SC_OK == response.code()) {
JSONObject jsonObject = new JSONObject(response.body().string());
return jsonObject;
JSONArray mediationPolicyList = (JSONArray) new JSONObject(response.body().string()).get("list");
return gson.fromJson(mediationPolicyList.toString(), MediationPolicy[].class);
} else if (HttpStatus.SC_UNAUTHORIZED == response.code()) {
APIApplicationServices apiApplicationServices = new APIApplicationServicesImpl();
AccessTokenInfo refreshedAccessToken = apiApplicationServices.
@ -705,7 +814,7 @@ public class PublisherRESTAPIServicesImpl implements PublisherRESTAPIServices {
}
@Override
public JSONObject getAPIRevisions(APIApplicationKey apiApplicationKey, AccessTokenInfo accessTokenInfo, String uuid,
public APIRevision[] getAPIRevisions(APIApplicationKey apiApplicationKey, AccessTokenInfo accessTokenInfo, String uuid,
Boolean deploymentStatus)
throws APIServicesException, BadRequestException, UnexpectedResponseException {
@ -722,8 +831,8 @@ public class PublisherRESTAPIServicesImpl implements PublisherRESTAPIServices {
try {
Response response = client.newCall(request).execute();
if (HttpStatus.SC_OK == response.code()) {
JSONObject jsonObject = new JSONObject(response.body().string());
return jsonObject;
JSONArray revisionList = (JSONArray) new JSONObject(response.body().string()).get("list");
return gson.fromJson(revisionList.toString(), APIRevision[].class);
} else if (HttpStatus.SC_UNAUTHORIZED == response.code()) {
APIApplicationServices apiApplicationServices = new APIApplicationServicesImpl();
AccessTokenInfo refreshedAccessToken = apiApplicationServices.
@ -747,16 +856,15 @@ public class PublisherRESTAPIServicesImpl implements PublisherRESTAPIServices {
}
@Override
public JSONObject addAPIRevision(APIApplicationKey apiApplicationKey, AccessTokenInfo accessTokenInfo, APIRevision apiRevision)
public APIRevision addAPIRevision(APIApplicationKey apiApplicationKey, AccessTokenInfo accessTokenInfo, APIRevision apiRevision)
throws APIServicesException, BadRequestException, UnexpectedResponseException {
String addNewScope = endPointPrefix + Constants.API_ENDPOINT + apiRevision.getApiUUID() + "/revisions";
String apiRevisionDescription = "{\n" +
" \"description\":\"" + apiRevision.getDescription() + "\"\n" +
"}";
JSONObject payload = new JSONObject();
payload.put("description", (apiRevision.getDescription() != null ? apiRevision.getDescription() : null));
RequestBody requestBody = RequestBody.create(JSON, apiRevisionDescription);
RequestBody requestBody = RequestBody.create(JSON, payload.toString());
Request request = new Request.Builder()
.url(addNewScope)
.addHeader(Constants.AUTHORIZATION_HEADER_NAME, Constants.AUTHORIZATION_HEADER_PREFIX_BEARER
@ -767,8 +875,7 @@ public class PublisherRESTAPIServicesImpl implements PublisherRESTAPIServices {
try {
Response response = client.newCall(request).execute();
if (HttpStatus.SC_CREATED == response.code()) {
JSONObject jsonObject = new JSONObject(response.body().string());
return jsonObject;
return gson.fromJson(response.body().string(), APIRevision.class);
} else if (HttpStatus.SC_UNAUTHORIZED == response.code()) {
APIApplicationServices apiApplicationServices = new APIApplicationServicesImpl();
AccessTokenInfo refreshedAccessToken = apiApplicationServices.
@ -799,15 +906,14 @@ public class PublisherRESTAPIServicesImpl implements PublisherRESTAPIServices {
String deployAPIRevisionEndPoint = endPointPrefix + Constants.API_ENDPOINT + uuid + "/deploy-revision?revisionId=" + apiRevisionId;
APIRevisionDeployment apiRevisionDeployment = apiRevisionDeploymentList.get(0);
String revision = "[\n" +
" {\n" +
" \"name\": \"" + apiRevisionDeployment.getDeployment() + "\",\n" +
" \"vhost\": \"" + apiRevisionDeployment.getVhost() + "\",\n" +
" \"displayOnDevportal\": " + apiRevisionDeployment.isDisplayOnDevportal() + "\n" +
" }\n" +
"]";
JSONArray payload = new JSONArray();
JSONObject revision = new JSONObject();
revision.put("name", (apiRevisionDeployment.getName() != null ? apiRevisionDeployment.getName() : ""));
revision.put("vhost", (apiRevisionDeployment.getVhost() != null ? apiRevisionDeployment.getVhost() : ""));
revision.put("displayOnDevportal", apiRevisionDeployment.isDisplayOnDevportal());
payload.put(revision);
RequestBody requestBody = RequestBody.create(JSON, revision);
RequestBody requestBody = RequestBody.create(JSON, payload.toString());
Request request = new Request.Builder()
.url(deployAPIRevisionEndPoint)
.addHeader(Constants.AUTHORIZATION_HEADER_NAME, Constants.AUTHORIZATION_HEADER_PREFIX_BEARER
@ -844,23 +950,22 @@ public class PublisherRESTAPIServicesImpl implements PublisherRESTAPIServices {
@Override
public boolean undeployAPIRevisionDeployment(APIApplicationKey apiApplicationKey, AccessTokenInfo accessTokenInfo,
JSONObject apiRevisionDeployment, String uuid)
APIRevision apiRevisionDeployment, String uuid)
throws APIServicesException, BadRequestException, UnexpectedResponseException {
String undeployAPIRevisionEndPoint = endPointPrefix + Constants.API_ENDPOINT + uuid + "/undeploy-revision?revisionId="
+ apiRevisionDeployment.getString("id");
JSONArray array = apiRevisionDeployment.getJSONArray("deploymentInfo");
JSONObject obj = array.getJSONObject(0);
+ apiRevisionDeployment.getId();
List<APIRevisionDeployment> apiRevisionDeployments = apiRevisionDeployment.getDeploymentInfo();
APIRevisionDeployment earliestDeployment = apiRevisionDeployments.get(0);
String revision = "[\n" +
" {\n" +
" \"name\": \"" + obj.getString("name") + "\",\n" +
" \"vhost\": \"" + obj.getString("vhost") + "\",\n" +
" \"displayOnDevportal\": " + obj.get("displayOnDevportal") + "\n" +
" }\n" +
"]";
JSONArray payload = new JSONArray();
JSONObject revision = new JSONObject();
revision.put("name", (earliestDeployment.getName() != null ? earliestDeployment.getName() : ""));
revision.put("vhost", (earliestDeployment.getVhost() != null ? earliestDeployment.getVhost() : ""));
revision.put("displayOnDevportal", earliestDeployment.isDisplayOnDevportal());
payload.put(revision);
RequestBody requestBody = RequestBody.create(JSON, revision);
RequestBody requestBody = RequestBody.create(JSON, payload.toString());
Request request = new Request.Builder()
.url(undeployAPIRevisionEndPoint)
.addHeader(Constants.AUTHORIZATION_HEADER_NAME, Constants.AUTHORIZATION_HEADER_PREFIX_BEARER
@ -896,11 +1001,11 @@ public class PublisherRESTAPIServicesImpl implements PublisherRESTAPIServices {
@Override
public boolean deleteAPIRevision(APIApplicationKey apiApplicationKey, AccessTokenInfo accessTokenInfo,
JSONObject apiRevision, String uuid)
APIRevision apiRevision, String uuid)
throws APIServicesException, BadRequestException, UnexpectedResponseException {
String apiRevisionEndPoint = endPointPrefix + Constants.API_ENDPOINT + uuid + "/revisions/" +
apiRevision.getString("id");
apiRevision.getId();
Request request = new Request.Builder()
.url(apiRevisionEndPoint)
@ -936,7 +1041,7 @@ public class PublisherRESTAPIServicesImpl implements PublisherRESTAPIServices {
}
@Override
public JSONObject getDocumentations(APIApplicationKey apiApplicationKey, AccessTokenInfo accessTokenInfo, String uuid)
public Documentation[] getDocumentations(APIApplicationKey apiApplicationKey, AccessTokenInfo accessTokenInfo, String uuid)
throws APIServicesException, BadRequestException, UnexpectedResponseException {
String getDocumentationsEndPoint = endPointPrefix + Constants.API_ENDPOINT + uuid + "/documents?limit=1000";
@ -951,8 +1056,8 @@ public class PublisherRESTAPIServicesImpl implements PublisherRESTAPIServices {
try {
Response response = client.newCall(request).execute();
if (HttpStatus.SC_OK == response.code()) {
JSONObject jsonObject = new JSONObject(response.body().string());
return jsonObject;
JSONArray documentList = (JSONArray) new JSONObject(response.body().string()).get("list");
return gson.fromJson(documentList.toString(), Documentation[].class);
} else if (HttpStatus.SC_UNAUTHORIZED == response.code()) {
APIApplicationServices apiApplicationServices = new APIApplicationServicesImpl();
AccessTokenInfo refreshedAccessToken = apiApplicationServices.
@ -1022,17 +1127,16 @@ public class PublisherRESTAPIServicesImpl implements PublisherRESTAPIServices {
String addNewScope = endPointPrefix + Constants.API_ENDPOINT + uuid + "/documents";
String document = "{\n" +
" \"name\": \"" + documentation.getName() + "\",\n" +
" \"type\": \"" + documentation.getType() + "\",\n" +
" \"summary\": \"" + documentation.getSummary() + "\",\n" +
" \"sourceType\": \"" + documentation.getSourceType() + "\",\n" +
" \"inlineContent\": \"" + documentation.getSourceType() + "\",\n" +
" \"visibility\": \"" + documentation.getVisibility() + "\",\n" +
" \"createdBy\": \"admin\"\n" +
"}";
JSONObject payload = new JSONObject();
payload.put("name", documentation.getName());
payload.put("type", documentation.getType());
payload.put("summary", documentation.getSummary());
payload.put("sourceType", documentation.getSourceType());
payload.put("inlineContent", documentation.getSourceType());
payload.put("visibility", documentation.getVisibility());
payload.put("createdBy", documentation.getCreatedBy());
RequestBody requestBody = RequestBody.create(JSON, document);
RequestBody requestBody = RequestBody.create(JSON, payload.toString());
Request request = new Request.Builder()
.url(addNewScope)
.addHeader(Constants.HEADER_CONTENT_TYPE, Constants.APPLICATION_JSON)

View File

@ -20,7 +20,7 @@ package io.entgra.device.mgt.core.apimgt.extension.rest.api.dto.APIInfo;
import org.json.JSONObject;
import java.util.*;
import java.util.List;
/**
* This class represents the API response.
@ -35,7 +35,7 @@ public class APIInfo {
private String version;
private String provider;
private String lifeCycleStatus;
private String wsdlInfo;
private type wsdlInfo;
private String wsdlUrl;
private boolean responseCachingEnabled;
private int cacheTimeout;
@ -45,59 +45,65 @@ public class APIInfo {
private String revisionedApiId;
private int revisionId;
private boolean enableSchemaValidation;
private boolean enableStore;
private String type;
private Set<String> transport;
private Set<String> tags;
private Set<String> policies;
private List<String> transport;
private List<String> tags;
private List<String> policies;
private String apiThrottlingPolicy;
private String authorizationHeader;
private String securityScheme;
private String maxTps;
private List<String> securityScheme;
private APIMaxTps maxTps;
private String visibility;
private String visibleRoles;
private String visibleTenants;
private String mediationPolicies;
private List<String> visibleRoles;
private List<String> visibleTenants;
private List<MediationPolicy> mediationPolicies;
private String subscriptionAvailability;
private String subscriptionAvailableTenants;
private String additionalProperties;
private String monetization;
private List<String> subscriptionAvailableTenants;
private List<AdditionalProperties> additionalProperties;
private Monetization monetization;
private String accessControl;
private String accessControlRoles;
private List<String> accessControlRoles;
private BusinessInformation businessInformation;
private CORSConfiguration corsConfiguration;
private WebsubSubscriptionConfiguration websubSubscriptionConfiguration;
private String workflowStatus;
private String createdTime;
private String lastUpdatedTime;
private JSONObject endpointConfig = new JSONObject();
private JSONObject endpointConfig;
private String endpointImplementationType;
private List<JSONObject> scopes = new ArrayList();
private List<JSONObject> operations;
private String threatProtectionPolicies;
private List<String> keyManagers = new ArrayList();
private JSONObject serviceInfo = new JSONObject();
private List<JSONObject> scopes;
private List<Operations> operations;
private JSONObject threatProtectionPolicies;
private List<String> categories;
private List<String> keyManagers;
private ServiceInfo serviceInfo;
private AdvertiseInfo advertiseInfo;
private String asyncApiDefinition;
public enum type {
WSDL, ZIP
}
private Set<URITemplate> uriTemplates = new LinkedHashSet<URITemplate>();
private String inSequence;
private Map<String, String> wsUriMapping;
public String getId() {
return id;
}
public void setId(String id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getDescription() {
return description;
}
public void setDescription(String description) {
this.description = description;
}
@ -109,12 +115,15 @@ public class APIInfo {
public void setContext(String context) {
this.context = context;
}
public String getVersion() {
return version;
}
public void setVersion(String version) {
this.version = version;
}
public String getProvider() {
return provider;
}
@ -131,11 +140,11 @@ public class APIInfo {
this.lifeCycleStatus = lifeCycleStatus;
}
public String getWsdlInfo() {
public APIInfo.type getWsdlInfo() {
return wsdlInfo;
}
public void setWsdlInfo(String wsdlInfo) {
public void setWsdlInfo(APIInfo.type wsdlInfo) {
this.wsdlInfo = wsdlInfo;
}
@ -211,6 +220,14 @@ public class APIInfo {
this.enableSchemaValidation = enableSchemaValidation;
}
public boolean isEnableStore() {
return enableStore;
}
public void setEnableStore(boolean enableStore) {
this.enableStore = enableStore;
}
public String getType() {
return type;
}
@ -219,27 +236,27 @@ public class APIInfo {
this.type = type;
}
public Set<String> getTransport() {
public List<String> getTransport() {
return transport;
}
public void setTransport(Set<String> transport) {
public void setTransport(List<String> transport) {
this.transport = transport;
}
public Set<String> getTags() {
public List<String> getTags() {
return tags;
}
public void setTags(Set<String> tags) {
public void setTags(List<String> tags) {
this.tags = tags;
}
public Set<String> getPolicies() {
public List<String> getPolicies() {
return policies;
}
public void setPolicies(Set<String> policies) {
public void setPolicies(List<String> policies) {
this.policies = policies;
}
@ -259,19 +276,19 @@ public class APIInfo {
this.authorizationHeader = authorizationHeader;
}
public String getSecurityScheme() {
public List<String> getSecurityScheme() {
return securityScheme;
}
public void setSecurityScheme(String securityScheme) {
public void setSecurityScheme(List<String> securityScheme) {
this.securityScheme = securityScheme;
}
public String getMaxTps() {
public APIMaxTps getMaxTps() {
return maxTps;
}
public void setMaxTps(String maxTps) {
public void setMaxTps(APIMaxTps maxTps) {
this.maxTps = maxTps;
}
@ -283,27 +300,27 @@ public class APIInfo {
this.visibility = visibility;
}
public String getVisibleRoles() {
public List<String> getVisibleRoles() {
return visibleRoles;
}
public void setVisibleRoles(String visibleRoles) {
public void setVisibleRoles(List<String> visibleRoles) {
this.visibleRoles = visibleRoles;
}
public String getVisibleTenants() {
public List<String> getVisibleTenants() {
return visibleTenants;
}
public void setVisibleTenants(String visibleTenants) {
public void setVisibleTenants(List<String> visibleTenants) {
this.visibleTenants = visibleTenants;
}
public String getMediationPolicies() {
public List<MediationPolicy> getMediationPolicies() {
return mediationPolicies;
}
public void setMediationPolicies(String mediationPolicies) {
public void setMediationPolicies(List<MediationPolicy> mediationPolicies) {
this.mediationPolicies = mediationPolicies;
}
@ -315,27 +332,27 @@ public class APIInfo {
this.subscriptionAvailability = subscriptionAvailability;
}
public String getSubscriptionAvailableTenants() {
public List<String> getSubscriptionAvailableTenants() {
return subscriptionAvailableTenants;
}
public void setSubscriptionAvailableTenants(String subscriptionAvailableTenants) {
public void setSubscriptionAvailableTenants(List<String> subscriptionAvailableTenants) {
this.subscriptionAvailableTenants = subscriptionAvailableTenants;
}
public String getAdditionalProperties() {
public List<AdditionalProperties> getAdditionalProperties() {
return additionalProperties;
}
public void setAdditionalProperties(String additionalProperties) {
public void setAdditionalProperties(List<AdditionalProperties> additionalProperties) {
this.additionalProperties = additionalProperties;
}
public String getMonetization() {
public Monetization getMonetization() {
return monetization;
}
public void setMonetization(String monetization) {
public void setMonetization(Monetization monetization) {
this.monetization = monetization;
}
@ -347,11 +364,11 @@ public class APIInfo {
this.accessControl = accessControl;
}
public String getAccessControlRoles() {
public List<String> getAccessControlRoles() {
return accessControlRoles;
}
public void setAccessControlRoles(String accessControlRoles) {
public void setAccessControlRoles(List<String> accessControlRoles) {
this.accessControlRoles = accessControlRoles;
}
@ -371,6 +388,14 @@ public class APIInfo {
this.corsConfiguration = corsConfiguration;
}
public WebsubSubscriptionConfiguration getWebsubSubscriptionConfiguration() {
return websubSubscriptionConfiguration;
}
public void setWebsubSubscriptionConfiguration(WebsubSubscriptionConfiguration websubSubscriptionConfiguration) {
this.websubSubscriptionConfiguration = websubSubscriptionConfiguration;
}
public String getWorkflowStatus() {
return workflowStatus;
}
@ -411,7 +436,7 @@ public class APIInfo {
this.endpointImplementationType = endpointImplementationType;
}
public List<JSONObject>getScopes() {
public List<JSONObject> getScopes() {
return scopes;
}
@ -419,22 +444,30 @@ public class APIInfo {
this.scopes = scopes;
}
public List<JSONObject> getOperations() {
public List<Operations> getOperations() {
return operations;
}
public void setOperations(List<JSONObject> operations) {
public void setOperations(List<Operations> operations) {
this.operations = operations;
}
public String getThreatProtectionPolicies() {
public JSONObject getThreatProtectionPolicies() {
return threatProtectionPolicies;
}
public void setThreatProtectionPolicies(String threatProtectionPolicies) {
public void setThreatProtectionPolicies(JSONObject threatProtectionPolicies) {
this.threatProtectionPolicies = threatProtectionPolicies;
}
public List<String> getCategories() {
return categories;
}
public void setCategories(List<String> categories) {
this.categories = categories;
}
public List<String> getKeyManagers() {
return keyManagers;
}
@ -443,11 +476,11 @@ public class APIInfo {
this.keyManagers = keyManagers;
}
public JSONObject getServiceInfo() {
public ServiceInfo getServiceInfo() {
return serviceInfo;
}
public void setServiceInfo(JSONObject serviceInfo) {
public void setServiceInfo(ServiceInfo serviceInfo) {
this.serviceInfo = serviceInfo;
}
@ -458,36 +491,4 @@ public class APIInfo {
public void setAdvertiseInfo(AdvertiseInfo advertiseInfo) {
this.advertiseInfo = advertiseInfo;
}
public String getInSequence() {
return inSequence;
}
public void setInSequence(String inSequence) {
this.inSequence = inSequence;
}
public String getAsyncApiDefinition() {
return asyncApiDefinition;
}
public void setAsyncApiDefinition(String asyncApiDefinition) {
this.asyncApiDefinition = asyncApiDefinition;
}
public Set<URITemplate> getUriTemplates() {
return uriTemplates;
}
public void setUriTemplates(Set<URITemplate> uriTemplates) {
this.uriTemplates = uriTemplates;
}
public Map<String, String> getWsUriMapping() {
return wsUriMapping;
}
public void setWsUriMapping(Map<String, String> wsUriMapping) {
this.wsUriMapping = wsUriMapping;
}
}

View File

@ -15,29 +15,30 @@
* specific language governing permissions and limitations
* under the License.
*/
package io.entgra.device.mgt.core.apimgt.extension.rest.api.dto.APIInfo;
import java.io.Serializable;
public class APIMaxTps implements Serializable {
.dontfloat {
clear:both;
}
.hidden-div {
display: none;
}
.hidden-input {
display: none;
}
.event-wrapper{
margin-top: 10px;
}
.wr-btn-horizontal{
padding: 7px 10px;
}
.wr-btn-secondary{
background-color: #617d8b;
private static final long serialVersionUID = 1L;
int production;
int sandbox;
public int getProduction() {
return production;
}
public void setProduction(int production) {
this.production = production;
}
public int getSandbox() {
return sandbox;
}
public void setSandbox(int sandbox) {
this.sandbox = sandbox;
}
}

View File

@ -17,26 +17,26 @@
*/
package io.entgra.device.mgt.core.apimgt.extension.rest.api.dto.APIInfo;
import org.wso2.carbon.apimgt.api.model.APIRevisionDeployment;
import java.io.Serializable;
import java.util.List;
public class APIRevision implements Serializable {
private static final long serialVersionUID = 1L;
private int id;
private String id;
private String apiUUID;
private String revisionUUID;
private String description;
private String displayName;
private String createdBy;
private String createdTime;
private List<APIRevisionDeployment> apiRevisionDeploymentList;
private APIInfo apiInfo;
private List<APIRevisionDeployment> deploymentInfo;
public int getId() {
public String getId() {
return id;
}
public void setId(int id) {
public void setId(String id) {
this.id = id;
}
@ -80,11 +80,28 @@ public class APIRevision implements Serializable {
this.createdTime = createdTime;
}
public List<APIRevisionDeployment> getApiRevisionDeploymentList() {
return apiRevisionDeploymentList;
public List<APIRevisionDeployment> getDeploymentInfo() {
return deploymentInfo;
}
public void setApiRevisionDeploymentList(List<APIRevisionDeployment> apiRevisionDeploymentList) {
this.apiRevisionDeploymentList = apiRevisionDeploymentList;
public void setDeploymentInfo(List<APIRevisionDeployment> deploymentInfo) {
this.deploymentInfo = deploymentInfo;
}
public String getDisplayName() {
return displayName;
}
public void setDisplayName(String displayName) {
this.displayName = displayName;
}
public APIInfo getApiInfo() {
return apiInfo;
}
public void setApiInfo(APIInfo apiInfo) {
this.apiInfo = apiInfo;
}
}

View File

@ -23,10 +23,10 @@ import java.io.Serializable;
public class APIRevisionDeployment implements Serializable {
private static final long serialVersionUID = 1L;
private int id;
private String revisionUUID;
private String deployment;
private String revisionUuid;
private String name;
private String vhost;
private boolean isDisplayOnDevportal;
private boolean displayOnDevportal;
private String deployedTime;
public int getId() {
@ -37,20 +37,20 @@ public class APIRevisionDeployment implements Serializable {
this.id = id;
}
public String getRevisionUUID() {
return revisionUUID;
public String getRevisionUuid() {
return revisionUuid;
}
public void setRevisionUUID(String revisionUUID) {
this.revisionUUID = revisionUUID;
public void setRevisionUuid(String revisionUuid) {
this.revisionUuid = revisionUuid;
}
public String getDeployment() {
return deployment;
public String getName() {
return name;
}
public void setDeployment(String deployment) {
this.deployment = deployment;
public void setName(String name) {
this.name = name;
}
public String getVhost() {
@ -62,11 +62,11 @@ public class APIRevisionDeployment implements Serializable {
}
public boolean isDisplayOnDevportal() {
return isDisplayOnDevportal;
return displayOnDevportal;
}
public void setDisplayOnDevportal(boolean displayOnDevportal) {
isDisplayOnDevportal = displayOnDevportal;
this.displayOnDevportal = displayOnDevportal;
}
public String getDeployedTime() {

View File

@ -16,19 +16,35 @@
* under the License.
*/
function onRequest(context) {
var userModule = require("/app/modules/business-controllers/user.js")["userModule"];
var mdmProps = require("/app/modules/conf-reader/main.js")["conf"];
var viewModel = {};
package io.entgra.device.mgt.core.apimgt.extension.rest.api.dto.APIInfo;
public class AdditionalProperties {
if (userModule.isAuthorized("/permission/admin/device-mgt/certificates/manage")) {
viewModel["removePermitted"] = true;
}
if (userModule.isAuthorized("/permission/admin/device-mgt/certificates/view")) {
viewModel["viewPermitted"] = true;
private String name;
private String value;
private boolean display;
public String getName() {
return name;
}
viewModel.adminUser = mdmProps.adminUser;
return viewModel;
public void setName(String name) {
this.name = name;
}
public String getValue() {
return value;
}
public void setValue(String value) {
this.value = value;
}
public boolean isDisplay() {
return display;
}
public void setDisplay(boolean display) {
this.display = display;
}
}

View File

@ -24,16 +24,21 @@ public class Documentation {
private static final long serialVersionUID = 1L;
private String id;
private String documentId;
private DocumentationType type;
private String name;
private DocumentationType type;
private String summary;
private DocumentSourceType sourceType;
private String sourceUrl;
private DocumentVisibility visibility;
private Date lastUpdated;
private String fileName;
private String filePath;
private Date createdDate;
private String inlineContent;
private String otherTypeName;
private DocumentVisibility visibility;
private String createdTime;
private Date createdDate;
private String createdBy;
private Date lastUpdatedTime;
private String lastUpdatedBy;
public String getOtherTypeName() {
return this.otherTypeName;
@ -113,12 +118,12 @@ public class Documentation {
return result;
}
public Date getLastUpdated() {
return this.lastUpdated;
public Date getLastUpdatedTime() {
return this.lastUpdatedTime;
}
public void setLastUpdated(Date lastUpdated) {
this.lastUpdated = lastUpdated;
public void setLastUpdatedTime(Date lastUpdatedTime) {
this.lastUpdatedTime = lastUpdatedTime;
}
public String getId() {
@ -145,6 +150,46 @@ public class Documentation {
this.createdDate = createdDate;
}
public String getFileName() {
return fileName;
}
public void setFileName(String fileName) {
this.fileName = fileName;
}
public String getInlineContent() {
return inlineContent;
}
public void setInlineContent(String inlineContent) {
this.inlineContent = inlineContent;
}
public String getCreatedTime() {
return createdTime;
}
public void setCreatedTime(String createdTime) {
this.createdTime = createdTime;
}
public String getCreatedBy() {
return createdBy;
}
public void setCreatedBy(String createdBy) {
this.createdBy = createdBy;
}
public String getLastUpdatedBy() {
return lastUpdatedBy;
}
public void setLastUpdatedBy(String lastUpdatedBy) {
this.lastUpdatedBy = lastUpdatedBy;
}
public static enum DocumentVisibility {
OWNER_ONLY("owner_only"),
PRIVATE("private"),

View File

@ -16,16 +16,44 @@
* under the License.
*/
// This file is autogenerated via the `commonjs` Grunt task. You can require() this file in a CommonJS environment.
require('../../js/transition.js')
require('../../js/alert.js')
require('../../js/button.js')
require('../../js/carousel.js')
require('../../js/collapse.js')
require('../../js/dropdown.js')
require('../../js/modal.js')
require('../../js/tooltip.js')
require('../../js/popover.js')
require('../../js/scrollspy.js')
require('../../js/tab.js')
require('../../js/affix.js')
package io.entgra.device.mgt.core.apimgt.extension.rest.api.dto.APIInfo;
public class MediationPolicy {
private String id;
private String name;
private String type;
private boolean shared;
public String getId() {
return id;
}
public void setId(String id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getType() {
return type;
}
public void setType(String type) {
this.type = type;
}
public boolean isShared() {
return shared;
}
public void setShared(boolean shared) {
this.shared = shared;
}
}

View File

@ -16,15 +16,27 @@
* under the License.
*/
function onRequest(context) {
var userModule = require("/app/modules/business-controllers/user.js")["userModule"];
var utility = require("/app/modules/utility.js")["utility"];
var deviceType = request.getParameter("type");
package io.entgra.device.mgt.core.apimgt.extension.rest.api.dto.APIInfo;
var canEdit = false;
if(userModule.isAuthorized("/permission/admin/device-mgt/policy/manage")) {
canEdit = true;
import org.json.JSONObject;
public class Monetization {
private boolean enabled;
private JSONObject properties;
public boolean isEnabled() {
return enabled;
}
return {"deviceTypePolicyView": utility.getTenantedDeviceUnitName(deviceType, "policy-view"), "canEdit": canEdit};
public void setEnabled(boolean enabled) {
this.enabled = enabled;
}
public JSONObject getProperties() {
return properties;
}
public void setProperties(JSONObject properties) {
this.properties = properties;
}
}

View File

@ -18,7 +18,8 @@
package io.entgra.device.mgt.core.apimgt.extension.rest.api.dto.APIInfo;
import java.util.Set;
import org.json.JSONObject;
import java.util.List;
/**
* This hold the api operations information.
@ -29,8 +30,8 @@ public class Operations {
private String verb;
private String authType;
private String throttlingPolicy;
private Set<String> scopes;
private String usedProductIds;
private List<String> scopes;
private List<String> usedProductIds;
private String amznResourceName;
private String amznResourceTimeout;
private String payloadSchema;
@ -78,19 +79,19 @@ public class Operations {
this.throttlingPolicy = throttlingPolicy;
}
public Set<String> getScopes() {
public List<String> getScopes() {
return scopes;
}
public void setScopes(Set<String> scopes) {
public void setScopes(List<String> scopes) {
this.scopes = scopes;
}
public String getUsedProductIds() {
public List<String> getUsedProductIds() {
return usedProductIds;
}
public void setUsedProductIds(String usedProductIds) {
public void setUsedProductIds(List<String> usedProductIds) {
this.usedProductIds = usedProductIds;
}

View File

@ -18,25 +18,29 @@
package io.entgra.device.mgt.core.apimgt.extension.rest.api.dto.APIInfo;
import java.io.Serializable;
import java.util.List;
import java.util.ArrayList;
import java.util.Objects;
import java.util.Set;
import java.util.HashSet;
public class Scope implements Serializable{
private static final long serialVersionUID = 1L;
String key;
String name;
String roles;
String description;
String id;
String name;
String displayName;
String description;
List<String> bindings;
int usageCount;
public String getKey() {
return key;
public String getDisplayName() {
return displayName;
}
public void setKey(String key) {
this.key = key;
public void setDisplayName(String displayName) {
this.displayName = displayName;
}
public String getName() {
@ -47,12 +51,12 @@ public class Scope implements Serializable{
this.name = name;
}
public String getRoles() {
return roles;
public List<String> getBindings() {
return bindings;
}
public void setRoles(String roles) {
this.roles = roles;
public void setBindings(List<String> bindings) {
this.bindings = removeDuplicatesFromRoleString(bindings);
}
public String getDescription() {
@ -87,14 +91,22 @@ public class Scope implements Serializable{
Scope scope = (Scope) o;
if (id != null ? !id.equals(scope.id) : scope.id != null) return false;
if (!key.equals(scope.key)) return false;
if (!name.equals(scope.name)) return false;
if (roles != null ? !roles.equals(scope.roles) : scope.roles != null) return false;
if (!displayName.equals(scope.displayName)) return false;
if (bindings != null ? !bindings.equals(scope.bindings) : scope.bindings != null) return false;
return description != null ? description.equals(scope.description) : scope.description == null;
}
@Override
public int hashCode() {
return Objects.hash(key, name, roles, description, id);
return Objects.hash(name, displayName, bindings, description, id);
}
private static List<String> removeDuplicatesFromRoleString(List<String> roles) {
Set<String> roleSet = new HashSet<>();
for(String role : roles) {
roleSet.add(role.trim());
}
return new ArrayList<>(roleSet);
}
}

View File

@ -0,0 +1,59 @@
/*
* Copyright (c) 2018 - 2023, Entgra (Pvt) Ltd. (http://www.entgra.io) All Rights Reserved.
*
* Entgra (Pvt) Ltd. licenses this file to you under the Apache License,
* Version 2.0 (the "License"); you may not use this file except
* in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
package io.entgra.device.mgt.core.apimgt.extension.rest.api.dto.APIInfo;
public class ServiceInfo {
private String key;
private String name;
private String version;
private boolean outdated;
public String getKey() {
return key;
}
public void setKey(String key) {
this.key = key;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getVersion() {
return version;
}
public void setVersion(String version) {
this.version = version;
}
public boolean isOutdated() {
return outdated;
}
public void setOutdated(boolean outdated) {
this.outdated = outdated;
}
}

View File

@ -16,17 +16,26 @@
* under the License.
*/
function onRequest(context) {
var deviceTypes = context.unit.params.deviceTypes;
var deviceType = context.uriParams.deviceType;
package io.entgra.device.mgt.core.apimgt.extension.rest.api.dto.APIInfo;
var deviceTypesList = [];
if (deviceTypes) {
for (var i = 0; i < deviceTypes.length; i++) {
deviceTypesList.push(deviceTypes[i].type);
public class ThreatProtectionPolicies {
private String policyID;
private int priority;
public String getPolicyID() {
return policyID;
}
} else if (deviceType) {
deviceTypesList.push(deviceType);
public void setPolicyID(String policyID) {
this.policyID = policyID;
}
public int getPriority() {
return priority;
}
public void setPriority(int priority) {
this.priority = priority;
}
return {"deviceTypes": stringify(deviceTypesList)};
}

View File

@ -0,0 +1,61 @@
/*
* Copyright (c) 2018 - 2023, Entgra (Pvt) Ltd. (http://www.entgra.io) All Rights Reserved.
*
* Entgra (Pvt) Ltd. licenses this file to you under the Apache License,
* Version 2.0 (the "License"); you may not use this file except
* in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
package io.entgra.device.mgt.core.apimgt.extension.rest.api.dto.APIInfo;
/**
* This hold the Websub Subscription Configuration of an API.
*/
public class WebsubSubscriptionConfiguration {
private boolean enable;
private String secret;
private String signingAlgorithm;
private String signatureHeader;
public boolean isEnable() {
return enable;
}
public void setEnable(boolean enable) {
this.enable = enable;
}
public String getSecret() {
return secret;
}
public void setSecret(String secret) {
this.secret = secret;
}
public String getSigningAlgorithm() {
return signingAlgorithm;
}
public void setSigningAlgorithm(String signingAlgorithm) {
this.signingAlgorithm = signingAlgorithm;
}
public String getSignatureHeader() {
return signatureHeader;
}
public void setSignatureHeader(String signatureHeader) {
this.signatureHeader = signatureHeader;
}
}

View File

@ -1,90 +0,0 @@
/*
* Copyright (c) 2018 - 2023, Entgra (Pvt) Ltd. (http://www.entgra.io) All Rights Reserved.
*
* Entgra (Pvt) Ltd. licenses this file to you under the Apache License,
* Version 2.0 (the "License"); you may not use this file except
* in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
package io.entgra.device.mgt.core.apimgt.extension.rest.api.util;
import java.util.HashSet;
import java.util.Set;
/**
* This class represents the scope data.
*/
public class ScopeUtils {
private String key;
private String name;
private String roles;
private String description;
private int id;
public ScopeUtils() {
}
public String getKey() {
return key;
}
public void setKey(String key) {
this.key = key;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getRoles() {
return roles;
}
public void setRoles(String roles) {
this.roles = removeDuplicatesFromRoleString(roles);
}
public String getDescription() {
return description;
}
public void setDescription(String description) {
this.description = description;
}
public String toJSON() {
String jsonString = "{\n" +
" \"name\":\"" + key + "\",\n" +
" \"displayName\":\"" + name + "\",\n" +
" \"description\":\"" + description + "\",\n" +
" \"bindings\":[\n" +
" \"" + roles + "\"\n" +
" ]\n" +
"}";
return jsonString;
}
private static String removeDuplicatesFromRoleString(String roleString) {
String[] roles = roleString.split(",");
Set<String> roleSet = new HashSet<>();
for(String role : roles) {
roleSet.add(role.trim());
}
return String.join(",", roleSet);
}
}

View File

@ -17,19 +17,15 @@
*/
package io.entgra.device.mgt.core.apimgt.webapp.publisher;
import com.google.gson.Gson;
import io.entgra.device.mgt.core.apimgt.annotations.Scopes;
import io.entgra.device.mgt.core.apimgt.extension.rest.api.APIApplicationServices;
import io.entgra.device.mgt.core.apimgt.extension.rest.api.APIApplicationServicesImpl;
import io.entgra.device.mgt.core.apimgt.extension.rest.api.PublisherRESTAPIServices;
import io.entgra.device.mgt.core.apimgt.extension.rest.api.PublisherRESTAPIServicesImpl;
import io.entgra.device.mgt.core.apimgt.extension.rest.api.constants.Constants;
import io.entgra.device.mgt.core.apimgt.extension.rest.api.dto.APIApplicationKey;
import io.entgra.device.mgt.core.apimgt.extension.rest.api.dto.APIInfo.APIInfo;
import io.entgra.device.mgt.core.apimgt.extension.rest.api.dto.APIInfo.Scope;
import io.entgra.device.mgt.core.apimgt.extension.rest.api.dto.APIInfo.Mediation;
import io.entgra.device.mgt.core.apimgt.extension.rest.api.dto.APIInfo.Documentation;
import io.entgra.device.mgt.core.apimgt.extension.rest.api.dto.APIInfo.APIRevision;
import io.entgra.device.mgt.core.apimgt.extension.rest.api.dto.APIInfo.APIRevisionDeployment;
import io.entgra.device.mgt.core.apimgt.extension.rest.api.dto.APIInfo.CORSConfiguration;
import io.entgra.device.mgt.core.apimgt.extension.rest.api.dto.APIInfo.*;
import io.entgra.device.mgt.core.apimgt.extension.rest.api.dto.AccessTokenInfo;
import io.entgra.device.mgt.core.apimgt.extension.rest.api.exceptions.APIServicesException;
import io.entgra.device.mgt.core.apimgt.extension.rest.api.exceptions.BadRequestException;
@ -91,6 +87,7 @@ import java.util.Date;
*/
public class APIPublisherServiceImpl implements APIPublisherService {
public static final APIManagerFactory API_MANAGER_FACTORY = APIManagerFactory.getInstance();
private static final Gson gson = new Gson();
private static final String UNLIMITED_TIER = "Unlimited";
private static final String WS_UNLIMITED_TIER = "AsyncUnlimited";
private static final String API_PUBLISH_ENVIRONMENT = "Default";
@ -100,7 +97,7 @@ public class APIPublisherServiceImpl implements APIPublisherService {
public static final String SUBSCRIPTION_TO_CURRENT_TENANT = "CURRENT_TENANT";
public static final String API_GLOBAL_VISIBILITY = "PUBLIC";
public static final String API_PRIVATE_VISIBILITY = "PRIVATE";
private static final String ADMIN_ROLE_KEY = ",admin";
private static final String ADMIN_ROLE_KEY = "admin";
private static final Log log = LogFactory.getLog(APIPublisherServiceImpl.class);
@ -166,14 +163,14 @@ public class APIPublisherServiceImpl implements APIPublisherService {
apiConfig.getName(), apiConfig.getVersion());
PublisherRESTAPIServices publisherRESTAPIServices = new PublisherRESTAPIServicesImpl();
JSONArray apiList = (JSONArray) publisherRESTAPIServices.getApis(apiApplicationKey, accessTokenInfo).get("list");
APIInfo[] apiList = publisherRESTAPIServices.getApis(apiApplicationKey, accessTokenInfo);
boolean apiFound = false;
for (int i = 0; i < apiList.length(); i++) {
JSONObject apiObj = apiList.getJSONObject(i);
if (apiObj.getString("name").equals(apiIdentifier.getApiName().replace(Constants.SPACE,
for (int i = 0; i < apiList.length; i++) {
APIInfo apiObj = apiList[i];
if (apiObj.getName().equals(apiIdentifier.getApiName().replace(Constants.SPACE,
Constants.EMPTY_STRING))) {
apiFound = true;
apiIdentifier.setUuid(apiObj.getString("id"));
apiIdentifier.setUuid(apiObj.getId());
break;
}
}
@ -184,21 +181,23 @@ public class APIPublisherServiceImpl implements APIPublisherService {
if (!publisherRESTAPIServices.isSharedScopeNameExists(apiApplicationKey, accessTokenInfo,
apiScope.getKey())) {
Scope scope = new Scope();
scope.setName(apiScope.getName());
scope.setDisplayName(apiScope.getName());
scope.setDescription(apiScope.getDescription());
scope.setKey(apiScope.getKey());
scope.setRoles(apiScope.getRoles() + ADMIN_ROLE_KEY);
scope.setName(apiScope.getKey());
List<String> bindings = new ArrayList<>(apiScope.getRoles());
bindings.add(ADMIN_ROLE_KEY);
scope.setBindings(bindings);
publisherRESTAPIServices.addNewSharedScope(apiApplicationKey, accessTokenInfo, scope);
}
}
APIInfo api = getAPI(apiConfig, true);
JSONObject createdAPI = publisherRESTAPIServices.addAPI(apiApplicationKey, accessTokenInfo, api);
apiUuid = createdAPI.getString("id");
APIInfo createdAPI = publisherRESTAPIServices.addAPI(apiApplicationKey, accessTokenInfo, api);
apiUuid = createdAPI.getId();
if (apiConfig.getEndpointType() != null && "WS".equals(apiConfig.getEndpointType())) {
publisherRESTAPIServices.saveAsyncApiDefinition(apiApplicationKey, accessTokenInfo,
apiUuid, apiConfig.getAsyncApiDefinition());
}
if (CREATED_STATUS.equals(createdAPI.getString("lifeCycleStatus"))) {
if (CREATED_STATUS.equals(createdAPI.getLifeCycleStatus())) {
// if endpoint type "dynamic" and then add in sequence
if ("dynamic".equals(apiConfig.getEndpointType())) {
Mediation mediation = new Mediation();
@ -216,10 +215,10 @@ public class APIPublisherServiceImpl implements APIPublisherService {
apiRevision.setApiUUID(apiUuid);
apiRevision.setDescription("Initial Revision");
String apiRevisionId = publisherRESTAPIServices.addAPIRevision(apiApplicationKey,
accessTokenInfo, apiRevision).getString("id");
accessTokenInfo, apiRevision).getId();
APIRevisionDeployment apiRevisionDeployment = new APIRevisionDeployment();
apiRevisionDeployment.setDeployment(API_PUBLISH_ENVIRONMENT);
apiRevisionDeployment.setName(API_PUBLISH_ENVIRONMENT);
apiRevisionDeployment.setVhost(System.getProperty("iot.gateway.host"));
apiRevisionDeployment.setDisplayOnDevportal(true);
@ -257,10 +256,12 @@ public class APIPublisherServiceImpl implements APIPublisherService {
} else {
// if new scope add as shared scope
Scope scope = new Scope();
scope.setName(apiScope.getName());
scope.setName(apiScope.getKey());
scope.setDescription(apiScope.getDescription());
scope.setKey(apiScope.getKey());
scope.setRoles(apiScope.getRoles() + ADMIN_ROLE_KEY);
scope.setDisplayName(apiScope.getName());
List<String> bindings = new ArrayList<>(apiScope.getRoles());
bindings.add(ADMIN_ROLE_KEY);
scope.setBindings(bindings);
publisherRESTAPIServices.addNewSharedScope(apiApplicationKey, accessTokenInfo, scope);
}
@ -268,27 +269,29 @@ public class APIPublisherServiceImpl implements APIPublisherService {
}
// Get existing API
JSONObject existingAPI = publisherRESTAPIServices.getApi(apiApplicationKey, accessTokenInfo,
APIInfo existingAPI = publisherRESTAPIServices.getApi(apiApplicationKey, accessTokenInfo,
apiUuid);
if (scopesToMoveAsSharedScopes.size() > 0) {
// update API to remove local scopes
APIInfo api = getAPI(apiConfig, false);
api.setLifeCycleStatus(existingAPI.getString("lifeCycleStatus"));
api.setLifeCycleStatus(existingAPI.getLifeCycleStatus());
publisherRESTAPIServices.updateApi(apiApplicationKey, accessTokenInfo, api);
for (ApiScope apiScope : scopesToMoveAsSharedScopes) {
Scope scope = new Scope();
scope.setName(apiScope.getName());
scope.setName(apiScope.getKey());
scope.setDescription(apiScope.getDescription());
scope.setKey(apiScope.getKey());
scope.setRoles(apiScope.getRoles() + ADMIN_ROLE_KEY);
scope.setDisplayName(apiScope.getName());
List<String> bindings = new ArrayList<>(apiScope.getRoles());
bindings.add(ADMIN_ROLE_KEY);
scope.setBindings(bindings);
publisherRESTAPIServices.addNewSharedScope(apiApplicationKey, accessTokenInfo, scope);
}
}
existingAPI = publisherRESTAPIServices.getApi(apiApplicationKey, accessTokenInfo, apiUuid);
APIInfo api = getAPI(apiConfig, true);
api.setLastUpdatedTime(existingAPI.getString("lifeCycleStatus"));
api.setLifeCycleStatus(existingAPI.getLifeCycleStatus());
api.setId(apiUuid);
publisherRESTAPIServices.updateApi(apiApplicationKey, accessTokenInfo, api);
@ -305,15 +308,14 @@ public class APIPublisherServiceImpl implements APIPublisherService {
mediation.setType("in");
mediation.setGlobal(false);
JSONArray mediationList = (JSONArray) publisherRESTAPIServices
.getAllApiSpecificMediationPolicies(apiApplicationKey, accessTokenInfo,
apiUuid).get("list");
MediationPolicy[] mediationList = publisherRESTAPIServices
.getAllApiSpecificMediationPolicies(apiApplicationKey, accessTokenInfo, apiUuid);
boolean isMediationPolicyFound = false;
for (int i = 0; i < mediationList.length(); i++) {
JSONObject mediationObj = mediationList.getJSONObject(i);
if (apiConfig.getInSequenceName().equals(mediationObj.getString("name"))) {
mediation.setUuid(mediationObj.getString("id"));
for (int i = 0; i < mediationList.length; i++) {
MediationPolicy mediationPolicy = mediationList[i];
if (apiConfig.getInSequenceName().equals(mediationPolicy.getName())) {
mediation.setUuid(mediationPolicy.getId());
publisherRESTAPIServices.deleteApiSpecificMediationPolicy(apiApplicationKey,
accessTokenInfo, apiUuid, mediation);
publisherRESTAPIServices.addApiSpecificMediationPolicy(apiApplicationKey,
@ -328,24 +330,22 @@ public class APIPublisherServiceImpl implements APIPublisherService {
}
}
int apiRevisionCount = (int) publisherRESTAPIServices.getAPIRevisions(apiApplicationKey,
accessTokenInfo, apiUuid, null).get("count");
int apiRevisionCount = publisherRESTAPIServices.getAPIRevisions(apiApplicationKey,
accessTokenInfo, apiUuid, null).length;
if (apiRevisionCount >= 5) {
// This will retrieve the deployed revision
JSONArray revisionDeploymentList = (JSONArray) publisherRESTAPIServices.getAPIRevisions(
apiApplicationKey, accessTokenInfo, apiUuid,
true).get("list");
if (revisionDeploymentList.length() > 0) {
JSONObject latestRevisionDeployment = revisionDeploymentList.getJSONObject(0);
APIRevision[] revisionDeploymentList = publisherRESTAPIServices.getAPIRevisions(
apiApplicationKey, accessTokenInfo, apiUuid, true);
if (revisionDeploymentList.length > 0) {
APIRevision latestRevisionDeployment = revisionDeploymentList[0];
publisherRESTAPIServices.undeployAPIRevisionDeployment(apiApplicationKey,
accessTokenInfo, latestRevisionDeployment, apiUuid);
}
// This will retrieve the un deployed revision list
JSONArray undeployedRevisionList = (JSONArray) publisherRESTAPIServices.getAPIRevisions(
apiApplicationKey, accessTokenInfo, apiUuid,
false).get("list");
if (undeployedRevisionList.length() > 0) {
JSONObject earliestUndeployRevision = undeployedRevisionList.getJSONObject(0);
// This will retrieve the undeployed revision list
APIRevision[] undeployedRevisionList = publisherRESTAPIServices.getAPIRevisions(apiApplicationKey,
accessTokenInfo, apiUuid, false);
if (undeployedRevisionList.length > 0) {
APIRevision earliestUndeployRevision = undeployedRevisionList[0];
publisherRESTAPIServices.deleteAPIRevision(apiApplicationKey, accessTokenInfo,
earliestUndeployRevision, apiUuid);
}
@ -356,10 +356,10 @@ public class APIPublisherServiceImpl implements APIPublisherService {
apiRevision.setApiUUID(apiUuid);
apiRevision.setDescription("Updated Revision");
String apiRevisionId = publisherRESTAPIServices.addAPIRevision(apiApplicationKey,
accessTokenInfo, apiRevision).getString("id");
accessTokenInfo, apiRevision).getId();
APIRevisionDeployment apiRevisionDeployment = new APIRevisionDeployment();
apiRevisionDeployment.setDeployment(API_PUBLISH_ENVIRONMENT);
apiRevisionDeployment.setName(API_PUBLISH_ENVIRONMENT);
apiRevisionDeployment.setVhost(System.getProperty("iot.gateway.host"));
apiRevisionDeployment.setDisplayOnDevportal(true);
@ -369,7 +369,7 @@ public class APIPublisherServiceImpl implements APIPublisherService {
publisherRESTAPIServices.deployAPIRevision(apiApplicationKey, accessTokenInfo,
apiUuid, apiRevisionId, apiRevisionDeploymentList);
if (CREATED_STATUS.equals(existingAPI.getString("lifeCycleStatus"))) {
if (CREATED_STATUS.equals(existingAPI.getLifeCycleStatus())) {
publisherRESTAPIServices.changeLifeCycleStatus(apiApplicationKey, accessTokenInfo,
apiUuid, PUBLISH_ACTION);
}
@ -397,27 +397,27 @@ public class APIPublisherServiceImpl implements APIPublisherService {
apiDocumentation.setVisibility(Documentation.DocumentVisibility.API_LEVEL);
apiDocumentation.setSourceType(Documentation.DocumentSourceType.MARKDOWN);
apiDocumentation.setCreatedDate(new Date());
apiDocumentation.setLastUpdated(new Date());
apiDocumentation.setLastUpdatedTime(new Date());
apiDocumentation.setSummary(apiConfig.getApiDocumentationSummary());
apiDocumentation.setOtherTypeName(null);
JSONArray documentList = (JSONArray) publisherRESTAPIServices.getDocumentations(apiApplicationKey,
accessTokenInfo, apiUuid).get("list");
Documentation[] documentList = publisherRESTAPIServices.getDocumentations(apiApplicationKey,
accessTokenInfo, apiUuid);
if (documentList.length() > 0) {
for (int i = 0; i < documentList.length(); i++) {
JSONObject existingDoc = documentList.getJSONObject(i);
if (existingDoc.getString("name").equals(apiConfig.getApiDocumentationName())
&& existingDoc.getString("type").equals(Documentation.DocumentationType.HOWTO.name())) {
if (documentList.length > 0) {
for (int i = 0; i < documentList.length; i++) {
Documentation existingDoc = documentList[i];
if (existingDoc.getName().equals(apiConfig.getApiDocumentationName())
&& existingDoc.getType().equals(Documentation.DocumentationType.HOWTO.name())) {
publisherRESTAPIServices.deleteDocumentations(apiApplicationKey, accessTokenInfo,
apiUuid, existingDoc.getString("documentId"));
apiUuid, existingDoc.getDocumentId());
}
}
} else {
log.info("There is no any existing api documentation.");
}
io.entgra.device.mgt.core.apimgt.extension.rest.api.dto.APIInfo.Documentation createdDoc = publisherRESTAPIServices.addDocumentation(apiApplicationKey, accessTokenInfo,
Documentation createdDoc = publisherRESTAPIServices.addDocumentation(apiApplicationKey, accessTokenInfo,
apiUuid, apiDocumentation);
publisherRESTAPIServices.addDocumentationContent(apiApplicationKey, accessTokenInfo, apiUuid,
@ -458,10 +458,14 @@ public class APIPublisherServiceImpl implements APIPublisherService {
for (DefaultPermission defaultPermission: defaultPermissions.getDefaultPermissions()) {
//todo check whether scope is available or not
ScopeMapping scopeMapping = defaultPermission.getScopeMapping();
scope.setName(scopeMapping.getName());
List<String> bindings = new ArrayList<>(
Arrays.asList(scopeMapping.getDefaultRoles().split(",")));
bindings.add(ADMIN_ROLE_KEY);
scope.setName(scopeMapping.getKey());
scope.setDescription(scopeMapping.getName());
scope.setKey(scopeMapping.getKey());
scope.setRoles(scopeMapping.getDefaultRoles() + ADMIN_ROLE_KEY);
scope.setDisplayName(scopeMapping.getName());
scope.setBindings(bindings);
publisherRESTAPIServices.addNewSharedScope(apiApplicationKey, accessTokenInfo, scope);
}
} catch (BadRequestException | UnexpectedResponseException | APIServicesException e) {
@ -497,7 +501,6 @@ public class APIPublisherServiceImpl implements APIPublisherService {
PrivilegedCarbonContext.startTenantFlow();
PrivilegedCarbonContext.getThreadLocalCarbonContext().setTenantDomain(tenantDomain, true);
PublisherRESTAPIServices publisherRESTAPIServices = new PublisherRESTAPIServicesImpl();
JSONObject scopeObject = publisherRESTAPIServices.getScopes(apiApplicationKey, accessTokenInfo);
try {
String fileName =
@ -543,52 +546,43 @@ public class APIPublisherServiceImpl implements APIPublisherService {
}
Scope scope = new Scope();
scope.setName(
scope.setDisplayName(
scopeMapping[0] != null ? StringUtils.trim(scopeMapping[0]) : StringUtils.EMPTY);
scope.setDescription(
scopeMapping[1] != null ? StringUtils.trim(scopeMapping[1]) : StringUtils.EMPTY);
scope.setKey(
scope.setName(
scopeMapping[2] != null ? StringUtils.trim(scopeMapping[2]) : StringUtils.EMPTY);
// scope.setPermissions(
// scopeMapping[3] != null ? StringUtils.trim(scopeMapping[3]) : StringUtils.EMPTY);
String permission = scopeMapping[3] != null ? StringUtils.trim(scopeMapping[3]) : StringUtils.EMPTY;
String roleString = "";
List<String> rolesList = new ArrayList<>();
for (int i = 4; i < scopeMapping.length; i++) {
if (scopeMapping[i] != null && StringUtils.trim(scopeMapping[i]).equals("Yes")) {
roleString = roleString + "," + roles.get(i);
rolesList.add(roles.get(i));
if (rolePermissions.containsKey(roles.get(i)) && StringUtils.isNotEmpty(permission)) {
rolePermissions.get(roles.get(i)).add(permission);
}
}
}
if (roleString.length() > 1) {
roleString = roleString.substring(1); // remove first , (comma)
//Set scope details which related to the scope key
Scope[] scopes = publisherRESTAPIServices.getScopes(apiApplicationKey, accessTokenInfo);
for (int i = 0; i < scopes.length; i++) {
Scope relatedScope = scopes[i];
if (relatedScope.getName().equals(scopeMapping[2].toString())) {
scope.setId(relatedScope.getId());
scope.setUsageCount(relatedScope.getUsageCount());
//Including already existing roles
rolesList.addAll(relatedScope.getBindings());
}
scope.setRoles(roleString);
}
scope.setBindings(rolesList);
//Set scope id which related to the scope key
JSONArray scopeList = (JSONArray) scopeObject.get("list");
for (int i = 0; i < scopeList.length(); i++) {
JSONObject scopeObj = scopeList.getJSONObject(i);
if (scopeObj.getString("name").equals(scopeMapping[2] != null ?
StringUtils.trim(scopeMapping[2]) : StringUtils.EMPTY)) {
scope.setId(scopeObj.getString("id"));
// Including already existing roles
JSONArray existingRolesArray = (JSONArray) scopeObj.get("bindings");
for (int j = 0; j < existingRolesArray.length(); j++) {
roleString = roleString + "," + existingRolesArray.get(j);
}
}
}
scope.setRoles(roleString);
if (publisherRESTAPIServices.isSharedScopeNameExists(apiApplicationKey, accessTokenInfo, scope.getKey())) {
if (publisherRESTAPIServices.isSharedScopeNameExists(apiApplicationKey, accessTokenInfo, scope.getName())) {
publisherRESTAPIServices.updateSharedScope(apiApplicationKey, accessTokenInfo, scope);
} else {
// todo: come to this level means, that scope is removed from API, but haven't removed from the scope-role-permission-mappings list
log.warn(scope.getKey() + " not available as shared scope");
log.warn(scope.getName() + " not available as shared scope");
}
}
for (String role : rolePermissions.keySet()) {
@ -601,12 +595,7 @@ public class APIPublisherServiceImpl implements APIPublisherService {
}
} catch (IOException | DirectoryIteratorException ex) {
log.error("failed to read scopes from file.", ex);
} catch (APIServicesException | BadRequestException e) {
String errorMsg = "Error while calling APIs";
log.error(errorMsg, e);
throw new APIManagerPublisherException(e);
}
}
} catch (APIServicesException e) {
String errorMsg = "Error while processing Publisher REST API response";
@ -642,13 +631,14 @@ public class APIPublisherServiceImpl implements APIPublisherService {
try {
PublisherRESTAPIServices publisherRESTAPIServices = new PublisherRESTAPIServicesImpl();
JSONObject scopeObject = publisherRESTAPIServices.getScopes(apiApplicationKey, accessTokenInfo);
Scope[] scopeList = publisherRESTAPIServices.getScopes(apiApplicationKey, accessTokenInfo);
Map<String, String> permScopeMap = APIPublisherDataHolder.getInstance().getPermScopeMapping();
if (permissions.length != 0) {
updateScopes(roleName, publisherRESTAPIServices, apiApplicationKey, accessTokenInfo, scopeObject, permissions, permScopeMap, false);
updateScopes(roleName, publisherRESTAPIServices, apiApplicationKey, accessTokenInfo, scopeList, permissions, permScopeMap, false);
}
if (removedPermissions.length != 0) {
updateScopes(roleName, publisherRESTAPIServices, apiApplicationKey, accessTokenInfo, scopeObject, removedPermissions, permScopeMap, true);
updateScopes(roleName, publisherRESTAPIServices, apiApplicationKey, accessTokenInfo, scopeList, removedPermissions, permScopeMap, true);
}
try {
@ -680,7 +670,7 @@ public class APIPublisherServiceImpl implements APIPublisherService {
* @param publisherRESTAPIServices {@link PublisherRESTAPIServices}
* @param apiApplicationKey {@link APIApplicationKey}
* @param accessTokenInfo {@link AccessTokenInfo}
* @param scopeObject scope object returning from APIM
* @param scopeList scope list returning from APIM
* @param permissions List of permissions
* @param permScopeMap Permission Scope map
* @param removingPermissions if list of permissions has to be removed from the role send true, otherwise sends false.
@ -688,7 +678,7 @@ public class APIPublisherServiceImpl implements APIPublisherService {
*/
private void updateScopes (String roleName, PublisherRESTAPIServices publisherRESTAPIServices,
APIApplicationKey apiApplicationKey, AccessTokenInfo accessTokenInfo,
JSONObject scopeObject, String[] permissions, Map<String, String> permScopeMap, boolean removingPermissions )
Scope[] scopeList, String[] permissions, Map<String, String> permScopeMap, boolean removingPermissions )
throws APIManagerPublisherException {
for (String permission : permissions) {
String scopeValue = permScopeMap.get(permission);
@ -699,22 +689,21 @@ public class APIPublisherServiceImpl implements APIPublisherService {
throw new APIManagerPublisherException(msg);
}
JSONArray scopeList = (JSONArray) scopeObject.get("list");
for (int i = 0; i < scopeList.length(); i++) {
JSONObject scopeObj = scopeList.getJSONObject(i);
if (scopeObj.getString("name").equals(scopeValue)) {
for (int i = 0; i < scopeList.length; i++) {
Scope scopeObj = scopeList[i];
if (scopeObj.getName().equals(scopeValue)) {
Scope scope = new Scope();
scope.setName(scopeObj.getString("name"));
scope.setKey(scopeObj.getString("name"));
scope.setDescription(scopeObj.getString("description"));
scope.setId(scopeObj.getString("id"));
scope.setName(scopeObj.getName());
scope.setDisplayName(scopeObj.getDisplayName());
scope.setDescription(scopeObj.getDescription());
scope.setId(scopeObj.getId());
// Including already existing roles
JSONArray existingRolesArray = (JSONArray) scopeObj.get("bindings");
List<String> existingRoleList = new ArrayList<String>();
List<String> existingRoleList = new ArrayList<>();
existingRoleList.addAll(scopeObj.getBindings());
for (int j = 0; j < existingRolesArray.length(); j++) {
existingRoleList.add((String) existingRolesArray.get(j));
if (!existingRoleList.contains(roleName)) {
existingRoleList.add(roleName);
}
if (removingPermissions) {
@ -724,14 +713,14 @@ public class APIPublisherServiceImpl implements APIPublisherService {
existingRoleList.add(roleName);
}
}
scope.setRoles(String.join(",", existingRoleList));
scope.setBindings(existingRoleList);
try {
if (publisherRESTAPIServices.isSharedScopeNameExists(apiApplicationKey, accessTokenInfo, scope.getKey())) {
if (publisherRESTAPIServices.isSharedScopeNameExists(apiApplicationKey, accessTokenInfo, scope.getName())) {
publisherRESTAPIServices.updateSharedScope(apiApplicationKey, accessTokenInfo, scope);
} else {
// todo: come to this level means, that scope is removed from API, but haven't removed from the scope-role-permission-mappings list
log.warn(scope.getKey() + " not available as shared scope");
log.warn(scope.getName() + " not available as shared scope");
}
} catch (APIServicesException | BadRequestException | UnexpectedResponseException e) {
log.error("Error occurred while updating role scope mapping via APIM REST endpoint.", e);
@ -783,55 +772,49 @@ public class APIPublisherServiceImpl implements APIPublisherService {
apiInfo.setRevisionedApiId(null);
apiInfo.setEnableSchemaValidation(false);
Set<String> tags = new HashSet<>();
List<String> tags = new ArrayList<>();
tags.addAll(Arrays.asList(config.getTags()));
apiInfo.setTags(tags);
Set<String> availableTiers = new HashSet<>();
List<String> availableTiers = new ArrayList<>();
if (config.getEndpointType() != null && "WS".equals(config.getEndpointType())) {
availableTiers.add(WS_UNLIMITED_TIER);
} else {
availableTiers.add(UNLIMITED_TIER);
}
apiInfo.setPolicies(availableTiers);
if (config.getEndpointType() != null && "WS".equals(config.getEndpointType())) {
apiInfo.setAsyncApiDefinition(config.getAsyncApiDefinition());
}
apiInfo.setApiThrottlingPolicy(UNLIMITED_TIER);
//set operations and scopes
List<JSONObject> operations = new ArrayList();
List<Operations> operations = new ArrayList();
List<JSONObject> scopeSet = new ArrayList();
Iterator<ApiUriTemplate> iterator;
for (iterator = config.getUriTemplates().iterator(); iterator.hasNext(); ) {
ApiUriTemplate apiUriTemplate = iterator.next();
JSONObject operation = new JSONObject();
operation.put("target", apiUriTemplate.getUriTemplate());
operation.put("verb", apiUriTemplate.getHttpVerb());
operation.put("authType", apiUriTemplate.getAuthType());
operation.put("throttlingPolicy", UNLIMITED_TIER);
operation.put("uriMapping", apiUriTemplate.getUriMapping());
Operations operation = new Operations();
operation.setTarget(apiUriTemplate.getUriTemplate());
operation.setVerb(apiUriTemplate.getHttpVerb());
operation.setAuthType(apiUriTemplate.getAuthType());
operation.setThrottlingPolicy(UNLIMITED_TIER);
operation.setUriMapping(apiUriTemplate.getUriMapping());
if (includeScopes) {
if (apiUriTemplate.getScope() != null) {
String scopeString = "{\n" +
" \"scope\": {\n" +
" \"id\": null,\n" +
" \"name\": \"" + apiUriTemplate.getScope().getKey() + "\",\n" +
" \"displayName\": \"" + apiUriTemplate.getScope().getName() + "\",\n" +
" \"description\": \"" + apiUriTemplate.getScope().getDescription() + "\",\n" +
" \"bindings\": [\n" +
" \"" + apiUriTemplate.getScope().getRoles() + "\"\n" +
" ],\n" +
" \"usageCount\": null\n" +
" },\n" +
" \"shared\": true\n" +
" }";
JSONObject scope = new JSONObject(scopeString);
scopeSet.add(scope);
Scope scope = new Scope();
scope.setName(apiUriTemplate.getScope().getKey());
scope.setDisplayName(apiUriTemplate.getScope().getName());
scope.setDescription(apiUriTemplate.getScope().getDescription());
scope.setBindings(apiUriTemplate.getScope().getRoles());
Set<String> scopes = new HashSet<>();
scopes.add(apiUriTemplate.getScope().getKey());
operation.put("scopes", scopes);
JSONObject scopeObject = new JSONObject();
scopeObject.put("scope", new JSONObject(gson.toJson(scope)));
scopeObject.put("shared", true);
scopeSet.add(scopeObject);
List<String> scopes = new ArrayList<>();
scopes.addAll(Arrays.asList(apiUriTemplate.getScope().getKey()));
operation.setScopes(scopes);
}
}
operations.add(operation);
@ -859,8 +842,8 @@ public class APIPublisherServiceImpl implements APIPublisherService {
" }";
JSONObject endPointConfig = new JSONObject(endpointConfig);
Set<String> transports = new HashSet<>();
transports.addAll(Arrays.asList(config.getTransports()));
List<String> transports = new ArrayList<>();
transports.addAll(Arrays.asList(config.getTransports().split(",")));
apiInfo.setTransport(transports);
apiInfo.setType("HTTP");
@ -876,7 +859,7 @@ public class APIPublisherServiceImpl implements APIPublisherService {
" }\n" +
" }";
endPointConfig = new JSONObject(endpointConfig);
apiInfo.setInSequence(config.getInSequenceName());
apiInfo.setEndpointImplementationType("ENDPOINT");
}
// if ws endpoint
@ -892,7 +875,8 @@ public class APIPublisherServiceImpl implements APIPublisherService {
" }";
endPointConfig = new JSONObject(endpointConfig);
transports.addAll(Arrays.asList("wss,ws"));
transports.add("wss");
transports.add("ws");
apiInfo.setTransport(transports);
apiInfo.setType("WS");
}
@ -926,6 +910,8 @@ public class APIPublisherServiceImpl implements APIPublisherService {
apiInfo.setEnableSchemaValidation(false);
apiInfo.setMonetization(null);
apiInfo.setServiceInfo(null);
apiInfo.setWebsubSubscriptionConfiguration(null);
apiInfo.setAdvertiseInfo(null);
return apiInfo;
}

View File

@ -18,11 +18,13 @@
package io.entgra.device.mgt.core.apimgt.webapp.publisher.dto;
import java.util.List;
public class ApiScope {
String key;
String name;
String roles;
List<String> roles;
String permissions;
String description;
int id;
@ -46,11 +48,11 @@ public class ApiScope {
this.name = name;
}
public String getRoles() {
public List<String> getRoles() {
return this.roles;
}
public void setRoles(String roles) {
public void setRoles(List<String> roles) {
this.roles = roles;
}

View File

@ -228,10 +228,9 @@ public class AnnotationProcessor {
String permissions[];
StringBuilder aggregatedPermissions;
String roles[];
StringBuilder aggregatedRoles;
List<String> aggregatedRoles;
for (int i = 0; i < annotatedScopes.length; i++) {
aggregatedPermissions = new StringBuilder();
aggregatedRoles = new StringBuilder();
methodHandler = Proxy.getInvocationHandler(annotatedScopes[i]);
scope = new ApiScope();
scope.setName(invokeMethod(scopeClass
@ -250,11 +249,8 @@ public class AnnotationProcessor {
scope.setPermissions(aggregatedPermissions.toString().trim());
roles = (String[]) methodHandler.invoke(annotatedScopes[i], scopeClass
.getMethod(SWAGGER_ANNOTATIONS_PROPERTIES_ROLES, null), null);
for (String role : roles) {
aggregatedRoles.append(role);
aggregatedRoles.append(",");
}
scope.setRoles(aggregatedRoles.substring(0, aggregatedRoles.lastIndexOf(",")));
aggregatedRoles = Arrays.asList(roles);
scope.setRoles(aggregatedRoles);
scopes.put(scope.getKey(), scope);
}
return scopes;
@ -305,11 +301,13 @@ public class AnnotationProcessor {
// } else {
// log.warn("Scope is not defined for '" + makeContextURLReady(resourceRootContext) +
// makeContextURLReady(subCtx) + "' endpoint, hence assigning the default scope");
// List<String> roles = new ArrayList<>();
// roles.add(DEFAULT_SCOPE_ROLE);
// scope = new ApiScope();
// scope.setName(DEFAULT_SCOPE_NAME);
// scope.setDescription(DEFAULT_SCOPE_NAME);
// scope.setKey(DEFAULT_SCOPE_KEY);
// scope.setRoles(DEFAULT_SCOPE_ROLE);
// scope.setRoles(roles);
// scope.setPermissions(DEFAULT_SCOPE_PERMISSION);
// resource.setScope(scope);
// }
@ -543,11 +541,13 @@ public class AnnotationProcessor {
} else {
// log.warn("Scope is not defined for '" + makeContextURLReady(resourceRootContext) +
// makeContextURLReady(subCtx) + "' endpoint, hence assigning the default scope");
List<String> roles = new ArrayList<>();
roles.add(DEFAULT_SCOPE_ROLE);
scope = new ApiScope();
scope.setName(DEFAULT_SCOPE_NAME);
scope.setDescription(DEFAULT_SCOPE_NAME);
scope.setKey(DEFAULT_SCOPE_KEY);
scope.setRoles(DEFAULT_SCOPE_ROLE);
scope.setRoles(roles);
scope.setPermissions(DEFAULT_SCOPE_PERMISSION);
apiResource.setScope(scope);
}

View File

@ -39,7 +39,7 @@ public class TestUtils {
ApiScope scope = new ApiScope();
scope.setKey("win:ops:reboot");
scope.setName("Reboot");
scope.setRoles("/permission/admin/device-mgt/devices/owning-device/operations/windows/reboot");
scope.setPermissions("/permission/admin/device-mgt/devices/owning-device/operations/windows/reboot");
scope.setDescription("Lock reset on Windows devices");
template.setScope(scope);
uriTemplates.add(template);

View File

@ -0,0 +1,51 @@
/*
* Copyright (c) 2018 - 2023, Entgra (Pvt) Ltd. (http://www.entgra.io) All Rights Reserved.
*
* Entgra (Pvt) Ltd. licenses this file to you under the Apache License,
* Version 2.0 (the "License"); you may not use this file except
* in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
package io.entgra.device.mgt.core.device.mgt.api.jaxrs.beans;
import com.fasterxml.jackson.annotation.JsonProperty;
import com.google.gson.Gson;
import io.swagger.annotations.ApiModel;
import io.swagger.annotations.ApiModelProperty;
import io.entgra.device.mgt.core.device.mgt.common.operation.mgt.DeviceActivity;
import java.util.List;
@ApiModel(value = "ListOfDeviceActivities", description = "This contains a set of device activities that " +
"matches a given"
+ " criteria as a collection")
public class DeviceActivityList extends BasePaginatedResult {
private List<DeviceActivity> activities;
@ApiModelProperty(value = "List of device activity Ids")
@JsonProperty("activities")
public List<DeviceActivity> getList() {
return activities;
}
public void setList(List<DeviceActivity> activities) {
this.activities = activities;
}
@Override
public String toString() {
return new Gson().toJson(this);
}
}

View File

@ -385,6 +385,131 @@ public interface ActivityInfoProviderService {
defaultValue = "5")
@QueryParam("limit") int limit);
@GET
@Path("/devices")
@ApiOperation(
produces = MediaType.APPLICATION_JSON,
httpMethod = "GET",
value = "Getting Device Activity Details",
notes = "Get the details of the operations/activities executed by the server on the devices registered" +
" with WSO2 EMM, during a defined time period.",
tags = "Device Activity Info Provider",
extensions = {
@Extension(properties = {
@ExtensionProperty(name = Constants.SCOPE, value = "perm:get-activity")
})
},
nickname = "getDeviceActivitiesWithFilters"
)
@ApiResponses(value = {
@ApiResponse(
code = 200,
message = "OK. \n Successfully fetched the device activity details.",
response = ActivityList.class,
responseHeaders = {
@ResponseHeader(
name = "Content-Type",
description = "The content type of the body"),
@ResponseHeader(
name = "ETag",
description = "Entity Tag of the response resource.\n" +
"Used by caches, or in conditional requests."),
@ResponseHeader(
name = "Last-Modified",
description = "Date and time the resource was last modified.\n" +
"Used by caches, or in conditional requests."),
}),
@ApiResponse(
code = 304,
message = "Not Modified. \n Empty body because the client already has the latest version of the" +
" requested resource.\n"),
@ApiResponse(
code = 401,
message = "Unauthorized. \n Unauthorized request."),
@ApiResponse(
code = 404,
message = "Not Found. \n No activities found.",
response = ErrorResponse.class),
@ApiResponse(
code = 406,
message = "Not Acceptable.\n The requested media type is not supported"),
@ApiResponse(
code = 500,
message = "Internal Server Error. \n Server error occurred while fetching the activity data.",
response = ErrorResponse.class)
})
Response getDeviceActivities(
@ApiParam(
name = "offset",
value = "The starting pagination index for the complete list of qualified items.",
defaultValue = "0")
@DefaultValue("0") @QueryParam("offset") int offset,
@ApiParam(
name = "limit",
value = "Provide how many activity details you require from the starting pagination index/offset.",
defaultValue = "5")
@DefaultValue("20") @QueryParam("limit") int limit,
@ApiParam(
name = "since",
value = "Checks if the requested variant was created since the specified date-time.\n" +
"Provide the value in the following format: EEE, d MMM yyyy HH:mm:ss Z.\n" +
"Example: Mon, 05 Jan 2014 15:10:00 +0200"
)
@QueryParam("since") String since,
@ApiParam(
name = "initiatedBy",
value = "The user, who initiated the operation. If is done by the task, the SYSTEM will be returned." +
" And if a user adds the operation, username is returned"
)
@QueryParam("initiatedBy") String initiatedBy,
@ApiParam(
name = "operationCode",
value = "Operation Code to filter"
)
@QueryParam("operationCode") String operationCode,
@ApiParam(
name = "operationId",
value = "Operation Id to filter"
)
@QueryParam("operationId") int operationId,
@ApiParam(
name = "deviceType",
value = "Device Type to filter"
)
@QueryParam("deviceType") String deviceType,
@ApiParam(
name = "deviceId",
value = "Device Id to filter"
)
@QueryParam("deviceId") List<String> deviceIds,
@ApiParam(
name = "type",
value = "Operation type to filter"
)
@QueryParam("type") String type,
@ApiParam(
name = "status",
value = "Operation response status to filter"
)
@QueryParam("status") String status,
@ApiParam(
name = "If-Modified-Since",
value = "Checks if the requested variant was modified, since the specified date-time\n." +
"Provide the value in the following format: EEE, d MMM yyyy HH:mm:ss Z\n." +
"Example: Mon, 05 Jan 2014 15:10:00 +0200"
)
@HeaderParam("If-Modified-Since") String ifModifiedSince,
@ApiParam(
name = "startTimestamp",
value = "Starting unix timestamp value for filtering activities"
)
@QueryParam("startTimestamp") long startTimestamp,
@ApiParam(
name = "endTimestamp",
value = "Ending unix timestamp value for filtering activities"
)
@QueryParam("endTimestamp") long endTimestamp);
@GET
@ApiOperation(
produces = MediaType.APPLICATION_JSON,

View File

@ -75,7 +75,7 @@ import javax.ws.rs.core.Response;
description = "Add, Edit or View a Device Type",
key = "dm:admin:device-type:modify",
roles = {"Internal/devicemgt-admin"},
permissions = {"/device-mgt/admin/device-type"}
permissions = {"/device-mgt/admin/device-type/modify"}
),
@Scope(
name = "Getting Details of a Device Type",

View File

@ -29,6 +29,7 @@ import io.entgra.device.mgt.core.device.mgt.common.operation.mgt.Operation;
import io.entgra.device.mgt.core.device.mgt.common.operation.mgt.OperationManagementException;
import io.entgra.device.mgt.core.device.mgt.core.service.DeviceManagementProviderService;
import io.entgra.device.mgt.core.device.mgt.api.jaxrs.beans.ActivityList;
import io.entgra.device.mgt.core.device.mgt.api.jaxrs.beans.DeviceActivityList;
import io.entgra.device.mgt.core.device.mgt.api.jaxrs.beans.ErrorResponse;
import io.entgra.device.mgt.core.device.mgt.api.jaxrs.common.ActivityIdList;
import io.entgra.device.mgt.core.device.mgt.api.jaxrs.service.api.ActivityInfoProviderService;
@ -246,6 +247,130 @@ public class ActivityProviderServiceImpl implements ActivityInfoProviderService
}
}
@GET
@Path("/devices")
@Override
public Response getDeviceActivities(@DefaultValue("0") @QueryParam("offset") int offset,
@DefaultValue("20") @QueryParam("limit") int limit,
@QueryParam("since") String since,
@QueryParam("initiatedBy") String initiatedBy,
@QueryParam("operationCode") String operationCode,
@QueryParam("operationId") int operationId,
@QueryParam("deviceType") String deviceType,
@QueryParam("deviceId") List<String> deviceIds,
@QueryParam("type") String type,
@QueryParam("status") String status,
@HeaderParam("If-Modified-Since") String ifModifiedSince,
@QueryParam("startTimestamp") long startTimestamp,
@QueryParam("endTimestamp") long endTimestamp) {
long ifModifiedSinceTimestamp;
long sinceTimestamp;
long timestamp = 0;
boolean isTimeDurationProvided = false;
if (log.isDebugEnabled()) {
log.debug("getDeviceActivities since: " + since + " , offset: " + offset + " ,limit: " + limit + " ," +
"ifModifiedSince: " + ifModifiedSince);
}
RequestValidationUtil.validatePaginationParameters(offset, limit);
if (ifModifiedSince != null && !ifModifiedSince.isEmpty()) {
Date ifSinceDate;
SimpleDateFormat format = new SimpleDateFormat("EEE, d MMM yyyy HH:mm:ss Z");
try {
ifSinceDate = format.parse(ifModifiedSince);
} catch (ParseException e) {
return Response.status(400).entity(
new ErrorResponse.ErrorResponseBuilder().setMessage(
"Invalid date string is provided in 'If-Modified-Since' header").build()).build();
}
ifModifiedSinceTimestamp = ifSinceDate.getTime();
timestamp = ifModifiedSinceTimestamp / 1000;
} else if (since != null && !since.isEmpty()) {
Date sinceDate;
SimpleDateFormat format = new SimpleDateFormat("EEE, d MMM yyyy HH:mm:ss Z");
try {
sinceDate = format.parse(since);
} catch (ParseException e) {
return Response.status(400).entity(
new ErrorResponse.ErrorResponseBuilder().setMessage(
"Invalid date string is provided in 'since' filter").build()).build();
}
sinceTimestamp = sinceDate.getTime();
timestamp = sinceTimestamp / 1000;
} else if (startTimestamp > 0 && endTimestamp > 0) {
RequestValidationUtil.validateTimeDuration(startTimestamp, endTimestamp);
isTimeDurationProvided = true;
}
if (timestamp == 0 && !isTimeDurationProvided) {
//If timestamp is not sent by the user, a default value is set, that is equal to current time-12 hours.
long time = System.currentTimeMillis() / 1000;
timestamp = time - 42300;
}
if (log.isDebugEnabled()) {
log.debug("getDeviceActivities final timestamp " + timestamp);
}
DeviceActivityList deviceActivityList = new DeviceActivityList();
DeviceManagementProviderService dmService;
ActivityPaginationRequest activityPaginationRequest = new ActivityPaginationRequest(offset, limit);
try {
if (log.isDebugEnabled()) {
log.debug("Calling database to get device activities.");
}
dmService = DeviceMgtAPIUtils.getDeviceManagementService();
if (initiatedBy != null && !initiatedBy.isEmpty()) {
activityPaginationRequest.setInitiatedBy(initiatedBy);
}
if (operationCode != null && !operationCode.isEmpty()) {
activityPaginationRequest.setOperationCode(operationCode);
}
if (operationId > 0) {
activityPaginationRequest.setOperationId(operationId);
}
if (deviceType != null && !deviceType.isEmpty()) {
activityPaginationRequest.setDeviceType(deviceType);
}
if (deviceIds != null && !deviceIds.isEmpty()) {
activityPaginationRequest.setDeviceIds(deviceIds);
}
if (type != null && !type.isEmpty()) {
activityPaginationRequest.setType(Operation.Type.valueOf(type.toUpperCase()));
}
if (status != null && !status.isEmpty()) {
activityPaginationRequest.setStatus(Operation.Status.valueOf(status.toUpperCase()));
}
if (timestamp > 0) {
activityPaginationRequest.setSince(timestamp);
} else {
activityPaginationRequest.setStartTimestamp(startTimestamp);
activityPaginationRequest.setEndTimestamp(endTimestamp);
}
if (log.isDebugEnabled()) {
log.debug("Device Activity request: " + new Gson().toJson(activityPaginationRequest));
}
int count = dmService.getDeviceActivitiesCount(activityPaginationRequest);
if (log.isDebugEnabled()) {
log.debug("Filtered Device Activity count: " + count);
}
if (count > 0) {
deviceActivityList.setList(dmService.getDeviceActivities(activityPaginationRequest));
if (log.isDebugEnabled()) {
log.debug("Fetched Device Activity count: " + deviceActivityList.getList().size());
}
} else if (ifModifiedSince != null && !ifModifiedSince.isEmpty()) {
return Response.notModified().build();
}
deviceActivityList.setCount(count);
return Response.ok().entity(deviceActivityList).build();
} catch (OperationManagementException e) {
String msg
= "ErrorResponse occurred while fetching the device activities updated after given time stamp.";
log.error(msg, e);
return Response.serverError().entity(
new ErrorResponse.ErrorResponseBuilder().setMessage(msg).build()).build();
}
}
@GET
@Override
public Response getActivities(@DefaultValue("0") @QueryParam("offset") int offset,
@ -306,8 +431,6 @@ public class ActivityProviderServiceImpl implements ActivityInfoProviderService
if (log.isDebugEnabled()) {
log.debug("getActivities final timestamp " + timestamp);
}
Response response = validateAdminPermission();
if (response == null) {
ActivityList activityList = new ActivityList();
DeviceManagementProviderService dmService;
ActivityPaginationRequest activityPaginationRequest = new ActivityPaginationRequest(offset, limit);
@ -367,9 +490,6 @@ public class ActivityProviderServiceImpl implements ActivityInfoProviderService
return Response.serverError().entity(
new ErrorResponse.ErrorResponseBuilder().setMessage(msg).build()).build();
}
} else {
return response;
}
}
private Response validateAdminPermission() {

View File

@ -340,7 +340,8 @@ public class RoleManagementServiceImpl implements RoleManagementService {
for (UIPermissionNode node : permissionNode.getNodeList()) {
if (Constants.Permission.LOGIN.equals(node.getResourcePath()) ||
Constants.Permission.DEVICE_MGT.equals(node.getResourcePath()) ||
Constants.Permission.APP_MGT.equals(node.getResourcePath())) {
Constants.Permission.APP_MGT.equals(node.getResourcePath()) ||
Constants.Permission.TENANT.equals(node.getResourcePath())) {
deviceMgtPermissionsList.add(node);
}
}

View File

@ -19,6 +19,7 @@ package io.entgra.device.mgt.core.device.mgt.api.jaxrs.service.impl;
import com.google.gson.JsonArray;
import com.google.gson.JsonObject;
import io.entgra.device.mgt.core.device.mgt.common.Device;
import org.apache.commons.lang.StringUtils;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
@ -320,32 +321,42 @@ public class UserManagementServiceImpl implements UserManagementService {
@Consumes(MediaType.WILDCARD)
@Override
public Response removeUser(@QueryParam("username") String username, @QueryParam("domain") String domain) {
boolean nameWithDomain = false;
if (domain != null && !domain.isEmpty()) {
username = domain + '/' + username;
nameWithDomain = true;
}
try {
int deviceCount;
UserStoreManager userStoreManager = DeviceMgtAPIUtils.getUserStoreManager();
if (!userStoreManager.isExistingUser(username)) {
if (log.isDebugEnabled()) {
log.debug("User by username: " + username + " does not exist for removal.");
log.debug("User by user: " + username + " does not exist for removal.");
}
String msg = "User by username: " + username + " does not exist for removal.";
String msg = "User by user: " + username + " does not exist for removal.";
return Response.status(Response.Status.NOT_FOUND).entity(msg).build();
}
// Un-enroll all devices for the user
DeviceManagementProviderService deviceManagementService = DeviceMgtAPIUtils.getDeviceManagementService();
deviceManagementService.setStatus(username, EnrolmentInfo.Status.REMOVED);
if (nameWithDomain) {
deviceCount = deviceManagementService.getDeviceCount(username.split("/")[1]);
} else {
deviceCount = deviceManagementService.getDeviceCount(username);
}
if (deviceCount == 0) {
userStoreManager.deleteUser(username);
if (log.isDebugEnabled()) {
log.debug("User '" + username + "' was successfully removed.");
}
return Response.status(Response.Status.OK).build();
} else {
String msg = "There are enrolled devices for user: " + username + ". Please remove them before deleting the user.";
log.error(msg);
return Response.status(400).entity(msg).build();
}
} catch (DeviceManagementException | UserStoreException e) {
String msg = "Exception in trying to remove user by username: " + username;
String msg = "Exception in trying to remove user by user: " + username;
log.error(msg, e);
return Response.serverError().entity(
new ErrorResponse.ErrorResponseBuilder().setMessage(msg).build()).build();
return Response.status(400).entity(msg).build();
}
}

View File

@ -84,6 +84,7 @@ public class Constants {
public static final String LOGIN = "/permission/admin/login";
public static final String DEVICE_MGT = "/permission/admin/device-mgt";
public static final String APP_MGT = "/permission/admin/app-mgt";
public static final String TENANT = "/permission/admin/tenants";
}
}

View File

@ -34,6 +34,9 @@ import org.wso2.carbon.context.PrivilegedCarbonContext;
import io.entgra.device.mgt.core.device.mgt.common.DeviceIdentifier;
import io.entgra.device.mgt.core.device.mgt.common.authorization.DeviceAccessAuthorizationService;
import io.entgra.device.mgt.core.device.mgt.common.operation.mgt.Activity;
import io.entgra.device.mgt.core.device.mgt.common.ActivityPaginationRequest;
import io.entgra.device.mgt.core.device.mgt.common.operation.mgt.DeviceActivity;
import io.entgra.device.mgt.core.device.mgt.common.operation.mgt.Operation;
import io.entgra.device.mgt.core.device.mgt.common.operation.mgt.OperationManagementException;
import io.entgra.device.mgt.core.device.mgt.core.authorization.DeviceAccessAuthorizationServiceImpl;
import io.entgra.device.mgt.core.device.mgt.core.service.DeviceManagementProviderService;
@ -47,6 +50,7 @@ import io.entgra.device.mgt.core.policy.mgt.core.util.PolicyManagerUtil;
import javax.ws.rs.core.Response;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import static org.mockito.MockitoAnnotations.initMocks;
@ -63,6 +67,12 @@ public class ActivityProviderServiceImplTest {
private static final Log log = LogFactory.getLog(ActivityProviderServiceImplTest.class);
private static final String TEST_ACTIVITY_ID = "ACTIVITY_1";
private static final String IF_MODIFIED_SINCE = "01Aug2018";
private static final String SINCE = "Fri, 06 Oct 2023 15:30:00 GMT";
private static final String DEVICE_TYPE_2 = "power-meter";
private static final Operation.Status STATUS = Operation.Status.NOTNOW;
private static final Operation.Type TYPE = Operation.Type.PROFILE;
private static final String INITIATED_BY = "admin";
private static final int OPERATION_ID = 158572;
private static final String DEVICE_TYPE = "android";
private static final String DEVICE_ID = "1234567";
private static final String OPERATION_CODE = "111222";
@ -71,7 +81,10 @@ public class ActivityProviderServiceImplTest {
private static final String TEST_ACTIVITY_ID_LIST = "ACTIVITY_1,ACTIVITY_2";
private static final List<String> idList = new ArrayList();
private static final List<Activity> activities = new ArrayList<>();
private static final List<DeviceActivity> deviceActivities = new ArrayList<>();
private static final ActivityIdList activityList = new ActivityIdList(TEST_ACTIVITY_ID_LIST);
private static final ActivityPaginationRequest activityPaginationRequest = new ActivityPaginationRequest(LIMIT,OFFSET);
private static final ActivityIdList activityListEmpty = new ActivityIdList("");
private List<String> idList1;
@ -108,6 +121,23 @@ public class ActivityProviderServiceImplTest {
activity2.setActivityId("ACTIVITY_2");
activities.add(activity1);
activities.add(activity2);
DeviceActivity deviceActivity1 = new DeviceActivity();
DeviceActivity deviceActivity2 = new DeviceActivity();
deviceActivity1.setActivityId("ACTIVITY_3");
deviceActivity2.setActivityId("ACTIVITY_4");
deviceActivities.add(deviceActivity1);
deviceActivities.add(deviceActivity2);
activityPaginationRequest.setDeviceIds(Collections.singletonList(DEVICE_ID));
activityPaginationRequest.setOperationCode(OPERATION_CODE);
activityPaginationRequest.setDeviceType(DEVICE_TYPE_2);
activityPaginationRequest.setOperationId(OPERATION_ID);
activityPaginationRequest.setInitiatedBy(INITIATED_BY);
activityPaginationRequest.setStatus(STATUS);
activityPaginationRequest.setType(TYPE);
activityPaginationRequest.setStartTimestamp(0);
activityPaginationRequest.setEndTimestamp(0);
activityPaginationRequest.setLimit(LIMIT);
activityPaginationRequest.setOffset(OFFSET);
}
@Test(description =
@ -186,6 +216,70 @@ public class ActivityProviderServiceImplTest {
Mockito.reset(this.deviceManagementProviderService);
}
@Test(description = "This method tests trying to get details activity IDs when call with data")
public void testGetActivitiesWithActivityPaginationRequest() throws OperationManagementException {
PowerMockito.stub(PowerMockito.method(DeviceMgtAPIUtils.class, "isAdmin")).toReturn(true);
PowerMockito.stub(PowerMockito.method(DeviceMgtAPIUtils.class, "getDeviceManagementService"))
.toReturn(this.deviceManagementProviderService);
Mockito.when(this.deviceManagementProviderService.getActivitiesCount(Mockito.any())).thenReturn(2);
Mockito.when(this.deviceManagementProviderService.getActivities(Mockito.any())).thenReturn(activities);
Response response = this.activityInfoProviderService.getActivities(
OFFSET, LIMIT, SINCE, INITIATED_BY, OPERATION_CODE, OPERATION_ID,
DEVICE_TYPE_2, Collections.singletonList(DEVICE_ID), TYPE.toString(), STATUS.toString(), null, 0, 0);
Assert.assertEquals(response.getStatus(), Response.Status.OK.getStatusCode());
Assert.assertNotNull(response);
Mockito.reset(this.deviceManagementProviderService);
}
@Test(description = "This method tests trying to get details device activity IDs when call with empty data")
public void testGetActivitiesWithEmptyActivityPaginationRequest() throws OperationManagementException {
PowerMockito.stub(PowerMockito.method(DeviceMgtAPIUtils.class, "isAdmin")).toReturn(true);
PowerMockito.stub(PowerMockito.method(DeviceMgtAPIUtils.class, "getDeviceManagementService"))
.toReturn(this.deviceManagementProviderService);
Response response = this.activityInfoProviderService.getActivities(
OFFSET, 0, null, null, null, 0,
null, null, null, null, null, 0, 0);
Assert.assertEquals(response.getStatus(), Response.Status.OK.getStatusCode());
Assert.assertEquals(response.getEntity().toString(), "{\"count\":0}");
Mockito.reset(this.deviceManagementProviderService);
}
@Test(description = "This method tests trying to get details device activity IDs when call with data")
public void testGetDeviceActivitiesWithActivityPaginationRequest() throws OperationManagementException {
PowerMockito.stub(PowerMockito.method(DeviceMgtAPIUtils.class, "isAdmin")).toReturn(true);
PowerMockito.stub(PowerMockito.method(DeviceMgtAPIUtils.class, "getDeviceManagementService"))
.toReturn(this.deviceManagementProviderService);
Mockito.when(this.deviceManagementProviderService.getDeviceActivitiesCount(Mockito.any())).thenReturn(2);
Mockito.when(this.deviceManagementProviderService.getDeviceActivities(Mockito.any())).thenReturn(deviceActivities);
Response response = this.activityInfoProviderService.getDeviceActivities(
OFFSET, LIMIT, SINCE, INITIATED_BY, OPERATION_CODE, OPERATION_ID,
DEVICE_TYPE_2, Collections.singletonList(DEVICE_ID), TYPE.toString(), STATUS.toString(), null, 0, 0);
Assert.assertEquals(response.getStatus(), Response.Status.OK.getStatusCode());
Assert.assertNotNull(response);
Mockito.reset(this.deviceManagementProviderService);
}
@Test(description = "This method tests trying to get details activity IDs when call with empty data")
public void testGetDeviceActivitiesWithEmptyActivityPaginationRequest() {
PowerMockito.stub(PowerMockito.method(DeviceMgtAPIUtils.class, "isAdmin")).toReturn(true);
PowerMockito.stub(PowerMockito.method(DeviceMgtAPIUtils.class, "getDeviceManagementService"))
.toReturn(this.deviceManagementProviderService);
Response response = this.activityInfoProviderService.getDeviceActivities(
OFFSET, 0, null, null, null, 0,
null, null, null, null, null, 0, 0);
Assert.assertEquals(response.getStatus(), Response.Status.OK.getStatusCode());
Assert.assertEquals(response.getEntity().toString(), "{\"count\":0}");
Mockito.reset(this.deviceManagementProviderService);
}
@Test(description = "This method tests trying to get details of a list activity IDs which does not exists")
public void testGetActivitiesWithNonExistingActivityIdList() throws OperationManagementException {
PowerMockito.stub(PowerMockito.method(DeviceMgtAPIUtils.class, "isAdmin")).toReturn(true);

View File

@ -18,6 +18,7 @@
package io.entgra.device.mgt.core.device.mgt.api.jaxrs.service.impl;
import io.entgra.device.mgt.core.device.mgt.common.Device;
import org.mockito.Mockito;
import org.mockito.invocation.InvocationOnMock;
import org.mockito.stubbing.Answer;
@ -272,7 +273,7 @@ public class UserManagementServiceImplTest {
.toReturn(this.userStoreManager);
PowerMockito.stub(PowerMockito.method(DeviceMgtAPIUtils.class, "getDeviceManagementService"))
.toReturn(this.deviceManagementProviderService);
Mockito.doReturn(true).when(deviceManagementProviderService).setStatus(Mockito.anyString(), Mockito.any());
Mockito.doReturn(0).when(deviceManagementProviderService).getDeviceCount(TEST_USERNAME);
Mockito.doNothing().when(userStoreManager).deleteUser(Mockito.anyString());
Response response = userManagementService.removeUser(TEST_USERNAME, null);
Assert.assertEquals(response.getStatus(), Response.Status.OK.getStatusCode(),
@ -337,7 +338,7 @@ public class UserManagementServiceImplTest {
Assert.assertEquals(response.getStatus(), Response.Status.INTERNAL_SERVER_ERROR.getStatusCode(),
"Response returned successful for a user updating request with problematic inputs");
response = userManagementService.removeUser(TEST3_USERNAME, null);
Assert.assertEquals(response.getStatus(), Response.Status.INTERNAL_SERVER_ERROR.getStatusCode(),
Assert.assertEquals(response.getStatus(), Response.Status.BAD_REQUEST.getStatusCode(),
"Response returned successful for a user removal request with problematic inputs");
response = userManagementService.getRolesOfUser(TEST3_USERNAME, null);
Assert.assertEquals(response.getStatus(), Response.Status.INTERNAL_SERVER_ERROR.getStatusCode(),

View File

@ -0,0 +1,205 @@
/*
* Copyright (c) 2018 - 2023, Entgra (Pvt) Ltd. (http://www.entgra.io) All Rights Reserved.
*
* Entgra (Pvt) Ltd. licenses this file to you under the Apache License,
* Version 2.0 (the "License"); you may not use this file except
* in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
package io.entgra.device.mgt.core.device.mgt.common.operation.mgt;
import com.fasterxml.jackson.annotation.JsonProperty;
import io.swagger.annotations.ApiModel;
import io.swagger.annotations.ApiModelProperty;
import io.entgra.device.mgt.core.device.mgt.common.DeviceIdentifier;
import java.util.List;
@ApiModel(value = "DeviceActivity", description = "An activity instance carries a unique identifier that can be " +
"used to identify a particular operation instance uniquely")
public class DeviceActivity {
public enum Type {
CONFIG, MESSAGE, INFO, COMMAND, PROFILE, POLICY
}
public enum Status {
IN_PROGRESS, PENDING, COMPLETED, ERROR, REPEATED, INVALID, UNAUTHORIZED, NOTNOW, REQUIRED_CONFIRMATION, CONFIRMED
}
@ApiModelProperty(
name = "activityId",
value = "Device Activity identifier",
required = true,
example = "ACTIVITY_1")
@JsonProperty("activityId")
private String activityId;
@ApiModelProperty(
name = "code",
value = "Device Activity code",
required = true,
example = "DEVICE_RING")
@JsonProperty("code")
private String code;
@ApiModelProperty(
name = "operationId",
value = "Operation Id",
required = false,
example = "10")
@JsonProperty("operationId")
private int operationId;
@ApiModelProperty(
name = "type",
value = "Activity type",
required = true,
allowableValues = "CONFIG, MESSAGE, INFO, COMMAND, PROFILE, POLICY",
example = "COMMAND")
@JsonProperty("type")
private Type type;
@ApiModelProperty(
name = "status",
value = "Status of the device activity performed.",
required = true,
example = "PENDING")
@JsonProperty("status")
private Status status;
@ApiModelProperty(
name = "createdTimeStamp",
value = "Timestamp recorded when the activity took place",
required = true,
example = "Thu Oct 06 11:18:47 IST 2016")
@JsonProperty("createdTimestamp")
private String createdTimeStamp;
@ApiModelProperty(
name = "deviceActivities",
value = "Collection of devices activities corresponding to the activity",
required = true)
@JsonProperty("deviceActivities")
private List<DeviceActivity> deviceActivities;
@ApiModelProperty(
name = "initiatedBy",
value = "Initiated user",
required = true)
@JsonProperty("initiatedBy")
private String initiatedBy;
@ApiModelProperty(
name = "deviceIdentifier",
value = "Device identifier of the device.",
required = true)
@JsonProperty("deviceIdentifier")
private DeviceIdentifier deviceIdentifier;
@ApiModelProperty(
name = "responses",
value = "Responses received from devices.",
required = true)
@JsonProperty("responses")
private List<OperationResponse> responses;
@ApiModelProperty(
name = "updatedTimestamp ",
value = "Last updated time of the activity.",
required = true,
example = "Thu Oct 06 11:18:47 IST 2016")
@JsonProperty("updatedTimestamp")
private String updatedTimestamp;
public DeviceIdentifier getDeviceIdentifier() {
return deviceIdentifier;
}
public void setDeviceIdentifier(DeviceIdentifier deviceIdentifier) {
this.deviceIdentifier = deviceIdentifier;
}
public List<OperationResponse> getResponses() {
return responses;
}
public void setResponses(List<OperationResponse> responses) {
this.responses = responses;
}
public String getUpdatedTimestamp() {
return updatedTimestamp;
}
public void setUpdatedTimestamp(String updatedTimestamp) {
this.updatedTimestamp = updatedTimestamp;
}
public String getActivityId() {
return activityId;
}
public void setActivityId(String activityId) {
this.activityId = activityId;
}
public String getCode() {
return code;
}
public void setCode(String code) {
this.code = code;
}
public Status getStatus() {
return status;
}
public void setStatus(Status status) {
this.status = status;
}
public int getOperationId() {
return operationId;
}
public void setOperationId(int operationId) {
this.operationId = operationId;
}
public Type getType() {
return type;
}
public void setType(Type type) {
this.type = type;
}
public String getCreatedTimeStamp() {
return createdTimeStamp;
}
public void setCreatedTimeStamp(String createdTimeStamp) {
this.createdTimeStamp = createdTimeStamp;
}
public List<DeviceActivity> getDeviceActivities() {
return deviceActivities;
}
public void setDeviceActivities(List<DeviceActivity> deviceActivities) {
this.deviceActivities = deviceActivities;
}
public String getInitiatedBy() {
return initiatedBy;
}
public void setInitiatedBy(String initiatedBy) {
this.initiatedBy = initiatedBy;
}
}

View File

@ -128,6 +128,11 @@ public interface OperationManager {
int getActivitiesCount(ActivityPaginationRequest activityPaginationRequest)
throws OperationManagementException;
List<DeviceActivity> getDeviceActivities(ActivityPaginationRequest activityPaginationRequest) throws OperationManagementException;
int getDeviceActivitiesCount(ActivityPaginationRequest activityPaginationRequest)
throws OperationManagementException;
List<Activity> getFilteredActivities(String operationCode, int limit, int offset) throws OperationManagementException;
int getTotalCountOfFilteredActivities(String operationCode) throws OperationManagementException;

View File

@ -41,6 +41,7 @@ import io.entgra.device.mgt.core.device.mgt.common.exceptions.InvalidDeviceExcep
import io.entgra.device.mgt.core.device.mgt.common.exceptions.TransactionManagementException;
import io.entgra.device.mgt.core.device.mgt.common.group.mgt.DeviceGroupConstants;
import io.entgra.device.mgt.core.device.mgt.common.operation.mgt.Activity;
import io.entgra.device.mgt.core.device.mgt.common.operation.mgt.DeviceActivity;
import io.entgra.device.mgt.core.device.mgt.common.operation.mgt.ActivityStatus;
import io.entgra.device.mgt.core.device.mgt.common.operation.mgt.Operation;
import io.entgra.device.mgt.core.device.mgt.common.operation.mgt.OperationManagementException;
@ -1303,6 +1304,36 @@ public class OperationManagerImpl implements OperationManager {
}
}
@Override
public List<DeviceActivity> getDeviceActivities(ActivityPaginationRequest activityPaginationRequest)
throws OperationManagementException {
try {
OperationManagementDAOFactory.openConnection();
return operationDAO.getDeviceActivities(activityPaginationRequest);
} catch (SQLException e) {
throw new OperationManagementException("Error occurred while opening a connection to the data source.", e);
} catch (OperationManagementDAOException e) {
throw new OperationManagementException("Error occurred while getting the device activity list.", e);
} finally {
OperationManagementDAOFactory.closeConnection();
}
}
@Override
public int getDeviceActivitiesCount(ActivityPaginationRequest activityPaginationRequest)
throws OperationManagementException {
try {
OperationManagementDAOFactory.openConnection();
return operationDAO.getDeviceActivitiesCount(activityPaginationRequest);
} catch (SQLException e) {
throw new OperationManagementException("Error occurred while opening a connection to the data source.", e);
} catch (OperationManagementDAOException e) {
throw new OperationManagementException("Error occurred while getting the device activity count.", e);
} finally {
OperationManagementDAOFactory.closeConnection();
}
}
@Override
public List<Activity> getFilteredActivities(String operationCode, int limit, int offset) throws OperationManagementException {
try {

View File

@ -22,6 +22,7 @@ import io.entgra.device.mgt.core.device.mgt.common.DeviceIdentifier;
import io.entgra.device.mgt.core.device.mgt.common.PaginationRequest;
import io.entgra.device.mgt.core.device.mgt.common.operation.mgt.Activity;
import io.entgra.device.mgt.core.device.mgt.common.operation.mgt.OperationResponse;
import io.entgra.device.mgt.core.device.mgt.common.operation.mgt.DeviceActivity;
import io.entgra.device.mgt.core.device.mgt.core.dto.operation.mgt.Operation;
import io.entgra.device.mgt.core.device.mgt.core.dto.operation.mgt.OperationResponseMeta;
import io.entgra.device.mgt.core.device.mgt.core.operation.mgt.OperationMapping;
@ -118,4 +119,9 @@ public interface OperationDAO {
int getActivitiesCount(ActivityPaginationRequest activityPaginationRequest)
throws OperationManagementDAOException;
List<DeviceActivity> getDeviceActivities(ActivityPaginationRequest activityPaginationRequest)
throws OperationManagementDAOException;
int getDeviceActivitiesCount(ActivityPaginationRequest activityPaginationRequest)
throws OperationManagementDAOException;
}

View File

@ -26,6 +26,7 @@ import io.entgra.device.mgt.core.device.mgt.common.ActivityPaginationRequest;
import io.entgra.device.mgt.core.device.mgt.common.DeviceIdentifier;
import io.entgra.device.mgt.core.device.mgt.common.PaginationRequest;
import io.entgra.device.mgt.core.device.mgt.common.operation.mgt.Activity;
import io.entgra.device.mgt.core.device.mgt.common.operation.mgt.DeviceActivity;
import io.entgra.device.mgt.core.device.mgt.common.operation.mgt.ActivityHolder;
import io.entgra.device.mgt.core.device.mgt.common.operation.mgt.ActivityStatus;
import io.entgra.device.mgt.core.device.mgt.common.operation.mgt.OperationResponse;
@ -399,6 +400,51 @@ public class GenericOperationDAOImpl implements OperationDAO {
}
}
public OperationResponse populateResponse(ResultSet rs) throws SQLException {
OperationResponse response = new OperationResponse();
DeviceActivity deviceActivity = new DeviceActivity();
int responseId = 0;
List<OperationResponse> operationResponses = new ArrayList<>();
List<Integer> largeResponseIDs = new ArrayList<>();
if (rs.getTimestamp("RECEIVED_TIMESTAMP") != null) {
Timestamp receivedTimestamp = rs.getTimestamp("RECEIVED_TIMESTAMP");
response.setReceivedTimeStamp(new Date(receivedTimestamp.getTime()).toString());
}
response.setResponse(rs.getString("OPERATION_RESPONSE"));
int deviceOpId = rs.getInt("OPERATION_ID");
String deviceActivityId = DeviceManagementConstants.OperationAttributes.ACTIVITY + deviceOpId;
String deviceIdentifierId = rs.getString("DEVICE_IDENTIFICATION");
if (rs.getInt("UPDATED_TIMESTAMP") != 0) {
responseId = rs.getInt("OP_RES_ID");
if (rs.getBoolean("IS_LARGE_RESPONSE")) {
largeResponseIDs.add(responseId);
} else {
deviceActivity.setResponses(operationResponses);
}
}
if (!largeResponseIDs.isEmpty()) {
Map<String, Map<String, List<OperationResponse>>> largeOperationResponses = null;
try {
largeOperationResponses = getLargeOperationResponsesInBulk(largeResponseIDs);
if (!largeOperationResponses.isEmpty()) {
Map<String, List<OperationResponse>> largeResponse = largeOperationResponses.get(deviceActivityId);
if (largeResponse != null) {
response = largeResponse.get(deviceIdentifierId).get(0);
}
}
} catch (OperationManagementDAOException e) {
log.warn("Unable to get operation response for Operation ID: " + deviceOpId +
", Error: " + e.getErrorMessage());
}
}
return response;
}
@Override
public Activity getActivity(int operationId) throws OperationManagementDAOException {
@ -2566,4 +2612,222 @@ public class GenericOperationDAOImpl implements OperationDAO {
return 0;
}
@Override
public List<DeviceActivity> getDeviceActivities(ActivityPaginationRequest activityPaginationRequest)
throws OperationManagementDAOException {
List<DeviceActivity> finalizedActivitiesList = new ArrayList<>();
try {
boolean isTimeDurationFilteringProvided = false;
Connection conn = OperationManagementDAOFactory.getConnection();
int tenantId = PrivilegedCarbonContext.getThreadLocalCarbonContext().getTenantId();
StringBuilder sql = new StringBuilder("SELECT " +
" eom.*," +
" opr.ID AS OP_RES_ID," +
" opr.RECEIVED_TIMESTAMP," +
" opr.OPERATION_RESPONSE, " +
" opr.IS_LARGE_RESPONSE " +
"FROM(" +
" SELECT * " +
" FROM " +
" DM_ENROLMENT_OP_MAPPING " +
" WHERE " +
" TENANT_ID = ? ");
if (activityPaginationRequest.getStartTimestamp() > 0 && activityPaginationRequest.getEndTimestamp() > 0) {
isTimeDurationFilteringProvided = true;
sql.append("AND CREATED_TIMESTAMP BETWEEN ? AND ? ");
}
if (activityPaginationRequest.getDeviceType() != null) {
sql.append("AND DEVICE_TYPE = ? ");
}
if (activityPaginationRequest.getDeviceIds() != null && !activityPaginationRequest.getDeviceIds().isEmpty()) {
sql.append("AND DEVICE_IDENTIFICATION IN (");
for (int i = 0; i < activityPaginationRequest.getDeviceIds().size() - 1; i++) {
sql.append("?, ");
}
sql.append("?) ");
}
if (activityPaginationRequest.getOperationId() > 0) {
sql.append("AND OPERATION_ID = ? ");
}
if (activityPaginationRequest.getOperationCode() != null) {
sql.append("AND OPERATION_CODE = ? ");
}
if (activityPaginationRequest.getInitiatedBy() != null) {
sql.append("AND INITIATED_BY = ? ");
}
if (activityPaginationRequest.getSince() != 0) {
sql.append("AND UPDATED_TIMESTAMP > ? ");
}
if (activityPaginationRequest.getType() != null) {
sql.append("AND TYPE = ? ");
}
if (activityPaginationRequest.getStatus() != null) {
sql.append("AND STATUS = ? ");
}
sql.append("ORDER BY ID ASC limit ? , ? ) eom " +
"LEFT JOIN DM_DEVICE_OPERATION_RESPONSE opr ON eom.ID = opr.EN_OP_MAP_ID");
int index = 1;
try (PreparedStatement stmt = conn.prepareStatement(sql.toString())) {
stmt.setInt(index++, tenantId);
if (isTimeDurationFilteringProvided) {
stmt.setLong(index++, activityPaginationRequest.getStartTimestamp());
stmt.setLong(index++, activityPaginationRequest.getEndTimestamp());
}
if (activityPaginationRequest.getDeviceType() != null) {
stmt.setString(index++, activityPaginationRequest.getDeviceType());
}
if (activityPaginationRequest.getDeviceIds() != null && !activityPaginationRequest.getDeviceIds().isEmpty()) {
for (String deviceId : activityPaginationRequest.getDeviceIds()) {
stmt.setString(index++, deviceId);
}
}
if (activityPaginationRequest.getOperationId() > 0) {
stmt.setInt(index++, activityPaginationRequest.getOperationId());
}
if (activityPaginationRequest.getOperationCode() != null) {
stmt.setString(index++, activityPaginationRequest.getOperationCode());
}
if (activityPaginationRequest.getInitiatedBy() != null) {
stmt.setString(index++, activityPaginationRequest.getInitiatedBy());
}
if (activityPaginationRequest.getSince() != 0) {
stmt.setLong(index++, activityPaginationRequest.getSince());
}
if (activityPaginationRequest.getType() != null) {
stmt.setString(index++, activityPaginationRequest.getType().name());
}
if (activityPaginationRequest.getStatus() != null) {
stmt.setString(index++, activityPaginationRequest.getStatus().name());
}
stmt.setInt(index++, activityPaginationRequest.getOffset());
stmt.setInt(index, activityPaginationRequest.getLimit());
try (ResultSet rs = stmt.executeQuery()) {
Map<Integer, DeviceActivity> activities = new HashMap<>();
while (rs.next()) {
int activityId = rs.getInt("ID");
DeviceActivity deviceActivity = activities.get(activityId);
if (deviceActivity == null) {
deviceActivity = OperationDAOUtil.populateActivity(rs);
activities.put(activityId, deviceActivity);
}
deviceActivity.getResponses().add(populateResponse(rs));
}
for (int activityId : activities.keySet()) {
DeviceActivity deviceActivity = activities.get(activityId);
finalizedActivitiesList.add(deviceActivity);
}
}
}
} catch (SQLException e) {
String msg = "Error occurred while getting the operation details from the database.";
log.error(msg, e);
throw new OperationManagementDAOException(msg, e);
}
return finalizedActivitiesList;
}
@Override
public int getDeviceActivitiesCount(ActivityPaginationRequest activityPaginationRequest)
throws OperationManagementDAOException {
try {
boolean isTimeDurationFilteringProvided = false;
Connection conn = OperationManagementDAOFactory.getConnection();
int tenantId = PrivilegedCarbonContext.getThreadLocalCarbonContext().getTenantId();
StringBuilder sql = new StringBuilder();
sql.append("SELECT count(DISTINCT ID) AS ACTIVITY_COUNT " +
"FROM DM_ENROLMENT_OP_MAPPING WHERE TENANT_ID = ? ");
if (activityPaginationRequest.getDeviceType() != null) {
sql.append("AND DEVICE_TYPE = ? ");
}
if (activityPaginationRequest.getDeviceIds() != null && !activityPaginationRequest.getDeviceIds().isEmpty()) {
sql.append("AND DEVICE_IDENTIFICATION IN (");
for (int i = 0; i < activityPaginationRequest.getDeviceIds().size() - 1; i++) {
sql.append("?, ");
}
sql.append("?) ");
}
if (activityPaginationRequest.getOperationCode() != null) {
sql.append("AND OPERATION_CODE = ? ");
}
if (activityPaginationRequest.getOperationId() > 0) {
sql.append("AND OPERATION_ID = ? ");
}
if (activityPaginationRequest.getInitiatedBy() != null) {
sql.append("AND INITIATED_BY = ? ");
}
if (activityPaginationRequest.getSince() != 0) {
sql.append("AND UPDATED_TIMESTAMP > ? ");
}
if (activityPaginationRequest.getType() != null) {
sql.append("AND TYPE = ? ");
}
if (activityPaginationRequest.getStatus() != null) {
sql.append("AND STATUS = ? ");
}
if (activityPaginationRequest.getStartTimestamp() > 0 && activityPaginationRequest.getEndTimestamp() > 0) {
isTimeDurationFilteringProvided = true;
sql.append("AND CREATED_TIMESTAMP BETWEEN ? AND ? ");
}
int index = 1;
try (PreparedStatement stmt = conn.prepareStatement(sql.toString())) {
stmt.setInt(index++, tenantId);
if (activityPaginationRequest.getDeviceType() != null) {
stmt.setString(index++, activityPaginationRequest.getDeviceType());
}
if (activityPaginationRequest.getDeviceIds() != null && !activityPaginationRequest.getDeviceIds().isEmpty()) {
for (String deviceId : activityPaginationRequest.getDeviceIds()) {
stmt.setString(index++, deviceId);
}
}
if (activityPaginationRequest.getOperationCode() != null) {
stmt.setString(index++, activityPaginationRequest.getOperationCode());
}
if (activityPaginationRequest.getOperationId() > 0) {
stmt.setInt(index++, activityPaginationRequest.getOperationId());
}
if (activityPaginationRequest.getInitiatedBy() != null) {
stmt.setString(index++, activityPaginationRequest.getInitiatedBy());
}
if (activityPaginationRequest.getSince() != 0) {
stmt.setLong(index++, activityPaginationRequest.getSince());
}
if (activityPaginationRequest.getType() != null) {
stmt.setString(index++, activityPaginationRequest.getType().name());
}
if (activityPaginationRequest.getStatus() != null) {
stmt.setString(index++, activityPaginationRequest.getStatus().name());
}
if (isTimeDurationFilteringProvided) {
stmt.setLong(index++, activityPaginationRequest.getStartTimestamp());
stmt.setLong(index, activityPaginationRequest.getEndTimestamp());
}
try (ResultSet rs = stmt.executeQuery()) {
if (rs.next()) {
return rs.getInt("ACTIVITY_COUNT");
}
}
}
} catch (SQLException e) {
String msg = "Error occurred while getting the operation details from the database.";
log.error(msg, e);
throw new OperationManagementDAOException(msg, e);
}
return 0;
}
}

View File

@ -21,6 +21,7 @@ import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import io.entgra.device.mgt.core.device.mgt.common.DeviceIdentifier;
import io.entgra.device.mgt.core.device.mgt.common.operation.mgt.Activity;
import io.entgra.device.mgt.core.device.mgt.common.operation.mgt.DeviceActivity;
import io.entgra.device.mgt.core.device.mgt.common.operation.mgt.ActivityHolder;
import io.entgra.device.mgt.core.device.mgt.common.operation.mgt.ActivityMapper;
import io.entgra.device.mgt.core.device.mgt.common.operation.mgt.ActivityStatus;
@ -38,6 +39,8 @@ import java.io.IOException;
import java.io.ObjectInputStream;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Timestamp;
import java.util.Date;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
@ -136,8 +139,9 @@ public class OperationDAOUtil {
public static OperationResponse getLargeOperationResponse(ResultSet rs) throws
ClassNotFoundException, IOException, SQLException {
OperationResponse response = new OperationResponse();
if (rs.getTimestamp("RECEIVED_TIMESTAMP") != (null)) {
response.setReceivedTimeStamp(rs.getTimestamp("RECEIVED_TIMESTAMP").toString());
if (rs.getTimestamp("RECEIVED_TIMESTAMP") != null) {
Timestamp receivedTimestamp = rs.getTimestamp("RECEIVED_TIMESTAMP");
response.setReceivedTimeStamp(new Date(receivedTimestamp.getTime()).toString());
}
ByteArrayInputStream bais = null;
ObjectInputStream ois = null;
@ -171,8 +175,9 @@ public class OperationDAOUtil {
public static OperationResponse getOperationResponse(ResultSet rs) throws SQLException {
OperationResponse response = new OperationResponse();
if (rs.getTimestamp("RECEIVED_TIMESTAMP") != (null)) {
response.setReceivedTimeStamp(rs.getTimestamp("RECEIVED_TIMESTAMP").toString());
if (rs.getTimestamp("RECEIVED_TIMESTAMP") != null) {
Timestamp receivedTimestamp = rs.getTimestamp("RECEIVED_TIMESTAMP");
response.setReceivedTimeStamp(new Date(receivedTimestamp.getTime()).toString());
}
if (rs.getString("OPERATION_RESPONSE") != null) {
response.setResponse(rs.getString("OPERATION_RESPONSE"));
@ -302,4 +307,27 @@ public class OperationDAOUtil {
throw new OperationManagementDAOException(msg, e);
}
}
public static DeviceActivity populateActivity(ResultSet rs) throws SQLException {
DeviceActivity deviceActivity = new DeviceActivity();
List<OperationResponse> operationResponses = new ArrayList<>();
deviceActivity.setType(DeviceActivity.Type.valueOf(rs.getString("TYPE")));
deviceActivity.setCreatedTimeStamp(new Date(rs.getLong(("CREATED_TIMESTAMP")) * 1000).toString());
deviceActivity.setActivityId(OperationDAOUtil.getActivityId(rs.getInt("OPERATION_ID")));
deviceActivity.setCode(rs.getString("OPERATION_CODE"));
deviceActivity.setOperationId(rs.getInt("OPERATION_ID"));
deviceActivity.setInitiatedBy(rs.getString("INITIATED_BY"));
DeviceIdentifier deviceIdentifier = new DeviceIdentifier();
deviceIdentifier.setId(rs.getString("DEVICE_IDENTIFICATION"));
deviceIdentifier.setType(rs.getString("DEVICE_TYPE"));
deviceActivity.setDeviceIdentifier(deviceIdentifier);
deviceActivity.setStatus(DeviceActivity.Status.valueOf(rs.getString("STATUS")));
if (rs.getInt("UPDATED_TIMESTAMP") != 0) {
deviceActivity.setResponses(operationResponses);
}
deviceActivity.setUpdatedTimestamp(new Date(rs.getLong(("UPDATED_TIMESTAMP")) * 1000).toString());
return deviceActivity;
}
}

View File

@ -39,6 +39,7 @@ import io.entgra.device.mgt.core.device.mgt.common.geo.service.GeoQuery;
import io.entgra.device.mgt.core.device.mgt.common.invitation.mgt.DeviceEnrollmentInvitationDetails;
import io.entgra.device.mgt.core.device.mgt.common.license.mgt.License;
import io.entgra.device.mgt.core.device.mgt.common.operation.mgt.Activity;
import io.entgra.device.mgt.core.device.mgt.common.operation.mgt.DeviceActivity;
import io.entgra.device.mgt.core.device.mgt.common.operation.mgt.Operation;
import io.entgra.device.mgt.core.device.mgt.common.operation.mgt.OperationManagementException;
import io.entgra.device.mgt.core.device.mgt.common.policy.mgt.PolicyMonitoringManager;
@ -1004,6 +1005,11 @@ public interface DeviceManagementProviderService {
int getActivitiesCount(ActivityPaginationRequest activityPaginationRequest)
throws OperationManagementException;
List<DeviceActivity> getDeviceActivities(ActivityPaginationRequest activityPaginationRequest) throws OperationManagementException;
int getDeviceActivitiesCount(ActivityPaginationRequest activityPaginationRequest)
throws OperationManagementException;
License getLicenseConfig (String deviceTypeName) throws DeviceManagementException;
/**

View File

@ -93,6 +93,7 @@ import io.entgra.device.mgt.core.device.mgt.common.license.mgt.LicenseManagement
import io.entgra.device.mgt.core.device.mgt.common.metadata.mgt.Metadata;
import io.entgra.device.mgt.core.device.mgt.common.metadata.mgt.MetadataManagementService;
import io.entgra.device.mgt.core.device.mgt.common.operation.mgt.Activity;
import io.entgra.device.mgt.core.device.mgt.common.operation.mgt.DeviceActivity;
import io.entgra.device.mgt.core.device.mgt.common.operation.mgt.Operation;
import io.entgra.device.mgt.core.device.mgt.common.operation.mgt.OperationManagementException;
import io.entgra.device.mgt.core.device.mgt.common.operation.mgt.OperationManager;
@ -2564,6 +2565,19 @@ public class DeviceManagementProviderServiceImpl implements DeviceManagementProv
.getActivitiesCount(activityPaginationRequest);
}
@Override
public List<DeviceActivity> getDeviceActivities(ActivityPaginationRequest activityPaginationRequest)
throws OperationManagementException {
return DeviceManagementDataHolder.getInstance().getOperationManager().getDeviceActivities(activityPaginationRequest);
}
@Override
public int getDeviceActivitiesCount(ActivityPaginationRequest activityPaginationRequest)
throws OperationManagementException {
return DeviceManagementDataHolder.getInstance().getOperationManager()
.getDeviceActivitiesCount(activityPaginationRequest);
}
@Override
public List<MonitoringOperation> getMonitoringOperationList(String deviceType) {
int tenantId = PrivilegedCarbonContext.getThreadLocalCarbonContext().getTenantId();

View File

@ -1,61 +0,0 @@
<?xml version="1.0" encoding="UTF-8"?>
<!--
~ Copyright (c) 2018 - 2023, Entgra (Pvt) Ltd. (http://www.entgra.io) All Rights Reserved.
~
~ Entgra (Pvt) Ltd. licenses this file to you under the Apache License,
~ Version 2.0 (the "License"); you may not use this file except
~ in compliance with the License.
~ You may obtain a copy of the License at
~
~ http://www.apache.org/licenses/LICENSE-2.0
~
~ Unless required by applicable law or agreed to in writing,
~ software distributed under the License is distributed on an
~ "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
~ KIND, either express or implied. See the License for the
~ specific language governing permissions and limitations
~ under the License.
-->
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<parent>
<artifactId>device-mgt</artifactId>
<groupId>io.entgra.device.mgt.core</groupId>
<version>5.0.0-SNAPSHOT</version>
<relativePath>../pom.xml</relativePath>
</parent>
<modelVersion>4.0.0</modelVersion>
<artifactId>org.wso2.carbon.device.mgt.ui</artifactId>
<packaging>pom</packaging>
<name>WSO2 Carbon - Device Management Base UI</name>
<description>WSO2 Carbon - Device Management Base UI</description>
<url>http://wso2.org</url>
<build>
<plugins>
<plugin>
<artifactId>maven-assembly-plugin</artifactId>
<version>2.5.5</version>
<configuration>
<finalName>${project.artifactId}-${io.entgra.device.mgt.core.version}</finalName>
<appendAssemblyId>false</appendAssemblyId>
<descriptors>
<descriptor>src/assembly/src.xml</descriptor>
</descriptors>
</configuration>
<executions>
<execution>
<id>create-archive</id>
<phase>package</phase>
<goals>
<goal>single</goal>
</goals>
</execution>
</executions>
</plugin>
</plugins>
</build>
</project>

View File

@ -1,48 +0,0 @@
<!--
~ Copyright (c) 2018 - 2023, Entgra (Pvt) Ltd. (http://www.entgra.io) All Rights Reserved.
~
~ Entgra (Pvt) Ltd. licenses this file to you under the Apache License,
~ Version 2.0 (the "License"); you may not use this file except
~ in compliance with the License.
~ You may obtain a copy of the License at
~
~ http://www.apache.org/licenses/LICENSE-2.0
~
~ Unless required by applicable law or agreed to in writing,
~ software distributed under the License is distributed on an
~ "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
~ KIND, either express or implied. See the License for the
~ specific language governing permissions and limitations
~ under the License.
-->
<assembly
xmlns="http://maven.apache.org/plugins/maven-assembly-plugin/assembly/1.1.0"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/plugins/maven-assembly-plugin/assembly/1.1.0 http://maven.apache.org/xsd/assembly-1.1.0.xsd">
<id>src</id>
<formats>
<format>zip</format>
</formats>
<includeBaseDirectory>false</includeBaseDirectory>
<baseDirectory>${basedir}/src</baseDirectory>
<fileSets>
<fileSet>
<!-- CDMF base app -->
<directory>${basedir}/src/main/resources/jaggeryapps/devicemgt</directory>
<outputDirectory>/jaggeryapps/devicemgt-cdmf/</outputDirectory>
<useDefaultExcludes>true</useDefaultExcludes>
</fileSet>
<fileSet>
<!-- UUF framework app -->
<directory>${basedir}/src/main/resources/jaggeryapps/uuf-template-app</directory>
<outputDirectory>/jaggeryapps/uuf-template-app/</outputDirectory>
<useDefaultExcludes>true</useDefaultExcludes>
</fileSet>
<fileSet>
<directory>${basedir}/src/main/resources/jaggery-modules</directory>
<outputDirectory>/jaggery-modules/</outputDirectory>
<useDefaultExcludes>true</useDefaultExcludes>
</fileSet>
</fileSets>
</assembly>

View File

@ -1,56 +0,0 @@
<!--
~ Copyright (c) 2018 - 2023, Entgra (Pvt) Ltd. (http://www.entgra.io) All Rights Reserved.
~
~ Entgra (Pvt) Ltd. licenses this file to you under the Apache License,
~ Version 2.0 (the "License"); you may not use this file except
~ in compliance with the License.
~ You may obtain a copy of the License at
~
~ http://www.apache.org/licenses/LICENSE-2.0
~
~ Unless required by applicable law or agreed to in writing,
~ software distributed under the License is distributed on an
~ "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
~ KIND, either express or implied. See the License for the
~ specific language governing permissions and limitations
~ under the License.
-->
<module name="utils" xmlns="http://wso2.org/projects/jaggery/module.xml">
<script>
<name>reflection</name>
<path>scripts/reflection/reflection.js</path>
</script>
<script>
<name>file</name>
<path>scripts/file/file.js</path>
</script>
<script>
<name>patterns</name>
<path>scripts/patterns/patterns.js</path>
</script>
<script>
<name>xml</name>
<path>scripts/xml/xml.js</path>
</script>
<script>
<name>request</name>
<path>scripts/request/request.js</path>
</script>
<script>
<name>response</name>
<path>scripts/response/response.js</path>
</script>
<script>
<name>time</name>
<path>scripts/time/time.js</path>
</script>
<script>
<name>url</name>
<path>scripts/url/url.js</path>
</script>
<script>
<name>exception</name>
<path>scripts/exception/exception.js</path>
</script>
</module>

View File

@ -1,64 +0,0 @@
/*
* Copyright (c) 2018 - 2023, Entgra (Pvt) Ltd. (http://www.entgra.io) All Rights Reserved.
*
* Entgra (Pvt) Ltd. licenses this file to you under the Apache License,
* Version 2.0 (the "License"); you may not use this file except
* in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
/**
* Description: The response of the currently invoked api enpoint is organized
*/
var exception = {};
var log = new Log('exception_module');
(function(exception) {
/**
*
* @param message The exception description
* @param code HTTP STATUS CODE related to the exception
* @return The error object
*/
exception.buildExceptionObject = function(message, code) {
var error = {};
error.message = message;
error.code = code;
return error;
};
exception.handleError = function (exception, type, code){
var constants = require('rxt').constants;
if (type == constants.THROW_EXCEPTION_TO_CLIENT) {
log.debug(exception);
var e = exceptionModule.buildExceptionObject(exception, code);
throw e;
} else if (type == constants.LOG_AND_THROW_EXCEPTION) {
log.error(exception);
throw exception;
} else if (type == constants.LOG_EXCEPTION_AND_TERMINATE) {
log.error(exception);
var msg = 'An error occurred while serving the request!';
var e = exceptionModule.buildExceptionObject(msg, constants.STATUS_CODES.INTERNAL_SERVER_ERROR);
throw e;
} else if (type == constants.LOG_EXCEPTION_AND_CONTINUE) {
log.debug(exception);
}
else {
log.error(exception);
throw e;
}
};
}(exception))

View File

@ -1,166 +0,0 @@
/*
* Copyright (c) 2018 - 2023, Entgra (Pvt) Ltd. (http://www.entgra.io) All Rights Reserved.
*
* Entgra (Pvt) Ltd. licenses this file to you under the Apache License,
* Version 2.0 (the "License"); you may not use this file except
* in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
var file = {};
(function() {
var log = new Log('utils-file');
var CONTENT_MAP = {
'js': 'application/javascript',
'css': 'text/css',
'csv': 'text/csv',
'html': 'text/html',
'json': 'application/json',
'png': 'image/png',
'jpeg': 'image/jpeg',
'gif': 'image/gif',
'svg': 'image/svg+xml',
'ttf': 'application/x-font-ttf',
'eot': 'application/vnd.ms-fontobject',
'woff': 'application/font-woff',
'otf': 'application/x-font-otf',
'zip': 'application/zip',
'xml': 'text/xml',
'xhtml': 'application/xhtml+xml',
'pdf': 'application/pdf'
};
/**
* The function checks whether a directory contains a particular file
* @param dir The directory in which the file must be checked
* @param file A File object if the file exists,else null
*/
file.getFileInDir = function(dir, fileName) {
var isFilePresent = false;
var files = dir.listFiles();
for (var index in files) {
if (files[index].getName() == fileName) {
return files[index];
}
}
return null;
};
/**
* The function returns the file extension of a filename
* @param file
* @return: The extension of the file
*/
file.getExtension = function(file) {
var baseFileName = file.getName();
//Break up the name by .
var baseNameComponents = baseFileName.split('.');
var extension = baseNameComponents[baseNameComponents.length - 1];
return extension;
};
/**
* The function obtains the MIME type based on the extension
* @param The extension
* @return The mime type
*/
file.getMimeType = function(extension) {
return CONTENT_MAP[extension];
};
/**
* The function returns the name of the file without the file extension
* @param file A file object
* @return: The name of the file without the extension
*/
file.getFileName = function(file) {
//Get the name of the file
var baseFileName = file.getName();
//Break up the name by .
var baseNameComponents = baseFileName.split('.');
//Get all of the components except the last one
baseNameComponents.splice(baseNameComponents.length - 1, 1);
return baseNameComponents.join('.');
};
/**
* The function returns the contents of a directory as a JSON object.The name of the
* file is used as the property names without the extensions.
* NOTE: The method will not traverse sub folders.
* @param The directory to be inspected
* @return A JSON object which contains the files in the directory
*/
file.getDirectoryContents = function(dir) {
var dirContents = {};
//Check if it is a directory
if (!dir.isDirectory()) {
log.info('Not a directory');
return dirContents;
}
//Obtain a list of all files
var files = this.getAllFiles(dir);
var name;
log.info('Files: ' + files);
//Create the directory object with each file been a property
for (var index in files) {
dirContents[this.getFileName(files[index])] = files[index];
}
return dirContents;
};
/**
* The function obtains a list of files that are not directories
* @param dir The directory to be inspected
* @return An array with all of the files in the directory
*/
file.getAllFiles = function(dir) {
var filesInDir = [];
if (!dir.isDirectory()) {
return filesInDir;
}
//Obtain a list of all files
var files = dir.listFiles();
for (var index in files) {
log.info('Checking file: ' + files[index].getName());
//Check if the file is a directory
if (!files[index].isDirectory()) {
filesInDir.push(files[index]);
}
}
return filesInDir;
};
/**
* The function returns a list of all file names in a directory
* @param dir The directory to be inspected
* @return {An array containing the name of all files in a directory
*/
file.getAllFileNames = function(dir) {
var files = dir.listFiles();
var list = [];
var fileName;
for (var index in files) {
if (files[index].isDirectory()) {
fileName=this.getFileName(files[index].getName());
list.push(fileName);
}
}
return list;
};
/**
* The function returns a list of all sub directories in a given directory
* @param dir The root directory
* @return: An array containing all sub directories
*/
file.getAllSubDirs = function(dir) {
var files = dir.listFiles();
var subDirs = [];
for (var index in files) {
if (files[index].isDirectory()) {
subDirs.push(files[index]);
}
}
return subDirs;
};
}());

View File

@ -1,127 +0,0 @@
/*
* Copyright (c) 2018 - 2023, Entgra (Pvt) Ltd. (http://www.entgra.io) All Rights Reserved.
*
* Entgra (Pvt) Ltd. licenses this file to you under the Apache License,
* Version 2.0 (the "License"); you may not use this file except
* in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
var patterns = {};
(function () {
var DEF_ERR_ARITY = 3;
var DEF_HANDLE_ARITY = 2;
var log = new Log('utils.patterns.GenericPipe');
function GenericPipe(options) {
this.errHandlerArity = DEF_ERR_ARITY || options.errArity;
this.handlerArity = DEF_HANDLE_ARITY || options.handlerArity;
this.plugins = [];
this.finalHandler = function () {
};
}
/**
*The function registers the provided plugin
*/
GenericPipe.prototype.plug = function (plugin, options) {
var options = options || {};
//Only a function
if (plugin instanceof Function) {
this.plugins.push({
handle: plugin,
options: options
});
}
//Is it a plugin object
else if (plugin instanceof Object) {
plugin.options = options;
this.plugins.push(plugin);
}
return this;
};
GenericPipe.prototype.finally = function (plugin) {
this.finalHandler = plugin;
return this;
};
GenericPipe.prototype.resolve = function (data, req, res, session) {
var context = {};
context.req = req;
context.res = res;
context.session = session;
context.data = data;
handle(context, this.plugins, this.errHandlerArity, this.handlerArity, this.finalHandler);
};
var handle = function (context, plugins, errArity, handlerArity, finallyHandler) {
var index = 0;
var currentPlugin;
var recursiveHandle = function (err) {
currentPlugin = plugins[index];
index++;
//Check if there is a plugin
if (!currentPlugin) {
//log.warn('No plugin found at index: ' + index);
return;
}
//Populate the options object for the plugin
context.options=currentPlugin.options;;
//Check if an error has been provided
if (err) {
//Can the current plugin handle the err
if (currentPlugin.handle.length == errArity) {
try {
currentPlugin.handle(err, context,recursiveHandle);
}
catch (e) {
recursiveHandle(e);
}
}
else {
recursiveHandle(err);
}
}
//There is no error so try to invoke the current plugin
else {
if (currentPlugin.handle.length == handlerArity) {
try {
currentPlugin.handle(context,recursiveHandle);
} catch (e) {
recursiveHandle(e);
}
}
else {
recursiveHandle();
}
}
};
recursiveHandle();
finallyHandler(context);
};
patterns.GenericPipe = GenericPipe;
}());

View File

@ -1,229 +0,0 @@
/*
* Copyright (c) 2018 - 2023, Entgra (Pvt) Ltd. (http://www.entgra.io) All Rights Reserved.
*
* Entgra (Pvt) Ltd. licenses this file to you under the Apache License,
* Version 2.0 (the "License"); you may not use this file except
* in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
var reflection = {};
/**
* Description: The script encapsulates any reflection related utility functions
*/
(function() {
var log = new Log('utils-reflection');
reflection.copyPropKeys = function(from, to) {
for (var key in from) {
if (from.hasOwnProperty(key)) {
to[key] = '';
}
}
return to;
};
/**
* The function recursively copies all property keys in an object
* @param from
* @param to
*/
reflection.copyAllPropKeys = function(from, to) {
recurse(from, to, function(from, to, key) {
if (from[key] instanceof Object) {
to[key] = from[key];
} else {
to[key] = null;
}
});
};
reflection.copyAllPropValues = function(from, to) {
recurse(from, to, function(from, to, key) {
//Create an instance if the property does not exist
if (!to[key]) {
to[key] = {};
}
//Copy the values over
if (!(from[key] instanceof Object)) {
to[key] = from[key];
} else {
log.debug('Not copying values of key: ' + key);
}
});
};
/**
* The function will only copy public properties
* @param from
* @param to
*/
reflection.copyPublicPropValues = function(from, to) {
recurse(from, to, function(from, to, key) {
//Ignore any hidden properties
if (key.charAt(0) == '_') {
log.warn('Drop key: ' + key);
return;
}
//Create an instance if the property does not exist
if (!to[key]) {
to[key] = {};
}
//Copy the values over
if (!(from[key] instanceof Object)) {
to[key] = from[key];
} else {
log.warn('Not copying values of key: ' + key);
}
});
};
reflection.inspect = function(from, to, cb) {
recurse(from, to, cb);
};
/**
* The function recursively traverses an object and then invokes the provided
* callback
* @param root
* @param clone
* @param cb
*/
var recurse = function(root, clone, cb) {
var key;
//Check if the root is an object
if (!(root instanceof Object)) {
return;
} else {
var keys = Object.keys(root);
//Go through all the other keys in the current root
for (var index in keys) {
key = keys[index];
cb(root, clone, key);
recurse(root[key], clone[key], cb);
}
}
};
reflection.copyProps = function(from, to) {
for (var key in from) {
if (from.hasOwnProperty(key)) {
to[key] = from[key];
}
}
return to;
};
reflection.getProps = function(obj) {
var props = {};
for (var key in obj) {
if (!(obj[key] instanceof Function)) {
props[key] = obj[key];
}
}
return props;
};
reflection.printProps = function(obj) {
for (var key in obj) {
if (obj.hasOwnProperty(key)) {
log.info('key: ' + key);
}
}
};
/**
* The function determines if a property is hidden based on _
* @param key
* @returns {boolean}
*/
reflection.isHiddenProp = function(key) {
if (key == '') {
return false;
}
return (key.charAt(0) == '_') ? true : false;
};
var getDiff = function(a, b, diff) {};
/**
* The function calculates the differences between two simple JSON objects
* @param a The object with which b is compared
* @param b The target of the comparison
* @return An object which records the differences between the two objects
*/
reflection.diff = function(a, b) {};
/**
* The function merges the two provided objects to create a new
* object.In the case where b has the same property as a; the property of b
* will have precedence
* @param {[type]} a [description]
* @param {[type]} b [description]
* @return A new object having the properties of both object a and b
*/
reflection.merge = function(a, b) {
var newObj = {};
//Copy the properties of a first
for (var key in a) {
newObj[key] = b[key];
}
//Override with the properties of b
for (var key in b) {
newObj[key] = b[key];
}
return newObj;
};
/**
* The function allows a child class to override a select set of methods of
* a parent class.The original methods of the parent can be accessed
* using the this._super keyword
* @param {[type]} parent The parent class instance to be overriden
* @param {[type]} child The child class instance containing methods which will override the parent
*/
reflection.override = function(parent, child) {
//Make a clone of the parent
var super = parse(stringify(parent));
for (var childKey in child) {
for (var parentKey in parent) {
//Only override those methods that are common
if (childKey === parentKey) {
var parentPtr = parent[parentKey];
var childPtr = child[childKey];
//Update the clone with the old parent method
super[parentKey] = parentPtr;
parent[parentKey] = childPtr;
/*parent[parentKey] = function() {
var result=childPtr.apply(this, arguments)||null;
return result;
};*/
}
}
}
//Allow the child object to call methods of the parent
parent._super = super;
};
reflection.overrideAll=function(parent,child){
//Make a clone of the parent
var super = parse(stringify(parent));
for (var childKey in child) {
for (var parentKey in parent) {
//Only override those methods that are common
if ( (child.hasOwnProperty(childKey))&&(parent.hasOwnProperty(parentKey)) ) {
var parentPtr = parent[parentKey];
var childPtr = child[childKey];
//Update the clone with the old parent method
super[parentKey] = parentPtr;
parent[parentKey] = childPtr;
/*parent[parentKey] = function() {
var result=childPtr.apply(this, arguments)||null;
return result;
};*/
}
}
}
//Allow the child object to call methods of the parent
parent._super = super;
};
reflection.isArray = function(object) {
if (Object.prototype.toString.call(object) === '[object Array]') {
return true;
}
return false;
};
}());

View File

@ -1,56 +0,0 @@
/*
* Copyright (c) 2018 - 2023, Entgra (Pvt) Ltd. (http://www.entgra.io) All Rights Reserved.
*
* Entgra (Pvt) Ltd. licenses this file to you under the Apache License,
* Version 2.0 (the "License"); you may not use this file except
* in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
var request = {};
(function(request) {
var hasOwnProperty = function(obj, element) {
return Object.prototype.hasOwnProperty.call(obj, element);
};
var isObject = function(object) {;
return typeof object === 'object';
};
/*
* ECMA Standard (ECMA-262 : 5.1 Edition)*/
var decodes = function(encodedURI) {
return decodeURIComponent(encodedURI);
};
request.getQueryOptions = function(queryString) {
var opt={};
var sep = opt.sep || '&',
assign = opt.assign || '=',
compoArray = [];
var obj = {};
var decodedURI = decodes(queryString);
decodedURI.split(sep).forEach(function(comp) {
comp.split(assign).some(function(element, index, array) {
if (hasOwnProperty(obj, element.toString())) {
compoArray.push(obj[element]);
compoArray.push(array[1]);
obj[element] = compoArray;
} else {
Object.defineProperty(obj, element, {
enumerable: true,
writable: true,
value: array[1]
});
}
return true;
});
});
return obj;
};
}(request))

View File

@ -1,98 +0,0 @@
/*
* Copyright (c) 2018 - 2023, Entgra (Pvt) Ltd. (http://www.entgra.io) All Rights Reserved.
*
* Entgra (Pvt) Ltd. licenses this file to you under the Apache License,
* Version 2.0 (the "License"); you may not use this file except
* in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
/**
* Description: The response of the currently invoked api endpoint is organized
*/
var response = {};
var log = new Log("response");
(function(response) {
/**
* Build Error response
* @param resp jaggery-response object to retrieve to client
* @param code status code
* @param message message to the client side
* @return return response
*/
response.buildErrorResponse = function(resp,code,message) {
var content={};
content.error = message;
resp = processResponse(resp,code,content);
return resp;
};
/**
* Build success response
* @param resp jaggery response object
* @param code status code
* @param data the result to client
* @return return response
*/
response.buildSuccessResponse= function(resp, code, data){
var content={};
content.data = data;
resp = processResponse(resp,code,content);
return resp;
};
/**
* process General response
* @param resp jaggery response
* @param code status code
* @param data success result
* @return resp jaggery response
*/
response.buildSuccessResponseForRxt= function(resp, code, data){
resp.status = code;
resp.content = data;
return resp;
};
/**
* General response builder
* @param resp jaggery response
* @param code status code
* @param content what ever the content to be sent as response
* @return resp jaggery response
*/
function processResponse(resp, code, content){
resp.status = code;
resp.contentType = 'application/json';
resp.content = content;
return resp;
};
/**
*
* @param resp
* @param code
* @param data
* @return The http response
*/
response.buildSuccessResponseForRxt= function(resp, code, data){
resp.contentType = 'application/json';
resp.status = code;
resp.content = data;
return resp;
};
}(response))

View File

@ -1,34 +0,0 @@
/*
* Copyright (c) 2018 - 2023, Entgra (Pvt) Ltd. (http://www.entgra.io) All Rights Reserved.
*
* Entgra (Pvt) Ltd. licenses this file to you under the Apache License,
* Version 2.0 (the "License"); you may not use this file except
* in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
var time = {};
(function(time) {
time.getCurrentTime = function(dateLength) {
var dateLength=dateLength||20;
var now = new String(new Date().valueOf());
var length = now.length;
var prefix = dateLength;
var onsetVal = '';
if (length != prefix) {
var onset = prefix - length;
for (var i = 0; i < onset; i++) {
onsetVal += '0';
}
}
return onsetVal + now;
};
}(time));

View File

@ -1,46 +0,0 @@
/*
* Copyright (c) 2018 - 2023, Entgra (Pvt) Ltd. (http://www.entgra.io) All Rights Reserved.
*
* Entgra (Pvt) Ltd. licenses this file to you under the Apache License,
* Version 2.0 (the "License"); you may not use this file except
* in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
var url = {};
(function() {
var log=new Log('utils-url');
url.popServerDetails = function(obj) {
var process = require('process');
var localIP = process.getProperty('server.host');
var httpPort = process.getProperty('http.port');
var httpsPort = process.getProperty('https.port');
var value = '';
var carbonLocalIP = process.getProperty('carbon.local.ip');
for (var key in obj) {
if (obj.hasOwnProperty(key)) {
value = obj[key];
if ((typeof value === 'string') && value.indexOf('%https.host%') > -1) {
value=value.replace('%https.host%', 'https://' + localIP + ':' + httpsPort);
} else if ((typeof value === 'string') && value.indexOf('%http.host%') > -1) {
value=value.replace('%http.host%', 'http://' + localIP + ':' + httpPort);
} else if ((typeof value === 'string') && value.indexOf('%https.carbon.local.ip%') > -1) {
value=value.replace('%https.carbon.local.ip%', 'https://' + carbonLocalIP + ':' + httpsPort);
} else if ((typeof value === 'string') && value.indexOf('%http.carbon.local.ip%') > -1) {
value=value.replace('%http.carbon.local.ip%', 'http://' + carbonLocalIP + ':' + httpPort);
}
obj[key] = value;
}
}
return obj;
};
}(url));

View File

@ -1,137 +0,0 @@
/*
* Copyright (c) 2018 - 2023, Entgra (Pvt) Ltd. (http://www.entgra.io) All Rights Reserved.
*
* Entgra (Pvt) Ltd. licenses this file to you under the Apache License,
* Version 2.0 (the "License"); you may not use this file except
* in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
var xml = {};
(function () {
var log=new Log('util.xml')
/*
The method is used to create a JSON object using
an xml object.
@xmlElement: An xml element object to be processed
@return: A pseudo object containing the properties of the
xml element.
*/
var createJSONObject = function (xmlElement) {
var pseudo = {};
//Extract all attributes
var attributes = xmlElement.@*;
//Fill the pseudo object with the attributes of the element
for (var attributeKey in attributes) {
var attribute = attributes[attributeKey];
pseudo[attribute.localName()] = attribute.toString();
}
return pseudo;
};
/*
The function converts an E4X Xml object to a JSON object
This function has been adapted from the work of Oleg Podsechin available at
https://gist.github.com/olegp/642667
It uses a slightly modified version of his algorithm , therefore
all credit should be attributed to Oleg Podsechin.
IMPORTANT:
1. It does not create a 1..1 mapping due to the differences
between Xml and JSON.It is IMPORTANT that you verify the structure
of the object generated before using it.
2. The input xml object must not contain the xml header information
This is a known bug 336551 (Mozilla Developer Network)
Source: https://developer.mozilla.org/en/docs/E4X
Please remove the header prior to sending the xml object for processing.
@root: A starting element in an E4X Xml object
@return: A JSON object mirroring the provided Xml object
*/
var recursiveConvertE4XtoJSON = function (root) {
log.debug('Root: ' + root.localName());
//Obtain child nodes
var children = root.*;
//The number of children
var numChildren = children.length();
//No children
if (numChildren == 0) {
//Extract contents
return createJSONObject(root);
}
else {
//Create an empty object
var rootObject = createJSONObject(root);
//Could be multiple children
for (var childElementKey in children) {
var child = children[childElementKey];
log.debug('Examining child: ' + child.localName());
//If the child just contains a single value then stop
if (child.localName() == undefined) {
log.debug('Child is undefined: ' + child.toString());
//Change the object to just a key value pair
rootObject[root.localName()] = child.toString();
return rootObject;
}
//Make a recursive call to construct the child element
var createdObject = recursiveConvertE4XtoJSON(child);
log.debug('Converted object: ' + stringify(createdObject));
//Check if the root object has the property
if (rootObject.hasOwnProperty(child.localName())) {
log.debug('key: ' + child.localName() + ' already present.');
rootObject[child.localName()].push(createdObject);
}
else {
log.debug('key: ' + child.localName() + ' not present.');
rootObject[child.localName()] = [];
rootObject[child.localName()].push(createdObject);
}
}
log.debug('root: ' + root.localName());
return rootObject;
}
};
/**
* The function is used to convert an E4X xml to JSON
* @param root
*/
xml.convertE4XtoJSON = function (root) {
return recursiveConvertE4XtoJSON(root);
};
}());

View File

@ -1,113 +0,0 @@
<%
/*
* Copyright (c) 2015, WSO2 Inc. (http://www.wso2.org) All Rights Reserved.
*
* WSO2 Inc. licenses this file to you under the Apache License,
* Version 2.0 (the "License"); you may not use this file except
* in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND,
* either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
var log = new Log("api/data-tables-invoker-api.jag");
var uri = request.getRequestURI();
var uriMatcher = new URIMatcher(String(uri));
var devicemgtProps = require("/app/modules/conf-reader/main.js")["conf"];
var serviceInvokers = require("/app/modules/oauth/token-protected-service-invokers.js")["invokers"];
var utility = require("/app/modules/utility.js")["utility"];
var deviceModule = require("/app/modules/business-controllers/device.js")["deviceModule"];
var EnrolmentInfo = Packages.io.entgra.device.mgt.core.device.mgt.common.EnrolmentInfo;
var DTYPE_CONF_DEVICE_TYPE_KEY = "deviceType";
var DTYPE_CONF_DEVICE_TYPE_LABEL_KEY = "label";
function appendQueryParam (url, queryParam , value) {
if (url.indexOf("?") > 0) {
return url + "&" + queryParam + "=" + value;
}
return url + "?" + queryParam + "=" + value;
}
if (uriMatcher.match("/{context}/api/data-tables/invoker/filters")) {
var result = {};
var i;
//Fetching Status types
var status = EnrolmentInfo.Status.values();
var statusArr = [];
for(i = 0; i < status.length; i++){
statusArr.push(status[i].name());
}
result.status = statusArr;
//Fetching Ownership types
var ownership = EnrolmentInfo.OwnerShip.values();
var ownershipArr = [];
for(i = 0; i < ownership.length; i++){
ownershipArr.push(ownership[i].name());
}
result.ownership = ownershipArr;
//Fetching Device Types
result.deviceTypes = [];
var deviceTypesRes = deviceModule.getDeviceTypes();
if (deviceTypesRes.status === "success") {
var deviceTypes = deviceTypesRes["content"];
for (i = 0; i < deviceTypes.length; i++) {
var deviceTypeName = deviceTypes[i].name;
var deviceTypeLabel = deviceTypeName.charAt(0).toUpperCase() + deviceTypeName.slice(1);
var configs = utility.getDeviceTypeConfig(deviceTypeLabel);
if (configs) {
if (configs[DTYPE_CONF_DEVICE_TYPE_KEY][DTYPE_CONF_DEVICE_TYPE_LABEL_KEY]) {
deviceTypeLabel = configs[DTYPE_CONF_DEVICE_TYPE_KEY][DTYPE_CONF_DEVICE_TYPE_LABEL_KEY];
}
}
result.deviceTypes.push({"name": deviceTypeLabel, "value": deviceTypeName});
}
}
//Adding policy compliance
result.compliance = ["MONITOR", "ENFORCE", "WARN", "BLOCK"];
result.depStatus = ["Empty", "Assigned", "Pushed", "Removed"];
response["status"] = 200;
response["content"] = result;
response["contentType"] = "application/json";
} else if (uriMatcher.match("/{context}/api/data-tables/invoker")) {
var url = request.getParameter("url");
var targetURL = devicemgtProps["httpsURL"] + request.getParameter("url");
//noinspection JSUnresolvedFunction getAllParameters
var allParams = request.getAllParameters();
for (var allParamsKey in allParams) {
if (allParams.hasOwnProperty(allParamsKey)) {
if (allParamsKey == "limit" || allParamsKey == "offset") {
targetURL = appendQueryParam(targetURL, allParamsKey, allParams[allParamsKey]);
} else if (allParamsKey == "filter") {
if (allParams[allParamsKey]) {
var searchPayload = JSON.parse(allParams[allParamsKey]);
for (var searchPayloadKey in searchPayload) {
if (searchPayload.hasOwnProperty(searchPayloadKey)) {
targetURL = appendQueryParam(targetURL, searchPayloadKey, searchPayload[searchPayloadKey]);
}
}
}
}
}
}
serviceInvokers.XMLHttp.get(
targetURL,
// response callback
function (backendResponse) {
response["status"] = backendResponse["status"];
response["content"] = utility.encodeJson(backendResponse["responseText"]);
response["contentType"] = "application/json";
}
);
}

View File

@ -1,227 +0,0 @@
<%
/*
* Copyright (c) 2016, WSO2 Inc. (http://www.wso2.org) All Rights Reserved.
*
* WSO2 Inc. licenses this file to you under the Apache License,
* Version 2.0 (the "License"); you may not use this file except
* in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
var uri = request.getRequestURI();
var uriMatcher = new URIMatcher(String(uri));
var log = new Log("api/device-api.jag");
var constants = require("/app/modules/constants.js");
var deviceModule = require("/app/modules/business-controllers/device.js")["deviceModule"];
var utility = require("/app/modules/utility.js").utility;
var devicemgtProps = require("/app/modules/conf-reader/main.js")["conf"];
var userModule = require("/app/modules/business-controllers/user.js")["userModule"];
var serviceInvokers = require("/app/modules/oauth/token-protected-service-invokers.js")["invokers"];
var user = session.get(constants.USER_SESSION_KEY);
var result;
response.contentType = 'application/json';
if (!user) {
response.sendRedirect("/devicemgt/login?#login-required");
exit();
} else {
if (uriMatcher.match("/{context}/api/devices/sketch/download")) {
// works as a proxy to pass the relavant query string to back end api.
var queryString = request.getQueryString();
if (!queryString) {
queryString = "";
} else {
queryString = "?" + queryString;
}
var deviceType = request.getParameter("deviceType"); // need a better solution here
deviceTypeConfig = utility.getDeviceTypeConfig(deviceType);
if (deviceTypeConfig && deviceTypeConfig.deviceType.downloadAgentUri) {
hearders = [{"name": constants["ACCEPT_IDENTIFIER"], "value": constants["APPLICATION_ZIP"]}];
sketchDownloadEndPoint = devicemgtProps["httpsURL"] + "/" + deviceTypeConfig.deviceType.downloadAgentUri;
serviceInvokers.HttpClient.get(sketchDownloadEndPoint + queryString, function (responsePayload, responseHeaders) {
if (responseHeaders) {
for (var i = 0; i < responseHeaders.length; i++) {
var header = responseHeaders[i];
var headerName = String(header.getName());
var headerValue = String(header.getValue());
response.addHeader(headerName, headerValue);
}
var streamObject = new Stream(responsePayload);
print(streamObject);
} else {
return responsePayload;
}
}, function (responsePayload) {
log.error(responsePayload);
var response = {};
response["status"] = "error";
return response;
}
, hearders);
} else {
result = 400;
}
} else if (uriMatcher.match("/{context}/api/devices/sketch/generate_link")) {
if (!request.getContent()){
log.error("Request Payload Is Empty");
// HTTP status code 400 refers to - Bad request.
result = 400;
} else{
deviceType = request.getContent()["deviceType"];
queryString = "?deviceName=" + request.getContent()["deviceName"] +"&deviceType="+
request.getContent()["deviceType"]+"&sketchType="+request.getContent()["sketchType"];
deviceTypeConfig = utility.getDeviceTypeConfig(deviceType);
if (deviceTypeConfig && deviceTypeConfig.deviceType.downloadAgentUri) {
sketchDownloadEndPoint = devicemgtProps["httpsURL"] + "/" + deviceTypeConfig.deviceType.downloadAgentUri;
var requestUrl = sketchDownloadEndPoint + queryString
result = "curl -k -o "+request.getContent()["deviceName"]+".zip -H \"Authorization: Bearer "
+JSON.parse(session.get(constants["TOKEN_PAIR"])).accessToken+"\" " +"'"+requestUrl+"'";
} else {
// HTTP status code 400 refers to - Bad request.
result = 400;
}
}
} else if (uriMatcher.match("/{context}/api/devices/all")) {
result = deviceModule.getOwnDevices();
} else if (uriMatcher.match("/{context}/api/devices/count")) {
var count = deviceModule.getOwnDevicesCount().data;
result = count.toString();
} else if (uriMatcher.match("/{context}/api/devices/types")) {
result = deviceModule.listDeviceTypes();
} else if (uriMatcher.match("/{context}/api/devices/{deviceType}/{deviceId}/remove")) {
var elements = uriMatcher.elements();
var deviceId = elements.deviceId;
var deviceType = elements.deviceType;
result = deviceModule.removeDevice(deviceType, deviceId);
} else if (uriMatcher.match("/{context}/api/devices/{deviceType}/{deviceId}/update")) {
var elements = uriMatcher.elements();
var deviceId = elements.deviceId;
var deviceType = elements.deviceType;
var deviceName = request.getParameter("name");
result = deviceModule.updateDevice(deviceType, deviceId, deviceName);
} else if (uriMatcher.match("/{context}/api/devices")) {
var url = request.getParameter("url");
var draw = request.getParameter("draw");
var length = request.getParameter("length");
var start = request.getParameter("start");
var search = request.getParameter("search[value]");
var deviceName = request.getParameter("columns[1][search][value]");
var owner = request.getParameter("columns[2][search][value]");
var status = request.getParameter("columns[3][search][value]");
var platform = request.getParameter("columns[4][search][value]");
var ownership = request.getParameter("columns[5][search][value]");
var targetURL;
function appendQueryParam (url, queryParam , value) {
if (url.indexOf("?") > 0) {
return url + "&" + queryParam + "=" + value;
}
return url + "?" + queryParam + "=" + value;
}
targetURL = devicemgtProps.httpsURL + request.getParameter("url");
targetURL = appendQueryParam(targetURL, "draw", draw);
targetURL = appendQueryParam(targetURL, "start", start);
targetURL = appendQueryParam(targetURL, "length", length);
if (search && search !== "") {
targetURL = appendQueryParam(targetURL, "search", search);
}
if (deviceName && deviceName !== "") {
targetURL = appendQueryParam(targetURL, "device-name", deviceName);
}
if (owner && owner !== "") {
targetURL = appendQueryParam(targetURL, "user", owner);
}
if (status && status !== "") {
targetURL = appendQueryParam(targetURL, "status", status);
}
if (platform && platform !== "") {
targetURL = appendQueryParam(targetURL, "type", platform);
}
if (ownership && ownership !== "") {
targetURL = appendQueryParam(targetURL, "ownership", ownership);
}
serviceInvokers.XMLHttp.get(
targetURL, function (responsePayload) {
response.status = 200;
result = responsePayload;
},
function (responsePayload) {
response.status = responsePayload.status;
result = responsePayload.responseText;
});
} else if (uriMatcher.match("/{context}/api/devices/")) {
if (userModule.isAuthorized("/permission/admin/device-mgt/devices/list")) {
result = deviceModule.listDevices();
} else {
response.sendError(403);
}
} else if (uriMatcher.match("/{context}/api/devices/{type}/{deviceId}")) {
elements = uriMatcher.elements();
deviceId = elements.deviceId;
type = elements.type;
if (userModule.isAuthorized("/permission/admin/device-mgt/devices/list")) {
result = deviceModule.viewDevice(type, deviceId);
}else {
response.sendError(403);
}
} else if (uriMatcher.match("/{context}/api/devices/agent/{type}/{deviceId}/config")) {
elements = uriMatcher.elements();
deviceId = elements.deviceId;
type = elements.type;
operation = elements.operation;
if (userModule.isAuthorized("/permission/admin/device-mgt/devices/owning-device")) {
result = deviceModule.getDeviceAgentConfig(type, deviceId);
if (!result) {
response.sendError(500);
}
} else {
response.sendError(403);
}
} else if (uriMatcher.match("{context}/api/devices/{type}/{deviceId}/{operation}")) {
elements = uriMatcher.elements();
deviceId = elements.deviceId;
type = elements.type;
operation = elements.operation;
if (userModule.isAuthorized("/permission/admin/device-mgt/devices/operation")) {
result = deviceModule.performOperation(deviceId, operation, [], type);
} else {
response.sendError(403);
}
}
}
// Returning the result.
if (result) {
print(result);
}
%>

View File

@ -1,138 +0,0 @@
<%
var log = new Log("api/enterprise.jag");
var uri = request.getRequestURI();
var uriMatcher = new URIMatcher(String(uri));
var constants = require("/app/modules/constants.js");
var devicemgtProps = require("/app/modules/conf-reader/main.js")["conf"];
var userModule = require("/app/modules/business-controllers/user.js")["userModule"];
var restAPIRequestDetails = request.getContent();
var result;
var user = session.get(constants.USER_SESSION_KEY);
// This checks if the session is valid
getAccessToken = function() {
if (session) {
var tokenPair = session.get(constants["TOKEN_PAIR"]);
if (tokenPair) {
return parse(tokenPair)["accessToken"];
}
}
return null;
};
callBackend = function(url, token, method, payload) {
var xmlHttpRequest = new XMLHttpRequest();
xmlHttpRequest.open(method, url);
xmlHttpRequest.setRequestHeader(constants["AUTHORIZATION_HEADER"], constants["BEARER_PREFIX"] + token);
xmlHttpRequest.setRequestHeader(constants["CONTENT_TYPE_IDENTIFIER"], constants["APPLICATION_JSON"]);
xmlHttpRequest.setRequestHeader(constants["ACCEPT_IDENTIFIER"], constants["APPLICATION_JSON"]);
if (payload) {
xmlHttpRequest.send(payload);
} else {
xmlHttpRequest.send();
}
response["status"] = xmlHttpRequest["status"];
if (xmlHttpRequest["responseText"]) {
result = xmlHttpRequest["responseText"];
response["content"] = xmlHttpRequest["responseText"];
}
};
var accessToken = getAccessToken();
if (!user || accessToken == null) {
response.sendRedirect("/devicemgt/login?#login-required");
exit();
} else {
response.contentType = 'application/json';
if (uriMatcher.match("/{context}/api/enterprise/token")) {
session.put("externalEndpoint", restAPIRequestDetails["endpoint"]);
session.put("externalToken", restAPIRequestDetails["externalToken"]);
log.info("Calling get token");
callBackend(restAPIRequestDetails["endpoint"], session.get("externalToken"), "POST", restAPIRequestDetails);
if (response["status"] && response["status"] == 200) {
var completionToken = parse(result)["completionToken"];
if (completionToken) {
log.info("Token received");
session.put("completionToken", completionToken)
}
}
} else if (uriMatcher.match("/{context}/api/enterprise/enroll-complete")) {
var tokenEndpoint = session.get("externalEndpoint")
var enterpriseEndpoint = tokenEndpoint.replace("signup-url", "complete-signup");
var completionToken = session.get("completionToken");
var enterpriseToken = request.getParameter("enterpriseToken");
log.debug("completionToken" + completionToken + ", enterpriseEndpoint" + enterpriseEndpoint +
", enterpriseToken" + enterpriseToken);
var requestPayload = {}
requestPayload.completionToken = completionToken;
requestPayload.enterpriseToken = enterpriseToken;
log.info("Calling complete-signup");
callBackend(enterpriseEndpoint, session.get("externalToken"), "POST", requestPayload);
var enterpriseId = parse(result)["id"];
if (enterpriseId) {
log.info("Calling complete-signup success");
var serviceAccountRequest = {};
serviceAccountRequest.enterpriseId = enterpriseId;
serviceAccountRequest.keyType = "googleCredentials"
var enterpriseEndpoint = tokenEndpoint.replace("signup-url", "create-esa");
log.info("Calling create-esa");
callBackend(enterpriseEndpoint, session.get("externalToken"), "POST", serviceAccountRequest);
var data = parse(result)["data"];
log.info("Calling create-esa success" + data);
var androidConfigAPI = devicemgtProps["httpsURL"] + "/api/device-mgt/android/v1.0/configuration";
log.info("fetching platform configs");
callBackend(androidConfigAPI, accessToken, "GET");
var configurationsList = parse(result);
for (var x = 0; x < configurationsList.configuration.length; x++) {
if (configurationsList.configuration[x].name == "esa" || configurationsList.configuration[x].name == "enterpriseId") {
configurationsList.configuration.splice(x, 1);
}
}
log.info("fetching platform configs success");
var payloadToAdd = {};
payloadToAdd.contentType = "text";
payloadToAdd.name = "esa";
payloadToAdd.value = data;
var enterpriseIdPayload = {};
enterpriseIdPayload.contentType = "text";
enterpriseIdPayload.name = "enterpriseId";
enterpriseIdPayload.value = enterpriseId;
configurationsList.configuration[configurationsList.configuration.length] = payloadToAdd;
configurationsList.configuration[configurationsList.configuration.length] = enterpriseIdPayload;
log.info("saving platform configs");
callBackend(androidConfigAPI, accessToken, "PUT", configurationsList);
log.info("saving platform configs success");
if (response["status"] == 200) {
log.info("Process successful!! Redirecting...");
response.sendRedirect("/devicemgt/platform-configuration?enterprise-success=true");
}
}
} else if (uriMatcher.match("/{context}/api/enterprise/unenroll")) {
session.put("externalEndpoint", restAPIRequestDetails["endpoint"]);
session.put("externalToken", restAPIRequestDetails["externalToken"]);
callBackend(restAPIRequestDetails["endpoint"], session.get("externalToken"), "GET", restAPIRequestDetails);
log.info("Calling unenroll");
if (response["status"] == 200) {
log.info("Unenroll success, wiping devices.");
var wipeURL = devicemgtProps["httpsURL"] + "/api/device-mgt/android/v1.0/enterprise/wipe-device"
callBackend(wipeURL, accessToken, "GET");
}
}
}
%>

View File

@ -1,87 +0,0 @@
<%
/*
* Copyright (c) 2016, WSO2 Inc. (http://www.wso2.org) All Rights Reserved.
*
* WSO2 Inc. licenses this file to you under the Apache License,
* Version 2.0 (the "License"); you may not use this file except
* in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
var uri = request.getRequestURI();
var uriMatcher = new URIMatcher(String(uri));
var log = new Log("api/device-api.jag");
var constants = require("/app/modules/constants.js");
var utility = require("/app/modules/utility.js").utility;
var devicemgtProps = require("/app/modules/conf-reader/main.js")["conf"];
var serviceInvokers = require("/app/modules/oauth/token-protected-service-invokers.js")["invokers"];
var user = session.get(constants.USER_SESSION_KEY);
var result;
response.contentType = 'application/json';
if (!user) {
response.sendRedirect("/devicemgt/login?#login-required");
exit();
} else {
if (uriMatcher.match("/{context}/api/groups")) {
var url = request.getParameter("url");
var draw = request.getParameter("draw");
var length = request.getParameter("length");
var start = request.getParameter("start");
var search = request.getParameter("search[value]");
var groupName = request.getParameter("columns[1][search][value]");
var owner = request.getParameter("columns[2][search][value]");
var targetURL;
function appendQueryParam(url, queryParam, value) {
if (url.indexOf("?") > 0) {
return url + "&" + queryParam + "=" + value;
}
return url + "?" + queryParam + "=" + value;
}
targetURL = devicemgtProps.httpsURL + request.getParameter("url");
targetURL = appendQueryParam(targetURL, "start", start);
targetURL = appendQueryParam(targetURL, "length", length);
if (search && search !== "") {
targetURL = appendQueryParam(targetURL, "search", search);
}
if (groupName && groupName !== "") {
targetURL = appendQueryParam(targetURL, "group-name", groupName);
}
if (owner && owner !== "") {
targetURL = appendQueryParam(targetURL, "user", owner);
}
serviceInvokers.XMLHttp.get(
targetURL, function (responsePayload) {
response.status = 200;
result = responsePayload;
},
function (responsePayload) {
response.status = responsePayload.status;
result = responsePayload.responseText;
});
}
}
if (result) {
print(result);
}
%>

View File

@ -1,119 +0,0 @@
<%
/*
* Copyright (c) 2015, WSO2 Inc. (http://www.wso2.org) All Rights Reserved.
*
* WSO2 Inc. licenses this file to you under the Apache License,
* Version 2.0 (the "License"); you may not use this file except
* in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND,
* either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
var log = new Log("api/invoker-api.jag");
var uri = request.getRequestURI();
var uriMatcher = new URIMatcher(String(uri));
var constants = require("/app/modules/constants.js");
var devicemgtProps = require("/app/modules/conf-reader/main.js")["conf"];
var serviceInvokers = require("/app/modules/oauth/token-protected-service-invokers.js")["invokers"];
if (uriMatcher.match("/{context}/api/invoker/execute/")) {
//NOTE: We are only interested in Content-Type headers. Appending all request headers to the back-end call
// will cause unforeseen security issues.
var contentType = request.getHeader(constants.CONTENT_TYPE_IDENTIFIER);
var acceptType = request.getHeader(constants.ACCEPT_IDENTIFIER);
var requestHeaders = [];
requestHeaders.push({"name": constants.CONTENT_TYPE_IDENTIFIER, "value" : contentType});
requestHeaders.push({"name": constants.ACCEPT_IDENTIFIER, "value" : acceptType});
var restAPIRequestDetails = request.getContent();
var requestMethod = restAPIRequestDetails["requestMethod"];
var requestURL = restAPIRequestDetails["requestURL"];
var requestPayload = restAPIRequestDetails["requestPayload"];
if (!requestMethod) {
requestMethod = parse(restAPIRequestDetails)["requestMethod"];
}
if (!requestURL) {
requestURL = parse(restAPIRequestDetails)["requestURL"];
}
if (!requestPayload) {
requestPayload = parse(restAPIRequestDetails)["requestPayload"];
}
var restAPIEndpoint = devicemgtProps["httpsURL"] + requestURL;
try {
switch (requestMethod) {
case constants["HTTP_GET"]:
serviceInvokers.XMLHttp.get(
restAPIEndpoint,
function (restAPIResponse) {
response["status"] = restAPIResponse["status"];
if (restAPIResponse["responseText"]) {
response["content"] = restAPIResponse["responseText"];
}
},
requestHeaders
);
break;
case constants["HTTP_POST"]:
serviceInvokers.XMLHttp.post(
restAPIEndpoint,
requestPayload,
function (restAPIResponse) {
response["status"] = restAPIResponse["status"];
if (restAPIResponse["responseText"]) {
response["content"] = restAPIResponse["responseText"];
}
},
requestHeaders
);
break;
case constants["HTTP_PUT"]:
serviceInvokers.XMLHttp.put(
restAPIEndpoint,
requestPayload,
function (restAPIResponse) {
response["status"] = restAPIResponse["status"];
if (restAPIResponse["responseText"]) {
response["content"] = restAPIResponse["responseText"];
}
},
requestHeaders
);
break;
case constants["HTTP_DELETE"]:
serviceInvokers.XMLHttp.delete(
restAPIEndpoint,
function (restAPIResponse) {
response["status"] = restAPIResponse["status"];
if (restAPIResponse["responseText"]) {
response["content"] = restAPIResponse["responseText"];
}
},
requestHeaders
);
break;
}
} catch (e) {
//Since this is an API we'll log the error message.
log.error(e.message); // JavaScript error message
log.error(e.stack); // Executed JavaScript file stack
throw new Error("Exception occurred while trying to access " +
"backend REST API services from Jaggery API invoker layer", e);
}
}
%>

View File

@ -1,68 +0,0 @@
<%
/*
* Copyright (c) 2015, WSO2 Inc. (http://www.wso2.org) All Rights Reserved.
*
* WSO2 Inc. licenses this file to you under the Apache License,
* Version 2.0 (the "License"); you may not use this file except
* in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND,
* either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
var uri = request.getRequestURI();
var uriMatcher = new URIMatcher(String(uri));
var log = new Log("api/operation-api.jag");
var serviceInvokers = require("/app/modules/oauth/token-protected-service-invokers.js")["invokers"];
var devicemgtProps = require("/app/modules/conf-reader/main.js")["conf"];
if (uriMatcher.match("/{context}/api/operation/paginate")) {
var deviceType = request.getParameter("deviceType");
var deviceId = request.getParameter("deviceId");
var owner = request.getParameter("owner");
var ownership = request.getParameter("ownership");
var index = request.getParameter("start");
var length = request.getParameter("length");
var search = request.getParameter("search[value]");
var restAPIEndpoint = devicemgtProps["httpsURL"] + devicemgtProps["backendRestEndpoints"]["deviceMgt"] +
"/devices/" + deviceType + "/" + deviceId + "/operations?owner=" + owner + "&ownership=" + ownership +
"&offset=" + index + "&limit=" + length;
serviceInvokers.XMLHttp.get(
restAPIEndpoint,
function (restAPIResponse) {
if (restAPIResponse["status"] == 200 && restAPIResponse["responseText"]) {
var responsePayload = parse(restAPIResponse["responseText"]);
var paginatedResult = {};
paginatedResult["recordsTotal"] = responsePayload["count"];
paginatedResult["recordsFiltered"] = responsePayload["count"];
paginatedResult["data"] = responsePayload["operations"];
response["status"] = restAPIResponse["status"];
response["content"] = paginatedResult;
} else {
response["status"] = restAPIResponse["status"];
if (restAPIResponse["responseText"]) {
var responseText = "";
try {
response["content"] = parse(restAPIResponse["responseText"]);
} catch (e) {
responseText = restAPIResponse["responseText"];
}
}
}
}
);
}
%>

View File

@ -1,52 +0,0 @@
<%
/*
* Copyright (c) 2015, WSO2 Inc. (http://www.wso2.org) All Rights Reserved.
*
* WSO2 Inc. licenses this file to you under the Apache License,
* Version 2.0 (the "License"); you may not use this file except
* in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND,
* either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
/*
@Deprecated
*/
var uri = request.getRequestURI();
var uriMatcher = new URIMatcher(String(uri));
var log = new Log("api/policy-api.jag");
var constants = require("/modules/constants.js");
var policyModule = require("/app/modules/business-controllers/group.js")["groupModule"];
var result;
if (uriMatcher.match("/{context}/api/policies/update")) {
payload = request.getContent();
policyModule.updatePolicyPriorities(payload);
} else if (uriMatcher.match("/{context}/api/policies/{id}/delete")) {
elements = uriMatcher.elements();
policyId = elements.id;
try {
result = policyModule.deletePolicy(policyId);
} catch (e) {
log.error("Exception occurred while trying to delete policy for id:" + policyId, e);
// http status code 500 refers to - Internal Server Error.
result = 500;
}
}
// returning the result.
if (result) {
response.content = result;
}
%>

View File

@ -1,77 +0,0 @@
<%
/*
* Copyright (c) 2015, WSO2 Inc. (http://www.wso2.org) All Rights Reserved.
*
* WSO2 Inc. licenses this file to you under the Apache License,
* Version 2.0 (the "License"); you may not use this file except
* in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND,
* either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
var uri = request.getRequestURI();
var uriMatcher = new URIMatcher(String(uri));
var log = new Log("api/stats-api.jag");
var serviceInvokers = require("/app/modules/oauth/token-protected-service-invokers.js")["invokers"];
var devicemgtProps = require("/app/modules/conf-reader/main.js")["conf"];
if (uriMatcher.match("/{context}/api/stats/paginate")) {
var deviceType = request.getParameter("deviceType");
var deviceId = request.getParameter("deviceId");
var from = request.getParameter("from");
var to = request.getParameter("to");
var index = request.getParameter("start");
var length = request.getParameter("length");
var keys = request.getParameter("attributes");
keys = JSON.parse(keys);
var restAPIEndpoint = devicemgtProps["httpsURL"] + devicemgtProps["backendRestEndpoints"]["deviceMgt"] + "/events/"
+ deviceType + "/" + deviceId + "?offset=" + index +"&limit=" + length + "&from="+ from + "&to=" + to;
serviceInvokers.XMLHttp.get(
restAPIEndpoint,
function (restAPIResponse) {
if (restAPIResponse["status"] == 200 && restAPIResponse["responseText"]) {
var responsePayload = parse(restAPIResponse["responseText"]);
var paginatedResult = {};
paginatedResult["recordsTotal"] = responsePayload["count"];
paginatedResult["recordsFiltered"] = responsePayload["count"];
var records = responsePayload["records"];
var dataSet = [];
for (var i = 0; i < records.length; i++){
var record = records[i];
var timestamp = record["timestamp"];
var dataRow = [];
dataRow.push(timestamp);
for (var j = 0; j < keys.length; j++) {
var key = keys[j];
dataRow.push(record.values[key]);
}
//dataSet.push(dataRow);
dataSet.push(dataRow);
}
paginatedResult["data"] = dataSet;
response["status"] = restAPIResponse["status"];
response["content"] = paginatedResult;
} else {
response["status"] = 204;
var paginatedResult = {};
var dataSet = [];
paginatedResult["recordsTotal"] = 0;
paginatedResult["recordsFiltered"] = 0;
paginatedResult["data"] = dataSet;
response["content"] = paginatedResult;
}
}
);
}
%>

View File

@ -1,211 +0,0 @@
<%
/*
* Copyright (c) 2015, WSO2 Inc. (http://www.wso2.org) All Rights Reserved.
*
* WSO2 Inc. licenses this file to you under the Apache License,
* Version 2.0 (the "License"); you may not use this file except
* in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND,
* either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
var uri = request.getRequestURI();
var uriMatcher = new URIMatcher(String(uri));
var log = new Log("api/user-api.jag");
var constants = require("/app/modules/constants.js");
var devicemgtProps = require("/app/modules/conf-reader/main.js")["conf"];
var userModule = require("/app/modules/business-controllers/user.js")["userModule"];
var deviceModule = require("/app/modules/business-controllers/device.js")["deviceModule"];
var utility = require("/app/modules/utility.js")["utility"];
var apiWrapperUtil = require("/app/modules/oauth/token-handlers.js")["handlers"];
var util = require("/app/modules/oauth/token-handler-utils.js")["utils"];
var responseProcessor = require("utils").response;
var result;
if (uriMatcher.match("/{context}/api/user/clearBilling")) {
carbonUser = session.get(constants.USER_SESSION_KEY);
session.put('BILLING_INFO_' + carbonUser.domain, null);
log.info("billing info cleared for " + carbonUser.domain);
} else if (uriMatcher.match("/{context}/api/user/authenticate")) {
var username = request.getParameter("username");
var password = request.getParameter("password");
//Check if a username and password is provided
if ((!username) || (!password)) {
response = responseProcessor.buildErrorResponse(response, 400, 'Username and Password must be provided');
} else {
try {
userModule.login(username, password, function (user) {
if (log.isDebugEnabled()) {
log.debug("User Logged In : " + user);
}
apiWrapperUtil.setupTokenPairByPasswordGrantType(username, password);
}, function () {
response = responseProcessor.buildSuccessResponse(response, 200, {'sessionId': session.getId()});
});
} catch (e) {
log.error("Exception occurred while a user tried to login to MDM", e);
response = responseProcessor.buildErrorResponse(response, 401, 'username/password is incorrect');
}
}
} else if (uriMatcher.match("/{context}/api/user/login/")) {
username = request.getParameter("username");
password = request.getParameter("password");
username = util.decode(username);
password = util.decode(password);
try {
userModule.login(username, password, function (user) {
if (log.isDebugEnabled()) {
log.debug("User Logged In : " + user);
}
apiWrapperUtil.setupTokenPairByPasswordGrantType(username, password);
var permissions = userModule.getUIPermissions();
if (permissions.VIEW_DASHBOARD) {
response.sendRedirect(devicemgtProps["appContext"]);
} else {
response.sendRedirect(devicemgtProps["appContext"] + "devices");
}
}, function () {
response.sendRedirect(devicemgtProps.appContext + "login?#auth-failed");
});
} catch (e) {
log.error("Exception occurred while a user tried to login to MDM", e);
response.sendRedirect(devicemgtProps.appContext + "login?#error");
}
} else if (uriMatcher.match("/{context}/api/user/logout/")) {
userModule.logout(function () {
response.sendRedirect(devicemgtProps.appContext + "login");
});
} else if (uriMatcher.match("/{context}/api/user/devices/")) {
/*
@Deprecated
*/
if (userModule.isAuthorized("/permission/admin/device-mgt/user/devices/list")) {
carbonUser = session.get(constants.USER_SESSION_KEY);
result = deviceModule.listDevicesForUser(carbonUser.username);
} else {
response.sendError(403);
}
} else if (uriMatcher.match("/{context}/api/user/{username}/invite")) {
/*
@Deprecated
*/
if (userModule.isAuthorized("/permission/admin/device-mgt/user/invite")) {
elements = uriMatcher.elements();
username = elements.username;
userModule.inviteUser(username);
} else {
response.sendError(403);
}
} else if (uriMatcher.match("/{context}/api/user/add")) {
/*
@Deprecated
*/
if (userModule.isAuthorized("/permission/admin/device-mgt/user/add")) {
addUserFormData = request.getContent();
username = addUserFormData.username;
firstname = addUserFormData.firstname;
lastname = addUserFormData.lastname;
emailAddress = addUserFormData.emailAddress;
if (!addUserFormData.userRoles) {
userRoles = null;
} else {
userRoles = String(addUserFormData.userRoles).split(",");
}
if (username.length < devicemgtProps.userValidationConfig.usernameLength) {
log.error("Username Must be between 1 and " + devicemgtProps.userValidationConfig.usernameLength + " characters long");
result = "Username Must be between 1 and " + devicemgtProps.userValidationConfig.usernameLength + " characters long";
} else {
try {
result = userModule.addUser(username, firstname, lastname, emailAddress, userRoles);
} catch (e) {
log.error("Exception occurred while trying to add a user to MDM User Store", e);
// http status code 400 refers to - Bad request.
result = 400;
}
}
} else {
// http status code 403 refers to - forbidden.
result = 403;
}
} else if (uriMatcher.match("/{context}/api/user/register")) {
addUserFormData = request.getContent();
username = addUserFormData.username;
firstname = addUserFormData.firstname;
lastname = addUserFormData.lastname;
emailAddress = addUserFormData.emailAddress;
password = addUserFormData.password;
userRoles = ["internal/devicemgt-user"];
try {
result = userModule.registerUser(username, firstname, lastname, emailAddress, password,
userRoles);
} catch (e) {
log.error("Exception occurred while trying to registering a new user to DC User Store", e);
// http status code 400 refers to - Bad request.
result = 400;
}
} else if (uriMatcher.match("/{context}/api/user/{username}/remove")) {
/*
@Deprecated
*/
if (userModule.isAuthorized("/permission/admin/device-mgt/user/remove")) {
elements = uriMatcher.elements();
username = elements.username;
try {
result = userModule.removeUser(username);
} catch (e) {
log.error("Exception occurred while trying to remove a user from MDM User Store", e);
// http status code 400 refers to - Bad request.
result = 400;
}
} else {
// http status code 403 refers to - forbidden.
result = 403;
}
} else if (uriMatcher.match("/{context}/api/user/all")) {
result = userModule.getUsers();
} else if (uriMatcher.match("/{context}/api/user/environment-loaded")) {
try {
var carbonUser = session.get(constants.USER_SESSION_KEY);
if (!carbonUser) {
response.sendRedirect("/devicemgt/login?#login-required");
exit();
}
utility.startTenantFlow(carbonUser);
var APIManagementProviderService = utility.getAPIManagementProviderService();
var isLoaded = APIManagementProviderService.isTierLoaded();
result = {"isLoaded": isLoaded};
if (isLoaded) {
var samlToken = session.get(constants.SAML_TOKEN_KEY);
if (samlToken) {
apiWrapperUtil.setupTokenPairByJWTGrantType(carbonUser.username + '@' + carbonUser.domain, samlToken);
}
}
response.contentType = 'application/json';
} finally {
utility.endTenantFlow();
}
}
// returning the result.
if (result) {
print(result);
}
%>

View File

@ -1,47 +0,0 @@
{
"appName": "Entgra IoT Server",
"cachingEnabled": false,
"debuggingEnabled": false,
"permissionRoot": "/",
"portalURL": "https://${server.ip}:9445",
"loginPage": "cdmf.page.sign-in.login-do",
"adminServicesUrl": "https://${server.ip}:${server.https_port}/admin/services/",
"authModule": {
"enabled": true,
"login": {
"onSuccess": {
"script": "/app/modules/login.js",
"page": "cdmf.page.processing"
},
"onFail": {
"script": "/app/modules/login.js",
"page": "cdmf.page.sign-in.login-do"
}
},
"logout": {
"onSuccess": {
"page": "cdmf.page.sign-in.login-do"
},
"onFail": {
"page": "cdmf.page.dashboard"
}
},
"sso": {
"enabled": true,
"issuer" : "devicemgt",
"appName" : "devicemgt",
"identityProviderUrl" : "https://%iot.keymanager.host%:%iot.keymanager.https.port%/samlsso",
"acs": "https://%iot.manager.host%:%iot.manager.https.port%/devicemgt/uuf/sso/acs",
"identityAlias": "wso2carbon",
"defaultNameIDPolicy": "urn:oasis:names:tc:SAML:1.1:nameid-format:unspecified",
"isPassive":false,
"responseSigningEnabled" : true,
"validateAssertionValidityPeriod": true,
"validateAudienceRestriction": true,
"assertionSigningEnabled": true
}
},
"errorPages": {
"default": "uuf.page.error"
}
}

View File

@ -1,174 +0,0 @@
{
"appContext": "/devicemgt/",
"isCloud": false,
"isDeviceOwnerEnabled": false,
"managerHTTPSURL": "https://%iot.manager.host%:%iot.manager.https.port%",
"httpsURL": "https://%iot.gateway.host%:%iot.gateway.https.port%",
"httpURL": "http://%iot.gateway.host%:%iot.gateway.http.port%",
"wssURL": "https://%iot.core.host%:%iot.core.https.port%",
"remoteSessionWSURL": "https://%iot.manager.host%:%iot.manager.https.port%",
"portalURL": "https://%iot.analytics.host%:%iot.analytics.https.port%",
"dashboardServerURL": "%https.ip%",
"androidAgentDownloadURL": "https://%iot.manager.host%:%iot.manager.https.port%/devicemgt/public/cdmf.unit.device.type.android.type-view/assets/android-agent.apk",
"windowsEnrollmentDir": "/windows-web-agent/enrollment",
"iOSEnrollmentDir": "/ios-web-agent/enrollment",
"iOSConfigRoot": "https://%iot.manager.host%:%iot.manager.https.port%/ios-enrollment/",
"iOSAPIRoot": "https://%iot.manager.host%:%iot.manager.https.port%/ios/",
"adminService": "https://%iot.manager.host%:%iot.manager.https.port%",
"deviceInfoServiceAPI" : "/api/device-mgt/%device-type%/v1.0/admin/devices/info",
"deviceLocationServiceAPI" : "/api/device-mgt/%device-type%/v1.0/admin/devices/location",
"iOSDeviceInfoServiceAPI" : "/api/device-mgt/%device-type%/v1.0/admin/devices/info",
"gatewayEnabled": true,
"oauthProvider": {
"appRegistration": {
"appType": "webapp",
"clientName": "iot_ui",
"owner": "admin@carbon.super",
"dynamicClientAppRegistrationServiceURL": "https://%iot.gateway.host%:%iot.gateway.https.port%/dynamic-client-web/register",
"apiManagerClientAppRegistrationServiceURL": "https://%iot.gateway.host%:%iot.gateway.https.port%/api-application-registration/register/tenants",
"grantType": "password refresh_token urn:ietf:params:oauth:grant-type:saml2-bearer urn:ietf:params:oauth:grant-type:jwt-bearer",
"tokenScope": "admin",
"callbackUrl": "https://%iot.gateway.host%:%iot.gateway.https.port%/api/device-mgt/v1.0",
"samlGrantTypeName": "urn:ietf:params:oauth:grant-type:saml2-bearer"
},
"tokenServiceURL": "https://%iot.gateway.host%:%iot.gateway.https.port%/token"
},
"adminUser": "admin@carbon.super",
"adminUserTenantId": "-1234",
"adminRole": "admin",
"userValidationConfig": {
"usernameLength": 30,
"usernameJSRegEx": "^[\\S]{3,30}$",
"usernameRegExViolationErrorMsg": "Provided username is invalid.",
"usernameHelpMsg": "Should be in minimum 3 characters long and do not include any whitespaces.",
"firstnameJSRegEx": "^.{3,30}$",
"firstnameRegExViolationErrorMsg": "Provided first name is invalid.",
"lastnameJSRegEx": "^.{3,30}$",
"lastnameRegExViolationErrorMsg": "Provided last name is invalid.",
"emailJSRegEx": "/^\w+([\.-]?\w+)*@\w+([\.-]?\w+)*(\.\w{2,3})+$/",
"emailRegExViolationErrorMsg": "Provided email is invalid."
},
"groupValidationConfig": {
"groupNameJSRegEx": "^[\\S]{3,30}$",
"groupNameRegExViolationErrorMsg": "Group name should be in minimum 3 characters long and should not include any whitespaces.",
"groupNameHelpMsg": "Should be in minimum 3 characters long and should not include any whitespaces."
},
"roleValidationConfig": {
"roleNameJSRegEx": "^[\\S]{3,30}$",
"roleNameRegExViolationErrorMsg": "Provided role name is invalid.",
"roleNameHelpMsg": "should be in minimum 3 characters long and do not include any whitespaces."
},
"generalConfig": {
"host": "https://%iot.manager.host%:%iot.manager.https.port%",
"companyName": "Entgra Carbon Device Manager",
"browserTitle": "Entgra Device Manager",
"copyrightPrefix": "\u00A9 %date-year%, ",
"copyrightOwner": "Entgra",
"copyrightOwnersSite": "https://www.entgra.io/",
"copyrightSuffix": " All Rights Reserved."
},
"scopes": [
"dm:sign-csr",
"dm:admin:devices:view",
"dm:admin:topics:view",
"rm:roles:add",
"rm:users:add",
"rm:roles:update",
"rm:roles:permissions:view",
"rm:roles:details:view",
"rm:roles:view",
"rm:roles:combined:add",
"rm:roles:delete",
"an:db:vulnerabilities",
"an:db:non-compliant:count",
"an:db:non-compliant",
"an:db:by-groups",
"an:db:device:count",
"an:db:feature-non-compliant",
"an:db:overview:count",
"an:db:filtered-count",
"an:db:details",
"dm:activity:get",
"dm:devices:delete",
"dm:devices:app:view",
"dm:devices:policy:view",
"dm:devices:compliance:view",
"dm:devices:features:view",
"dm:devices:ops:view",
"dm:devices:search",
"dm:devices:details",
"dm:devices:update",
"dm:devices:view",
"dm:conf:view",
"dm:conf:manage",
"pm:policies:remove",
"pm:policies:priorities:update",
"pm:policies:deactivate",
"pm:policies:details:view",
"pm:policies:add",
"pm:policies:activate",
"pm:policies:update",
"pm:policies:change",
"dm:policies:view",
"um:users:add",
"um:users:details:view",
"um:users:count",
"um:users:delete",
"um:roles:view",
"um:users:user-details:view",
"um:users:cred:change",
"um:users:search",
"um:users:is-exist",
"um:users:update",
"um:users:invite",
"um:admin:users:view",
"dm:admin:enrollment:update",
"gm:devices:view",
"gm:groups:update",
"gm:groups:add",
"gm:groups:device:view",
"gm:devices:count",
"gm:groups:remove",
"gm:groups:view",
"gm:groups:groups-view",
"gm:roles:share",
"gm:groups:count",
"gm:roles:view",
"gm:devices:remove",
"gm:devices:add",
"gm:devices:assign",
"dm:device-type:conf:view",
"dm:device-type:features:view",
"dm:device-type:view",
"am:admin:app:install",
"am:admin:app:uninstall",
"gm:admin:groups:count",
"gm:admin:groups:view",
"dm:notif:mark-checked",
"dm:notifications:view",
"cm:cert:delete",
"cm:cert:details:get",
"cm:cert:view",
"cm:cert:add",
"cm:cert:verify",
"dm:admin",
"dm:device-type:deploy",
"dm:device-type:event:modify",
"dm:device-type:event:view",
"dm:admin:device-type:modify",
"dm:admin:device-type:view",
"dm:admin:device-type:conf:add",
"dm:device:enroll",
"dm:geo:an:view",
"dm:geo:alerts:manage",
"dm:admin:devices:permanent-delete",
"appm:read",
"and:enterprise:modify",
"and:enterprise:view"
],
"isOAuthEnabled": true,
"backendRestEndpoints": {
"deviceMgt": "/api/device-mgt/v1.0",
"appMgt": "/api/application-mgt-store/v1.0"
}
}

View File

@ -1,138 +0,0 @@
{
"Logo": {
"name": "Cloud",
"url": "https://cloudmgt.cloud.wso2.com/cloudmgt",
"target": "_parent"
},
"Main": {
"Domain": {
"url": "#",
"icon": "fw fw-organization",
"isAdminOnly": false,
"target": "_parent",
"dropDown": {
"Organization": {
"url": "https://cloudmgt.cloud.wso2.com/cloudmgt/site/pages/organization.jag",
"icon": "fw fw-organization",
"dropDown": "false",
"target": "_self"
},
"Members": {
"url": "https://cloudmgt.cloud.wso2.com/cloudmgt/site/pages/user.jag",
"icon": "fa fa-users",
"dropDown": "false",
"target": "_self"
}
}
},
"Account": {
"url": "#",
"icon": "fw fw-resource",
"isAdminOnly": false,
"billingEnabled": true,
"billingApi": {
"username": "admin",
"password": "admin"
},
"cloudMgtHost" : "https://cloudmgt.cloudstaging.wso2.com",
"cloudMgtIndexPage": "https://cloudmgt.cloud.wso2.com/cloudmgt/site/pages/index.jag",
"dropDown": {
"Upgrade Now": {
"url": "https://cloudmgt.cloud.wso2.com/cloudmgt/site/pages/payment-plans.jag?cloud-type=device_cloud",
"icon": "fw fw-export",
"dropDown": "true",
"target": "_self"
},
"Request Extension": {
"url": "https://cloudmgt.cloud.wso2.com/cloudmgt/site/pages/contact-us.jag?cloud-type=device_cloud&request-extension=true",
"icon": "fa fa-mail",
"dropDown": "true",
"target": "_self"
}
}
},
"Support": {
"url": "https://cloudmgt.cloud.wso2.com/cloudmgt/site/pages/contact-us.jag?cloud-type=device_cloud",
"icon": "fw fw-mail",
"isAdminOnly": false,
"target": "_self",
"dropDown": "false"
},
"Documentation": {
"url": "#",
"icon": "fw fw-document",
"isAdminOnly": false,
"dropDown": {
"Device Cloud": {
"id": "device_cloud",
"url": "https://docs.wso2.com/display/DeviceCloud/WSO2+Device+Cloud+Documentation",
"icon": "fw fw-mobile",
"target": "_blank"
}
}
}
},
"User": {
"url": "#",
"icon": "fw fw-user",
"dropDown": {
"Profile": {
"url": "https://cloudmgt.cloud.wso2.com/cloudmgt/site/pages/user-profile.jag",
"icon": "fw fw-user",
"dropDown": "true",
"target": "_self"
},
"Change Password": {
"url": "https://cloudmgt.cloud.wso2.com/cloudmgt/site/pages/change-password.jag",
"icon": "fw fw-lock",
"dropDown": "true",
"target": "_self"
},
"Logout": {
"url": "https://device.cloud.wso2.com/devicemgt/logout",
"icon": "fw fw-sign-out",
"dropDown": "true",
"target": "_self"
}
}
},
"Expand": {
"Clouds": {
"API Cloud": {
"id": "api_cloud",
"url": "https://api.cloud.wso2.com/publisher",
"icon": "fw fw-api fw-3x",
"dropDown": "true",
"target": "_self"
},
"Integration Cloud": {
"id": "integration_cloud",
"url": "https://integration.cloud.wso2.com/appmgt",
"icon": "fw fw-service fw-3x",
"dropDown": "true",
"target": "_self"
},
"Identity Cloud": {
"id": "integration_cloud",
"url": "https://identity.cloud.wso2.com/admin",
"icon": "fw fw-security fw-3x",
"dropDown": "true",
"target": "_self"
}
},
"Actions": {
"Organization": {
"url": "https://cloudmgt.cloud.wso2.com/cloudmgt/site/pages/organization.jag",
"icon": "fw fw-organization fw-3x",
"dropDown": "true",
"target": "_self"
},
"Members": {
"url": "https://cloudmgt.cloud.wso2.com/cloudmgt/site/pages/user.jag",
"icon": "fa fa-users fa-3x",
"dropDown": "true",
"target": "_self"
}
}
}
}

View File

@ -1,82 +0,0 @@
{{!-- Copyright (c) 2015, WSO2 Inc. (http://www.wso2.org) All Rights Reserved.
WSO2 Inc. licenses this file to you under the Apache License,
Version 2.0 (the "License"); you may not use this file except
in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing,
software distributed under the License is distributed on an
"AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND,
either express or implied. See the License for the
specific language governing permissions and limitations
under the License. --}}
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
{{defineZone "favicon"}}
<title>
{{defineZone "title"}}
</title>
{{defineZone "topLibCss"}}
{{defineZone "topCss"}}
{{defineZone "topJs"}}
</head>
<body>
<!--modal-->
<div class="modal fade" tabindex="-1" role="dialog" aria-labelledby="modalDemo">
<div class="modal-dialog" role="document">
<div class="modal-content clearfix">
<div class="modal-header">
<button type="button" class="close" data-dismiss="modal" aria-label="Close"><i class="fw fw-cancel"></i></button>
</div>
<div class="modal-body add-margin-top-2x add-margin-bottom-2x">
</div>
<div class="modal-footer">
<button type="button" class="btn btn-default" data-dismiss="modal">Close</button>
</div>
</div>
</div>
</div>
<!--modal-->
{{defineZone "header"}}
{{defineZone "sidePanes"}}
<!-- page-content-wrapper -->
<div class="page-content-wrapper">
<div class="navbar-wrapper">
{{defineZone "navbars"}}
</div>
{{!defineZone "contentTitle"}}
<div class="container-fluid ">
<div class="body-wrapper">
{{defineZone "content"}}
</div>
</div>
</div>
<!-- /page-content-wrapper -->
<footer class="footer">
<div class="container-fluid">
{{defineZone "footer"}}
</div>
</footer>
{{defineZone "bottomModalContent"}}
{{defineZone "bottomLibJs"}}
{{defineZone "bottomJs"}}
</body>
</html>

View File

@ -1,48 +0,0 @@
{{!-- Copyright (c) 2015, WSO2 Inc. (http://www.wso2.org) All Rights Reserved.
WSO2 Inc. licenses this file to you under the Apache License,
Version 2.0 (the "License"); you may not use this file except
in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing,
software distributed under the License is distributed on an
"AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND,
either express or implied. See the License for the
specific language governing permissions and limitations
under the License. --}}
<!DOCTYPE html>
<html>
<head>
<meta charset='UTF-8'>
<link rel="stylesheet" href="https://error.cloud.wso2.com/style/style.css">
<link rel="stylesheet" href="https://error.cloud.wso2.com/style/font-mf.css">
<title>
{{defineZone "title"}}
</title>
</head>
<body>
<div class="sky">
<section>
<div class="error-400">
<img src="https://error.cloud.wso2.com/images/400-error.svg">
</div>
<div class="text-label">
<h1>{{#defineZone "messageTitle"}}Oops something went wrong{{/defineZone}}</h1>
<h2>{{defineZone "messageDescription"}}</h2>
<div style="clear: both"></div>
<div class="button-label">
<a href="https://cloudmgt.cloud.wso2.com/cloudmgt/site/pages/index.jag"><label class="label-back">Back to Cloud </label></a>
<a href="https://cloudmgt.cloud.wso2.com/cloudmgt/site/pages/contact-us.jag"><label class="label-report"> Report Issue </label></a>
</div>
</div>
</section>
<div class="clouds_one"></div>
<div class="clouds_two"></div>
<div class="clouds_three"></div>
</div>
</body>
</html>

View File

@ -1,57 +0,0 @@
{{!-- Copyright (c) 2015, WSO2 Inc. (http://www.wso2.org) All Rights Reserved.
WSO2 Inc. licenses this file to you under the Apache License,
Version 2.0 (the "License"); you may not use this file except
in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing,
software distributed under the License is distributed on an
"AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND,
either express or implied. See the License for the
specific language governing permissions and limitations
under the License. --}}
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
{{defineZone "favicon"}}
<title>
{{defineZone "title"}}
</title>
{{defineZone "topLibCss"}}
{{defineZone "topCss"}}
{{defineZone "topJs"}}
</head>
<body>
<!--modal-->
<div class="modal fade" tabindex="-1" role="dialog" aria-labelledby="modalDemo">
<div class="modal-dialog" role="document">
<div class="modal-content clearfix">
<div class="modal-header">
<button type="button" class="close" data-dismiss="modal" aria-label="Close"><i class="fw fw-cancel"></i></button>
</div>
<div class="modal-body add-margin-top-2x add-margin-bottom-2x">
</div>
<div class="modal-footer">
<button type="button" class="btn btn-default" data-dismiss="modal">Close</button>
</div>
</div>
</div>
</div>
<!--modal-->
{{defineZone "content"}}
{{defineZone "bottomModalContent"}}
{{defineZone "bottomLibJs"}}
{{defineZone "bottomJs"}}
</body>
</html>

View File

@ -1,149 +0,0 @@
/*
* Copyright (c) 2018 - 2023, Entgra (Pvt) Ltd. (http://www.entgra.io) All Rights Reserved.
*
* Entgra (Pvt) Ltd. licenses this file to you under the Apache License,
* Version 2.0 (the "License"); you may not use this file except
* in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
var batchProviders;
batchProviders = function () {
var operations = {};
var CONTENT_TYPE_JSON = "application/json";
var JS_MAX_VALUE = "9007199254740992";
var JS_MIN_VALUE = "-9007199254740992";
var TABLENAME_ANDROID = "ORG_WSO2_GEO_FUSEDSPATIALEVENT";
var TABLENAME_ANDROID_SENSE = "ORG_WSO2_IOT_ANDROID_LOCATION";
var tableName = function (deviceType) {
switch (deviceType) {
case "android" :
return TABLENAME_ANDROID;
break;
case "android_sense" :
return TABLENAME_ANDROID_SENSE;
break;
default:
return null;
}
};
var typeMap = {
"bool": "string",
"boolean": "string",
"string": "string",
"int": "number",
"integer": "number",
"long": "number",
"double": "number",
"float": "number",
"time": "time"
};
var log = new Log();
var carbon = require('carbon');
var JSUtils = Packages.org.wso2.carbon.analytics.jsservice.Utils;
var AnalyticsCachedJSServiceConnector = Packages.org.wso2.carbon.analytics.jsservice.AnalyticsCachedJSServiceConnector;
var AnalyticsCache = Packages.org.wso2.carbon.analytics.jsservice.AnalyticsCachedJSServiceConnector.AnalyticsCache;
var cacheTimeoutSeconds = 5;
var cacheSizeBytes = 1024 * 1024 * 1024; // 1GB
response.contentType = CONTENT_TYPE_JSON;
var cache = application.get("AnalyticsWebServiceCache");
if (cache == null) {
cache = new AnalyticsCache(cacheTimeoutSeconds, cacheSizeBytes);
application.put("AnalyticsWebServiceCache", cache);
}
var connector = new AnalyticsCachedJSServiceConnector(cache);
/**
* returns an array of column names & types
* @param providerConfig
*/
operations.getSchema = function (loggedInUser) {
var tablename = tableName(deviceType);
if (tablename == null) {
return [];
}
var schema = [];
var result = connector.getTableSchema(loggedInUser, tablename).getMessage();
result = JSON.parse(result);
var columns = result.columns;
Object.getOwnPropertyNames(columns).forEach(function (name, idx, array) {
var type = "ordinal";
if (columns[name]['type']) {
type = columns[name]['type'];
}
schema.push({
fieldName: name,
fieldType: typeMap[type.toLowerCase()]
});
});
// log.info(schema);
return schema;
};
/**
* returns the actual data
* @param providerConfig
* @param limit
*/
operations.getData = function (loggedInUser, deviceId, deviceType) {
var luceneQuery = "";
var limit = 100;
var result;
var tablename = tableName(deviceType);
if (tablename == null) {
return [];
}
//if there's a filter present, we should perform a Lucene search instead of reading the table
if (luceneQuery) {
luceneQuery = 'id:"' + deviceId + '" AND type:"' + deviceType + '"';
var filter = {
"query": luceneQuery,
"start": 0,
"count": limit
};
result = connector.search(loggedInUser, tablename, stringify(filter)).getMessage();
} else {
var from = JS_MIN_VALUE;
var to = JS_MAX_VALUE;
result = connector.getRecordsByRange(loggedInUser, tablename, from, to, 0, limit, null).getMessage();
}
// error handling ----
var resultString = result.toString();
if (resultString.contains("Failed to get records from table")) {
return null;
}
result = JSON.parse(result);
var data = [];
for (var i = 0; i < result.length; i++) {
var values = result[i].values;
data.push(values);
}
return data;
};
return operations;
}();

View File

@ -1,467 +0,0 @@
/*
* Copyright (c) 2018 - 2023, Entgra (Pvt) Ltd. (http://www.entgra.io) All Rights Reserved.
*
* Entgra (Pvt) Ltd. licenses this file to you under the Apache License,
* Version 2.0 (the "License"); you may not use this file except
* in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
var deviceModule;
deviceModule = function () {
var log = new Log("/app/modules/business-controllers/device.js");
var utility = require('/app/modules/utility.js')["utility"];
var constants = require('/app/modules/constants.js');
var devicemgtProps = require("/app/modules/conf-reader/main.js")["conf"];
var serviceInvokers = require("/app/modules/oauth/token-protected-service-invokers.js")["invokers"];
var batchProvider = require("/app/modules/batch-provider-api.js")["batchProviders"];
var process = require("process");
var carbon = require("carbon");
var publicMethods = {};
var privateMethods = {};
/**
* Only GET method is implemented for now since there are no other type of methods used this method.
* @param url - URL to call the backend without the host
* @param method - HTTP Method (GET, POST)
* @returns An object with 'status': 'success'|'error', 'content': {}
*/
privateMethods.callBackend = function (url, method) {
if (constants["HTTP_GET"] == method) {
return serviceInvokers.XMLHttp.get(url,
function (backendResponse) {
var response = {};
response.content = backendResponse.responseText;
if (backendResponse.status == 200) {
response.status = "success";
} else if (backendResponse.status == 400 || backendResponse.status == 401 ||
backendResponse.status == 404 || backendResponse.status == 500) {
response.status = "error";
}
return response;
}
);
} else {
log.error("Runtime error : This method only support HTTP GET requests.");
}
};
privateMethods.validateAndReturn = function (value) {
return (value == undefined || value == null) ? constants["UNSPECIFIED"] : value;
};
/*
@Updated
*/
publicMethods.viewDevice = function (deviceType, deviceId, owner, ownership) {
var carbonUser = session.get(constants["USER_SESSION_KEY"]);
if (!carbonUser) {
log.error("User object was not found in the session");
userModule.logout(function () {
response.sendRedirect(devicemgtProps["appContext"] + "login");
});
}
var userName = carbonUser.username + "@" + carbonUser.domain;
var locationHistory = [];
var geoServicesEnabled = devicemgtProps.serverConfig.geoLocationConfiguration.enabled;
if (geoServicesEnabled) {
try {
var fromDate = new Date();
fromDate.setHours(fromDate.getHours() - 2);
var toDate = new Date();
var serviceUrl = devicemgtProps["httpsURL"] + '/api/device-mgt/v1.0/geo-services/stats/' + deviceType + '/' + deviceId + '?from=' + fromDate.getTime() + '&to=' + toDate.getTime();
serviceInvokers.XMLHttp.get(serviceUrl,
function (backendResponse) {
if (backendResponse.status === 200 && backendResponse.responseText) {
locationHistory = JSON.parse(backendResponse.responseText);
}
});
} catch (e) {
log.error(e.message, e);
}
}
var locationInfo = {};
try {
var url = devicemgtProps["httpsURL"] + "/api/device-mgt/v1.0/devices/" + deviceType + "/" + deviceId + "/location";
serviceInvokers.XMLHttp.get(
url,
function (backendResponse) {
if (backendResponse.status == 200 && backendResponse.responseText) {
var device = parse(backendResponse.responseText);
locationInfo.latitude = device.latitude;
locationInfo.longitude = device.longitude;
locationInfo.updatedOn = device.updatedTime;
}
});
} catch (e) {
log.error(e.message, e);
}
var utility = require('/app/modules/utility.js')["utility"];
try {
utility.startTenantFlow(carbonUser);
var url = devicemgtProps["httpsURL"] + "/api/device-mgt/v1.0/devices/" + deviceType + "/" + deviceId;
if (owner) {
url = url + "?owner=" + owner;
if (ownership){
url = url + "&ownership=" + ownership;
}
} else if (ownership){
url = url + "?ownership=" + ownership;
}
return serviceInvokers.XMLHttp.get(
url,
function (backendResponse) {
var response = {};
if (backendResponse.status == 200 && backendResponse.responseText) {
var device = parse(backendResponse.responseText);
var filteredDeviceData = {};
if (device["deviceIdentifier"]) {
filteredDeviceData["deviceIdentifier"] = device["deviceIdentifier"];
}
if (device["type"]) {
filteredDeviceData["type"] = device["type"];
}
if (device["name"]) {
filteredDeviceData["name"] = device["name"];
}
if (device["enrolmentInfo"]) {
var enrolmentInfo = {};
if (device["enrolmentInfo"]["status"]) {
enrolmentInfo["status"] = device["enrolmentInfo"]["status"];
}
if (device["enrolmentInfo"]["owner"]) {
enrolmentInfo["owner"] = device["enrolmentInfo"]["owner"];
}
if (device["enrolmentInfo"]["ownership"]) {
enrolmentInfo["ownership"] = device["enrolmentInfo"]["ownership"];
}
filteredDeviceData["enrolmentInfo"] = enrolmentInfo;
}
if (device["properties"] && device["properties"].length > 0) {
var propertiesList = device["properties"];
var properties = {};
if (propertiesList) {
for (var i = 0; i < propertiesList.length; i++) {
if (propertiesList[i]["value"]) {
properties[propertiesList[i]["name"]] =
propertiesList[i]["value"];
}
}
}
filteredDeviceData["initialDeviceInfo"] = properties;
if (properties["DEVICE_INFO"]) {
var initialDeviceInfoList = parse(properties["DEVICE_INFO"]);
var initialDeviceInfo = {};
if (Array.isArray(initialDeviceInfoList)) {
for (var j = 0; j < initialDeviceInfoList.length; j++) {
if (initialDeviceInfoList[j]["value"]) {
initialDeviceInfo[initialDeviceInfoList[j]["name"]] =
initialDeviceInfoList[j]["value"];
}
}
} else {
initialDeviceInfo = initialDeviceInfoList;
}
filteredDeviceData["initialDeviceInfo"]["DEVICE_INFO"] = initialDeviceInfo;
}
}
if (filteredDeviceData["type"]) {
if (filteredDeviceData["type"] == constants["PLATFORM_IOS"]) {
if (filteredDeviceData["properties"]) {
filteredDeviceData["properties"]["VENDOR"] = "Apple";
}
}
}
if (device["deviceInfo"]) {
filteredDeviceData["latestDeviceInfo"] = device["deviceInfo"];
} else {
filteredDeviceData["latestDeviceInfo"] = {};
filteredDeviceData["latestDeviceInfo"]["location"] = {};
}
//location related verification and modifications
// adding the location histry for the movement path.
filteredDeviceData["locationHistory"] = locationHistory;
//checking for the latest location information based on historical data.
if (locationHistory) {
var infoDate;
var locationDate;
var historicalLatestLoc = locationHistory[locationHistory.length - 1];
if (historicalLatestLoc && filteredDeviceData.latestDeviceInfo && filteredDeviceData.latestDeviceInfo.location) {
infoDate = new Date(filteredDeviceData.latestDeviceInfo.location.updatedTime);
locationDate = new Date(historicalLatestLoc.values.timeStamp);
}
if (infoDate < locationDate || filteredDeviceData.latestDeviceInfo.length === 0) {
filteredDeviceData.latestDeviceInfo.location = {};
filteredDeviceData.latestDeviceInfo.location.longitude = historicalLatestLoc.values.longitude;
filteredDeviceData.latestDeviceInfo.location.latitude = historicalLatestLoc.values.latitude;
filteredDeviceData.latestDeviceInfo.location.updatedTime = historicalLatestLoc.values.timeStamp;
}
}
//checking for the latest location information.
if (filteredDeviceData.latestDeviceInfo.location && locationInfo) {
var infoDate = new Date(filteredDeviceData.latestDeviceInfo.location.updatedTime);
var locationDate = new Date(locationInfo.updatedOn);
if (infoDate < locationDate) {
filteredDeviceData.latestDeviceInfo.location.longitude = locationInfo.longitude;
filteredDeviceData.latestDeviceInfo.location.latitude = locationInfo.latitude;
filteredDeviceData.latestDeviceInfo.location.updatedTime = locationInfo.updatedOn;
}
}
response["content"] = filteredDeviceData;
response["status"] = "success";
return response;
} else if (backendResponse.status == 401) {
response["status"] = "unauthorized";
return response;
} else if (backendResponse.status == 404) {
response["status"] = "notFound";
return response;
} else {
response["status"] = "error";
return response;
}
}
);
} catch (e) {
throw e;
} finally {
utility.endTenantFlow();
}
};
// Refactored methods
publicMethods.getDevicesCount = function () {
var carbonUser = session.get(constants.USER_SESSION_KEY);
if (carbonUser) {
var userModule = require("/app/modules/business-controllers/user.js")["userModule"];
var uiPermissions = userModule.getUIPermissions();
var url;
if (uiPermissions.LIST_DEVICES) {
url = devicemgtProps["httpsURL"] +
devicemgtProps["backendRestEndpoints"]["deviceMgt"] + "/devices?offset=0&limit=1";
} else if (uiPermissions.LIST_OWN_DEVICES) {
url = devicemgtProps["httpsURL"] + devicemgtProps["backendRestEndpoints"]["deviceMgt"] +
"/devices?offset=0&limit=1&user=" + carbonUser.username;
} else {
log.error("Access denied for user: " + carbonUser.username);
return -1;
}
return serviceInvokers.XMLHttp.get(
url, function (responsePayload) {
if(!responsePayload["responseText"]){
log.error("Error while fetching device count. API `" + url + "` returns HTTP: " + responsePayload["status"]);
userModule.logout(function () {
response.sendRedirect(devicemgtProps["appContext"] + "login");
});
}
return parse(responsePayload["responseText"])["count"];
},
function (responsePayload) {
log.error(responsePayload["responseText"]);
return -1;
}
);
} else {
log.error("User object was not found in the session");
userModule.logout(function () {
response.sendRedirect(devicemgtProps["appContext"] + "login");
});
}
};
publicMethods.getDeviceTypeCount = function () {
var carbonUser = session.get(constants.USER_SESSION_KEY);
if (carbonUser) {
var userModule = require("/app/modules/business-controllers/user.js")["userModule"];
var uiPermissions = userModule.getUIPermissions();
var url;
if (uiPermissions.LIST_OWN_DEVICES) {
url = devicemgtProps["httpsURL"] +
devicemgtProps["backendRestEndpoints"]["deviceMgt"] + "/device-types";
} else {
log.error("Access denied for user: " + carbonUser.username);
return -1;
}
return serviceInvokers.XMLHttp.get(
url, function (responsePayload) {
return parse(responsePayload["responseText"]).length;
},
function (responsePayload) {
log.error(responsePayload["responseText"]);
return -1;
}
);
} else {
log.error("User object was not found in the session");
userModule.logout(function () {
response.sendRedirect(devicemgtProps["appContext"] + "login");
});
}
};
publicMethods.getDeviceTypes = function () {
var url = devicemgtProps["httpsURL"] + devicemgtProps["backendRestEndpoints"]["deviceMgt"] + "/device-types";
var response = privateMethods.callBackend(url, constants["HTTP_GET"]);
if (response.status == "success") {
response.content = parse(response.content);
}
return response;
};
/*
@Updated
*/
// publicMethods.getLicense = function (deviceType) {
// var url;
// var license;
// if (deviceType == "windows") {
// url = mdmProps["httpURL"] + "/mdm-windows-agent/services/device/license";
// } else if (deviceType == "ios") {
// url = mdmProps["httpsURL"] + "/ios-enrollment/license/";
// }
// if (url != null && url != undefined) {
// serviceInvokers.XMLHttp.get(url, function (responsePayload) {
// license = responsePayload.text;
// }, function (responsePayload) {
// return null;
// });
// }
// return license;
// };
publicMethods.getDevices = function (userName) {
var url = devicemgtProps["httpsURL"] +
devicemgtProps["backendRestEndpoints"]["deviceMgt"] + "/devices";
if (userName && userName !== "") {
url = url + "?user=" + userName;
}
return serviceInvokers.XMLHttp.get(
url, function (responsePayload) {
var devices = JSON.parse(responsePayload.responseText).devices;
for (var i = 0; i < devices.length; i++) {
devices[i].thumb = utility.getDeviceThumb(devices[i].type);
}
return devices;
},
function (responsePayload) {
log.error(responsePayload);
return -1;
}
);
};
publicMethods.getDeviceAgentConfig = function (type, deviceId) {
var carbonUser = session.get(constants["USER_SESSION_KEY"]);
if (!carbonUser) {
log.error("User object was not found in the session");
userModule.logout(function () {
response.sendRedirect(devicemgtProps["appContext"] + "login");
});
}
var userName = carbonUser.username + "@" + carbonUser.domain;
var config = {};
config.type = type;
config.deviceId = deviceId;
// register a tenant based app at API Manager
var applicationName = type.replace(" ", "") + "_" + carbonUser.domain;
var requestURL = (devicemgtProps["oauthProvider"]["appRegistration"]
["apiManagerClientAppRegistrationServiceURL"]).replace("/tenants","");
var payload = {applicationName:applicationName, tags:["device_agent"],
isAllowedToAllDomains:false, validityPeriod: 3600};
serviceInvokers.XMLHttp.post(
requestURL, payload, function (responsePayload) {
var app = JSON.parse(responsePayload.responseText);
config.clientId = app["client_id"];
config.clientSecret = app["client_secret"];
if (config.clientId && config.clientSecret) {
var JWTClientManagerServicePackagePath =
"io.entgra.device.mgt.core.identity.jwt.client.extension.service.JWTClientManagerService";
//noinspection JSUnresolvedFunction, JSUnresolvedVariable
var JWTClientManagerService = carbon.server.osgiService(JWTClientManagerServicePackagePath);
//noinspection JSUnresolvedFunction
var jwtClient = JWTClientManagerService.getJWTClient();
// returning access token by JWT grant type
var deviceScope = "device_" + type.replace(" ", "") + "_" + deviceId + " dm:device:enroll " +
"dm:device:disenroll dm:device:modify dm:devices:ops:view dm:device:event:publish";
var tokenInfo = jwtClient.getAccessToken(config.clientId, config.clientSecret,
userName, deviceScope);
config.accessToken = tokenInfo.getAccessToken();
config.refreshToken = tokenInfo.getRefreshToken();
if (config.accessToken == null) {
return null;
}
config.mqttGateway = "tcp://" + process.getProperty("mqtt.broker.host") + ":" + process.getProperty("mqtt.broker.port");
config.httpsGateway = "https://" + process.getProperty("iot.gateway.host") + ":" + process.getProperty("iot.gateway.https.port");
config.httpGateway = "http://" + process.getProperty("iot.gateway.host") + ":" + process.getProperty("iot.gateway.http.port");
return config;
} else {
return null;
}
return config;
},
function (responsePayload) {
log.error(responsePayload);
return null;
}
);
return config;
};
/**
* Retrieve device info details of a device
* @param deviceType - Type of the device i.e ios, android
* @param deviceId - Device ID of te device
*/
publicMethods.getDeviceInfo = function (deviceType, deviceId) {
try {
var url = devicemgtProps["httpsURL"] + devicemgtProps["backendRestEndpoints"]["deviceMgt"]
+ "/devices/" + deviceType + "/" + deviceId + "/info";
var response = {};
return serviceInvokers.XMLHttp.get(
url,
function (backendResponse) {
if (backendResponse.status === 200 && backendResponse.responseText) {
response["status"] = "success";
response["content"] = parse(backendResponse.responseText);
} else {
log.error("Error occurred while retrieving device info via " + url + ". Error code: "
+ backendResponse.status + ". Reason: " + backendResponse.responseText);
response["status"] = "error";
}
return response;
});
} catch (e) {
log.error("Error occurred while retrieving device info via " + url, e);
}
};
return publicMethods;
}();

View File

@ -1,143 +0,0 @@
/*
* Copyright (c) 2018 - 2023, Entgra (Pvt) Ltd. (http://www.entgra.io) All Rights Reserved.
*
* Entgra (Pvt) Ltd. licenses this file to you under the Apache License,
* Version 2.0 (the "License"); you may not use this file except
* in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
var groupModule = {};
(function (groupModule) {
var log = new Log("/app/modules/business-controllers/group.js");
var userModule = require("/app/modules/business-controllers/user.js")["userModule"];
var constants = require('/app/modules/constants.js');
var devicemgtProps = require("/app/modules/conf-reader/main.js")["conf"];
var utility = require("/app/modules/utility.js").utility;
var serviceInvokers = require("/app/modules/oauth/token-protected-service-invokers.js")["invokers"];
var deviceServiceEndpoint = devicemgtProps["httpsURL"] + "/api/device-mgt/v1.0";
var user = session.get(constants.USER_SESSION_KEY);
var endPoint;
groupModule.getGroupCount = function () {
var permissions = userModule.getUIPermissions();
if (permissions.LIST_ALL_GROUPS) {
endPoint = deviceServiceEndpoint + "/admin/groups/count";
} else if (permissions.LIST_GROUPS) {
endPoint = deviceServiceEndpoint + "/groups/count";
} else {
if (!user) {
log.error("User object was not found in the session");
userModule.logout(function () {
response.sendRedirect(devicemgtProps["appContext"] + "login");
});
}
log.error("Access denied for user: " + user.username);
return -1;
}
return serviceInvokers.XMLHttp.get(
endPoint, function (responsePayload) {
return parse(responsePayload["responseText"]);
},
function (responsePayload) {
log.error(responsePayload["responseText"]);
return -1;
}
);
};
groupModule.getGroupDeviceCount = function (groupId) {
endPoint = deviceServiceEndpoint + "/groups/id/" + groupId + "/devices/count";
return serviceInvokers.XMLHttp.get(
endPoint, function (responsePayload) {
return responsePayload["responseText"];
},
function (responsePayload) {
log.error(responsePayload);
return -1;
}
);
};
groupModule.getGroupDevices = function (groupId) {
endPoint = deviceServiceEndpoint + "/groups/id/" + groupId + "/devices?limit=10";
return serviceInvokers.XMLHttp.get(
endPoint, function (responsePayload) {
return responsePayload;
},
function (responsePayload) {
log.error(responsePayload);
return responsePayload;
}
);
};
groupModule.getGroups = function () {
var permissions = userModule.getUIPermissions();
if (permissions.LIST_ALL_GROUPS) {
endPoint = deviceServiceEndpoint + "/admin/groups";
} else if (permissions.LIST_GROUPS) {
endPoint = deviceServiceEndpoint + "/groups";
} else {
log.error("Access denied for user: " + carbonUser.username);
return -1;
}
return serviceInvokers.XMLHttp.get(
endPoint, function (responsePayload) {
var data = JSON.parse(responsePayload.responseText);
if(data) {
return data.deviceGroups;
} else {
return [];
}
},
function (responsePayload) {
log.error(responsePayload);
return -1;
}
);
};
groupModule.getGroup = function (groupId) {
return serviceInvokers.XMLHttp.get(
deviceServiceEndpoint + "/groups/id/" + groupId, function (responsePayload) {
return JSON.parse(responsePayload.responseText);
},
function (responsePayload) {
log.error(responsePayload);
return -1;
}
);
};
groupModule.getRolesOfGroup = function (groupId) {
return serviceInvokers.XMLHttp.get(
deviceServiceEndpoint + "/groups/id/" + groupId + "/roles", function (responsePayload) {
var data = JSON.parse(responsePayload.responseText);
if(data) {
return data.roles;
} else {
return [];
}
},
function (responsePayload) {
log.error(responsePayload);
return -1;
}
);
};
}(groupModule));

View File

@ -1,168 +0,0 @@
/*
* Copyright (c) 2018 - 2023, Entgra (Pvt) Ltd. (http://www.entgra.io) All Rights Reserved.
*
* Entgra (Pvt) Ltd. licenses this file to you under the Apache License,
* Version 2.0 (the "License"); you may not use this file except
* in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
var operationModule = function () {
var log = new Log("/app/modules/business-controllers/operation.js");
var utility = require('/app/modules/utility.js').utility;
var constants = require('/app/modules/constants.js');
var devicemgtProps = require("/app/modules/conf-reader/main.js")["conf"];
var serviceInvokers = require("/app/modules/oauth/token-protected-service-invokers.js")["invokers"];
var publicMethods = {};
var privateMethods = {};
/**
* This method reads the token from the Token client and return the access token.
* If the token pair s not set in the session this will send a redirect to the login page.
*/
function getAccessToken(deviceType, owner, deviceId) {
var TokenClient = Packages.org.wso2.carbon.device.mgt.iot.apimgt.TokenClient;
var accessTokenClient = new TokenClient(deviceType);
var accessTokenInfo = accessTokenClient.getAccessToken(owner, deviceId);
return accessTokenInfo.getAccess_token();
}
privateMethods.getOperationsFromFeatures = function (deviceType, operationType) {
var url = devicemgtProps["httpsURL"] + devicemgtProps["backendRestEndpoints"]["deviceMgt"] + "/device-types/"
+ deviceType + "/features?featureType=" + operationType + "&hidden=false";
return serviceInvokers.XMLHttp.get(url, function (responsePayload) {
var features = JSON.parse(responsePayload.responseText);
var featureList = [];
var feature;
for (var i = 0; i < features.length; i++) {
feature = {};
feature["operation"] = features[i].code;
feature["name"] = features[i].name;
feature["description"] = features[i].description;
feature["contentType"] = features[i].contentType;
feature["deviceType"] = deviceType;
feature["params"] = [];
var metaData = features[i].metadataEntries;
if (metaData) {
for (var j = 0; j < metaData.length; j++) {
if (metaData[j].name === "operationMeta") {
var operationMeta = metaData[j].value;
var params = {};
params["method"] = operationMeta.method;
params["pathParams"] = operationMeta.pathParams;
params["queryParams"] = operationMeta.queryParams;
params["formParams"] = operationMeta.formParams ? operationMeta.formParams : [];
params["uri"] = operationMeta.uri;
params["contentType"] = operationMeta.contentType;
feature["params"].push(params);
feature["permission"] = operationMeta.permission;
if (operationMeta.icon) {
//Check if icon is a path or font
if (operationMeta.icon.indexOf("path:") === 0) {
feature["icon"] = operationMeta.icon.replace("path:", "");
} else {
feature["iconFont"] = operationMeta.icon;
}
}
if (operationMeta.uiParams && operationMeta.uiParams.length > 0) {
feature["uiParams"] = operationMeta.uiParams;
}
if (operationMeta.filters) {
feature["filters"] = operationMeta.filters;
}
if (operationMeta.ownershipDescription) {
feature["ownershipDescription"] = operationMeta.ownershipDescription;
}
continue;
}
feature["metadata"].push(metaData[j].value);
}
featureList.push(feature);
}
}
return featureList;
}, function (responsePayload) {
var response = {};
response["status"] = "error";
return response;
}
);
};
publicMethods.getControlOperations = function (device) {
var deviceType = device.type;
var operations = privateMethods.getOperationsFromFeatures(deviceType, "operation");
for (var op in operations) {
if (operations.hasOwnProperty(op)) {
operations[op]["isDisabled"] = false;
if (device && operations[op].filters && operations[op].filters.length > 0) {
var filters = operations[op].filters;
for (var filter in filters) {
if (filters.hasOwnProperty(filter)) {
if (device[filters[filter].property] !== filters[filter].value) {
operations[op]["isDisabled"] = true;
operations[op]["disabledText"] = operations[op]["disabledText"] ?
operations[op]["disabledText"] + ", " + filters[filter].description :
filters[filter].description;
}
}
}
}
}
}
return operations;
};
publicMethods.getMonitorOperations = function (deviceType) {
return privateMethods.getOperationsFromFeatures(deviceType, "monitor");
};
publicMethods.handlePOSTOperation = function (deviceType, operation, deviceId, params) {
var user = session.get(constants.USER_SESSION_KEY);
var endPoint = devicemgtProps["httpsURL"] + '/' + deviceType + "/controller/" + operation;
var header = '{"owner":"' + user.username + '","deviceId":"' + deviceId +
'","protocol":"mqtt", "sessionId":"' + session.getId() + '", "' +
constants.AUTHORIZATION_HEADER + '":"' + constants.BEARER_PREFIX +
getAccessToken(deviceType, user.username, deviceId) + '"}';
return post(endPoint, params, JSON.parse(header), "json");
};
publicMethods.handleGETOperation = function (deviceType, operation, operationName, deviceId) {
var user = session.get(constants.USER_SESSION_KEY);
var endPoint = devicemgtProps["httpsURL"] + '/' + deviceType + "/controller/" + operation;
var header = '{"owner":"' + user.username + '","deviceId":"' + deviceId +
'","protocol":"mqtt", "' + constants.AUTHORIZATION_HEADER + '":"' +
constants.BEARER_PREFIX + getAccessToken(deviceType, user.username, deviceId) +
'"}';
var result = get(endPoint, {}, JSON.parse(header), "json");
if (result.data) {
var values = result.data.sensorValue.split(',');
if (operationName == 'gps') {
result.data.map = {
lat: parseFloat(values[0]),
lng: parseFloat(values[1])
}
} else {
var sqSum = 0;
for (var v in values) {
sqSum += Math.pow(values[v], 2);
}
result.data[operationName] = Math.sqrt(sqSum);
}
delete result.data['sensorValue'];
}
return result;
};
return publicMethods;
}();

View File

@ -1,282 +0,0 @@
/*
* Copyright (c) 2018 - 2023, Entgra (Pvt) Ltd. (http://www.entgra.io) All Rights Reserved.
*
* Entgra (Pvt) Ltd. licenses this file to you under the Apache License,
* Version 2.0 (the "License"); you may not use this file except
* in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
var policyModule;
policyModule = function () {
var log = new Log("/app/modules/business-controllers/policy.js");
var constants = require('/app/modules/constants.js');
var utility = require("/app/modules/utility.js")["utility"];
var devicemgtProps = require("/app/modules/conf-reader/main.js")["conf"];
var serviceInvokers = require("/app/modules/oauth/token-protected-service-invokers.js")["invokers"];
var publicMethods = {};
var privateMethods = {};
privateMethods.handleGetAllPoliciesResponse = function (backendResponse) {
var response = {};
if (backendResponse.status == 200 && backendResponse.responseText) {
var isUpdated = false;
var policyListFromRestEndpoint = parse(backendResponse.responseText)["policies"];
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"];
policyObjectFromRestEndpoint["policyType"] = policyListFromRestEndpoint["policyType"];
var payloadVersion = policyObjectFromRestEndpoint["policyPayloadVersion"];
if (!parseFloat(payloadVersion) >= 2.0) {
policyObjectFromRestEndpoint["correctiveActions"] = policyListFromRestEndpoint["correctiveActions"];
}
if (policyObjectToView["platform"] == "ios") {
policyObjectToView["deviceTypeIcon"] = "apple";
} else {
policyObjectToView["deviceTypeIcon"] = policyObjectToView["platform"];
}
var ownershipType = "None";
var deviceGroups = policyObjectFromRestEndpoint["deviceGroups"];
if (deviceGroups) {
for (var j = 0; j < deviceGroups.length; j++) {
var deviceGroup = deviceGroups[j];
if (deviceGroup.name === "COPE") {
ownershipType = (ownershipType === "BYOD") ? "BYOD & COPE" : "COPE";
} else if (deviceGroup.name === "BYOD") {
ownershipType = (ownershipType === "COPE") ? "BYOD & COPE" : "BYOD";
}
}
}
policyObjectToView["ownershipType"] = ownershipType;
var assignedRoleCount = policyObjectFromRestEndpoint["roles"].length;
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] + ", ...";
}
policyObjectToView["compliance"] = policyObjectFromRestEndpoint["compliance"];
if (policyObjectFromRestEndpoint["active"] == true &&
policyObjectFromRestEndpoint["updated"] == true) {
policyObjectToView["status"] = "Active/Updated";
isUpdated = true;
} else if (policyObjectFromRestEndpoint["active"] == true &&
policyObjectFromRestEndpoint["updated"] == false) {
policyObjectToView["status"] = "Active";
} else if (policyObjectFromRestEndpoint["active"] == false &&
policyObjectFromRestEndpoint["updated"] == true) {
policyObjectToView["status"] = "Inactive/Updated";
isUpdated = true;
} else if (policyObjectFromRestEndpoint["active"] == false &&
policyObjectFromRestEndpoint["updated"] == false) {
policyObjectToView["status"] = "Inactive";
}
// push view-objects to list
policyListToView.push(policyObjectToView);
}
// generate response
response.updated = isUpdated;
response.status = "success";
response.content = 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;
}
};
/*
@Updated
*/
publicMethods.getAllPolicies = function () {
var carbonUser = session.get(constants["USER_SESSION_KEY"]);
if (!carbonUser) {
log.error("User object was not found in the session");
userModule.logout(function () {
response.sendRedirect(devicemgtProps["appContext"] + "login");
});
}
try {
var url = devicemgtProps["httpsURL"] + devicemgtProps["backendRestEndpoints"]["deviceMgt"] +
"/policies?offset=0&limit=100";
return serviceInvokers.XMLHttp.get(url, privateMethods.handleGetAllPoliciesResponse);
} catch (e) {
throw e;
}
};
/**
* Retrieve all policies based on policy type
*/
publicMethods.getAllPoliciesByType = function (policyType) {
var carbonUser = session.get(constants["USER_SESSION_KEY"]);
if (!carbonUser) {
log.error("User object was not found in the session");
userModule.logout(function () {
response.sendRedirect(devicemgtProps["appContext"] + "login");
});
}
try {
var url = devicemgtProps["httpsURL"] + devicemgtProps["backendRestEndpoints"]["deviceMgt"] +
"/policies/type/" + policyType + "?offset=0&limit=100";
return serviceInvokers.XMLHttp.get(url, privateMethods.handleGetAllPoliciesResponse);
} catch (e) {
log.error("Error occurred while retrieving policies by policy type " + policyType);
throw e;
}
};
/*
Get policies count from backend services.
*/
publicMethods.getPoliciesCount = function () {
var carbonUser = session.get(constants["USER_SESSION_KEY"]);
if (!carbonUser) {
log.error("User object was not found in the session");
userModule.logout(function () {
response.sendRedirect(devicemgtProps["appContext"] + "login");
});
}
try {
var url = devicemgtProps["httpsURL"] + devicemgtProps["backendRestEndpoints"]["deviceMgt"] +
"/policies?offset=0&limit=1";
return serviceInvokers.XMLHttp.get(
url, function (responsePayload) {
return parse(responsePayload["responseText"])["count"];
},
function (responsePayload) {
log.error(responsePayload["responseText"]);
return -1;
}
);
} catch (e) {
throw e;
}
};
/*
Get apps available in the store from backend service.
*/
publicMethods.getStoreAppsForPolicy = function () {
var carbonUser = session.get(constants["USER_SESSION_KEY"]);
if (!carbonUser) {
log.error("User object was not found in the session");
userModule.logout(function () {
response.sendRedirect(devicemgtProps["appContext"] + "login");
});
}
try {
var url = devicemgtProps["managerHTTPSURL"] + devicemgtProps["backendRestEndpoints"]["appMgt"] +
"/applications";
var data = {
limit: -1
};
return serviceInvokers.XMLHttp.post(url, data,
function (backendResponse) {
var response = {};
if (backendResponse.status === 200 && backendResponse.responseText) {
var appListFromRestEndpoint = parse(backendResponse.responseText)["applications"];
var storeApps = [];
var i, appObjectFromRestEndpoint, appObjectToView;
for (i=0; i<appListFromRestEndpoint.length; i++) {
appObjectFromRestEndpoint = appListFromRestEndpoint[i];
appObjectToView = {};
appObjectToView["appName"] = appObjectFromRestEndpoint["name"];
appObjectToView["packageName"] = appObjectFromRestEndpoint["packageName"];
appObjectToView["appId"] = appObjectFromRestEndpoint["id"];
if ("WEB_CLIP" === appObjectFromRestEndpoint["type"]) {
appObjectToView["type"] = "Web Clip"
} else {
appObjectToView["type"] = "Mobile App"
}
appObjectToView["uuid"] = appObjectFromRestEndpoint["applicationReleases"][0]["uuid"];
appObjectToView["version"] = appObjectFromRestEndpoint["applicationReleases"][0]["version"];
appObjectToView["platform"] = appObjectFromRestEndpoint["deviceType"];
storeApps.push(appObjectToView);
}
response.status = "success";
response.content = storeApps;
return response;
} else {
response.status = "error";
if (backendResponse.responseText === "Scope validation failed") {
response.content = "Permission Denied";
} else {
response.content = backendResponse.responseText;
}
return response;
}
});
} catch (e) {
throw e;
}
};
/*
@Updated - used by getAllPolicies
*/
privateMethods.getElementsInAString = function (elementList) {
var i, elementsInAString = "";
for (i = 0; i < elementList.length; i++) {
if (i == elementList.length - 1) {
elementsInAString += elementList[i];
} else {
elementsInAString += elementList[i] + ", ";
}
}
return elementsInAString;
};
return publicMethods;
}();

View File

@ -1,760 +0,0 @@
/*
* Copyright (c) 2018 - 2023, Entgra (Pvt) Ltd. (http://www.entgra.io) All Rights Reserved.
*
* Entgra (Pvt) Ltd. licenses this file to you under the Apache License,
* Version 2.0 (the "License"); you may not use this file except
* in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
/*
* This module contains user and roles related functionality.
*/
var userModule = function () {
var log = new Log("/app/modules/business-controllers/user.js");
var constants = require("/app/modules/constants.js");
var utility = require("/app/modules/utility.js")["utility"];
var devicemgtProps = require("/app/modules/conf-reader/main.js")["conf"];
var serviceInvokers = require("/app/modules/oauth/token-protected-service-invokers.js")["invokers"];
/* Initializing user manager */
var carbon = require("carbon");
var url = carbon.server.address("https") + "/admin/services";
var server = new carbon.server.Server(url);
var publicMethods = {};
var privateMethods = {};
/**
* Get the carbon user object from the session. If not found - it will throw a user not found error.
* @returns {object} carbon user object
*/
publicMethods.getCarbonUser = function () {
var carbon = require("carbon");
var carbonUser = session.get(constants["USER_SESSION_KEY"]);
var utility = require("/app/modules/utility.js")["utility"];
if (!carbonUser) {
log.error("User object was not found in the session");
throw constants["ERRORS"]["USER_NOT_FOUND"];
}
return carbonUser;
};
/**
* Only GET method is implemented for now since there are no other type of methods used this method.
* @param url - URL to call the backend without the host
* @param method - HTTP Method (GET, POST)
* @returns An object with 'status': 'success'|'error', 'content': {}
*/
privateMethods.callBackend = function (url, method) {
if (constants["HTTP_GET"] == method) {
return serviceInvokers.XMLHttp.get(url,
function (backendResponse) {
var response = {};
response.content = backendResponse.responseText;
if (backendResponse.status == 200) {
response.status = "success";
} else if (backendResponse.status == 400 || backendResponse.status == 401 ||
backendResponse.status == 404 || backendResponse.status == 500) {
response.status = "error";
}
return response;
}
);
} else {
log.error("Runtime error : This method only support HTTP GET requests.");
}
};
/**
* Build default user claims.
*
* @param firstname First name of the user
* @param lastname Last name of the user
* @param emailAddress Email address of the user
*
* @returns {Object} Default user claims to be provided
*/
privateMethods.buildDefaultUserClaims = function (firstname, lastname, emailAddress) {
var defaultUserClaims = {
"http://wso2.org/claims/givenname": firstname,
"http://wso2.org/claims/lastname": lastname,
"http://wso2.org/claims/emailaddress": emailAddress
};
if (log.isDebugEnabled()) {
log.debug("ClaimMap created for new user : " + stringify(defaultUserClaims));
}
return defaultUserClaims;
};
/**
* Register user to dc-user-store.
*
* @param username Username of the user
* @param firstname First name of the user
* @param lastname Last name of the user
* @param emailAddress Email address of the user
* @param password Password of the user
* @param userRoles Roles assigned to the user
*
* @returns {number} HTTP Status code 201 if succeeded, 409 if user already exists
*/
publicMethods.registerUser = function (username, firstname, lastname, emailAddress, password, userRoles) {
var carbon = require('carbon');
var tenantId = carbon.server.tenantId();
var url = carbon.server.address('https') + "/admin/services";
var server = new carbon.server.Server(url);
var userManager = new carbon.user.UserManager(server, tenantId);
try {
if (userManager.userExists(username)) {
if (log.isDebugEnabled()) {
log.debug("A user with name '" + username + "' already exists.");
}
// http status code 409 refers to - conflict.
return constants.HTTP_CONFLICT;
} else {
var defaultUserClaims = privateMethods.buildDefaultUserClaims(firstname, lastname, emailAddress);
userManager.addUser(username, password, userRoles, defaultUserClaims, "default");
if (log.isDebugEnabled()) {
log.debug("A new user with name '" + username + "' was created.");
}
// http status code 201 refers to - created.
return constants.HTTP_CREATED;
}
} catch (e) {
throw e;
}
};
/*
@Updated
*/
publicMethods.getUsers = function () {
var carbonUser = session.get(constants["USER_SESSION_KEY"]);
var utility = require("/app/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 url = devicemgtProps["httpsURL"] + devicemgtProps["backendRestEndpoints"]["deviceMgt"] + "/users?offset=0&limit=100";
var response = privateMethods.callBackend(url, constants["HTTP_GET"]);
if (response.status == "success") {
response.content = parse(response.content).users;
}
return response;
} catch (e) {
throw e;
} finally {
utility.endTenantFlow();
}
};
/*
Get users count from backend services.
*/
publicMethods.getUsersCount = function () {
var carbonUser = session.get(constants["USER_SESSION_KEY"]);
var utility = require("/app/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 url = devicemgtProps["httpsURL"] + devicemgtProps["backendRestEndpoints"]["deviceMgt"] + "/users/count";
return serviceInvokers.XMLHttp.get(
url, function (responsePayload) {
return parse(responsePayload["responseText"])["count"];
},
function (responsePayload) {
log.error(responsePayload["responseText"]);
return -1;
}
);
} catch (e) {
throw e;
} finally {
utility.endTenantFlow();
}
};
/**
* Return a User object from the backend by calling the JAX-RS
* @param username
* @returns {object} a response object with status and content on success.
*/
publicMethods.getUser = function (username) {
var carbonUser = publicMethods.getCarbonUser();
var domain;
if (username.indexOf('/') > 0) {
domain = username.substr(0, username.indexOf('/'));
username = username.substr(username.indexOf('/') + 1);
}
try {
utility.startTenantFlow(carbonUser);
var url = devicemgtProps["httpsURL"] + devicemgtProps["backendRestEndpoints"]["deviceMgt"] + "/users/" +
encodeURIComponent(username);
if (domain) {
url += '?domain=' + encodeURIComponent(domain);
}
var response = privateMethods.callBackend(url, constants["HTTP_GET"]);
response["content"] = parse(response.content);
response["userDomain"] = carbonUser.domain;
return response;
} catch (e) {
throw e;
} finally {
utility.endTenantFlow();
}
};
/**
* Returns a set of roles assigned to a particular user
* @param username
* @returns {object} a response object with status and content on success.
*/
publicMethods.getRolesByUsername = function (username) {
var carbonUser = publicMethods.getCarbonUser();
var domain;
if (username.indexOf('/') > 0) {
domain = username.substr(0, username.indexOf('/'));
username = username.substr(username.indexOf('/') + 1);
}
try {
utility.startTenantFlow(carbonUser);
var url = devicemgtProps["httpsURL"] + devicemgtProps["backendRestEndpoints"]["deviceMgt"] + "/users/" +
encodeURIComponent(username) + "/roles";
if (domain) {
url += '?domain=' + encodeURIComponent(domain);
}
var response = privateMethods.callBackend(url, constants["HTTP_GET"]);
if (response.status == "success") {
response.content = parse(response.content).roles;
}
return response;
} catch (e) {
throw e;
} finally {
utility.endTenantFlow();
}
};
/*
@NewlyAdded
*/
publicMethods.getUsersByUsername = function () {
var carbonUser = session.get(constants["USER_SESSION_KEY"]);
var utility = require("/app/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 url = devicemgtProps["httpsURL"] + "/mdm-admin/users/users-by-username";
return privateMethods.callBackend(url, constants["HTTP_GET"]);
} catch (e) {
throw e;
} finally {
utility.endTenantFlow();
}
};
/*
@Updated
*/
/**
* Get User Roles from user store (Internal roles not included).
*/
publicMethods.getRoles = function () {
var carbonUser = session.get(constants["USER_SESSION_KEY"]);
var utility = require("/app/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 url = devicemgtProps["httpsURL"] + devicemgtProps["backendRestEndpoints"]["deviceMgt"] +
"/roles?offset=0&limit=100&user-store=all";
var response = privateMethods.callBackend(url, constants["HTTP_GET"]);
if (response.status == "success") {
response.content = parse(response.content).roles;
}
return response;
} catch (e) {
throw e;
} finally {
utility.endTenantFlow();
}
};
/**
* Get User Roles from user store (Internal roles not included).
*/
publicMethods.getFilteredRoles = function (prefix) {
var carbonUser = session.get(constants["USER_SESSION_KEY"]);
var utility = require("/app/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 url = devicemgtProps["httpsURL"] + devicemgtProps["backendRestEndpoints"]["deviceMgt"] +
"/roles/filter/" + prefix + "?offset=0&limit=100&user-store=all";
var response = privateMethods.callBackend(url, constants["HTTP_GET"]);
if (response.status == "success") {
response.content = parse(response.content);
}
return response;
} catch (e) {
throw e;
} finally {
utility.endTenantFlow();
}
};
/**
* Get User Roles count from user store (Internal roles not included).
*/
publicMethods.getRolesCount = function () {
var carbonUser = session.get(constants["USER_SESSION_KEY"]);
var utility = require("/app/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 url = devicemgtProps["httpsURL"] + devicemgtProps["backendRestEndpoints"]["deviceMgt"] +
"/roles?offset=0&limit=1&user-store=all";
return serviceInvokers.XMLHttp.get(
url, function (responsePayload) {
return parse(responsePayload["responseText"])["count"];
},
function (responsePayload) {
log.error(responsePayload["responseText"]);
return -1;
}
);
} catch (e) {
throw e;
} finally {
utility.endTenantFlow();
}
};
/*
@Updated
*/
/**
* 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) {
userStore = userStore ? userStore : "all";
var carbonUser = session.get(constants["USER_SESSION_KEY"]);
var utility = require("/app/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 url = devicemgtProps["httpsURL"] + devicemgtProps["backendRestEndpoints"]["deviceMgt"] +
"/roles?user-store=" + encodeURIComponent(userStore) + "&limit=100";
var response = privateMethods.callBackend(url, constants["HTTP_GET"]);
if (response.status == "success") {
response.content = parse(response.content).roles;
}
return response;
} catch (e) {
throw e;
} finally {
utility.endTenantFlow();
}
};
/**
* Get Platforms.
* @deprecated moved this device module under getDeviceTypes.
*/
//TODO Move this piece of logic out of user.js to somewhere else appropriate.
publicMethods.getPlatforms = function () {
var carbonUser = session.get(constants["USER_SESSION_KEY"]);
var utility = require("/app/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 url = devicemgtProps["httpsURL"] + devicemgtProps["backendRestEndpoints"]["deviceMgt"] + "/device-types";
var response = privateMethods.callBackend(url, constants["HTTP_GET"]);
if (response.status == "success") {
response.content = parse(response.content);
}
return response;
} catch (e) {
throw e;
} finally {
utility.endTenantFlow();
}
};
/**
* Get role
*/
publicMethods.getRole = function (roleName) {
var carbonUser = session.get(constants["USER_SESSION_KEY"]);
var utility = require("/app/modules/utility.js")["utility"];
var userStore;
if (!carbonUser) {
log.error("User object was not found in the session");
throw constants["ERRORS"]["USER_NOT_FOUND"];
}
try {
utility.startTenantFlow(carbonUser);
if (roleName.indexOf('/') > 0) {
userStore = roleName.substr(0, roleName.indexOf('/'));
roleName = roleName.substr(roleName.indexOf('/') + 1);
}
var url = devicemgtProps["httpsURL"] + devicemgtProps["backendRestEndpoints"]["deviceMgt"] +
"/roles/" + encodeURIComponent(roleName);
if (userStore) {
url += "?user-store=" + encodeURIComponent(userStore);
}
var response = privateMethods.callBackend(url, constants["HTTP_GET"]);
if (response.status == "success") {
response.content = parse(response.content);
}
return response;
} catch (e) {
throw e;
} finally {
utility.endTenantFlow();
}
};
/**
* Authenticate a user when he or she attempts to login to MDM.
*
* @param username Username of the user
* @param password Password of the user
* @param successCallback Function to be called at the event of successful authentication
* @param failureCallback Function to be called at the event of failed authentication
*/
publicMethods.login = function (username, password, successCallback, failureCallback) {
var carbonModule = require("carbon");
var carbonServer = application.get("carbonServer");
try {
// check if the user is an authenticated user.
var isAuthenticated = carbonServer.authenticate(username, password);
if (!isAuthenticated) {
failureCallback("authentication");
return;
}
var tenantUser = carbonModule.server.tenantUser(username);
var isAuthorizedToLogin = privateMethods.isAuthorizedToLogin(tenantUser);
if (!isAuthorizedToLogin) {
failureCallback("authorization");
return;
}
session.put(constants.USER_SESSION_KEY, tenantUser);
successCallback(tenantUser);
} catch (e) {
throw e;
}
};
publicMethods.logout = function (successCallback) {
session.invalidate();
successCallback();
};
publicMethods.isAuthorized = function (permission) {
var carbon = require("carbon");
var carbonServer = application.get("carbonServer");
var carbonUser;
try {
carbonUser = session.get(constants.USER_SESSION_KEY);
} catch (e) {
log.error("User object was not found in the session");
carbonUser = null;
}
var utility = require('/app/modules/utility.js').utility;
if (!carbonUser) {
log.error("User object was not found in the session");
response.sendError(401, constants.ERRORS.USER_NOT_FOUND);
exit();
}
try {
utility.startTenantFlow(carbonUser);
var tenantId = carbon.server.tenantId();
var userManager = new carbon.user.UserManager(server, tenantId);
var user = new carbon.user.User(userManager, carbonUser.username);
return user.isAuthorized(permission, "ui.execute");
} catch (e) {
throw e;
} finally {
utility.endTenantFlow();
}
};
privateMethods.isAuthorizedToLogin = function(carbonUser) {
var utility = require('/app/modules/utility.js').utility;
try {
utility.startTenantFlow(carbonUser);
var tenantId = carbon.server.tenantId();
var userManager = new carbon.user.UserManager(server, tenantId);
var user = new carbon.user.User(userManager, carbonUser.username);
return user.isAuthorized("/permission/admin/login", "ui.execute");
} catch (e) {
throw e;
} finally {
utility.endTenantFlow();
}
};
publicMethods.getUIPermissions = function () {
var permissions = {};
if (publicMethods.isAuthorized("/permission/admin/device-mgt/devices/any-device")) {
permissions["LIST_DEVICES"] = true;
permissions["LIST_OWN_DEVICES"] = true;
}
if (publicMethods.isAuthorized("/permission/admin/device-mgt/devices/owning-device/view")) {
permissions["LIST_OWN_DEVICES"] = true;
}
if (publicMethods.isAuthorized("/permission/admin/device-mgt/admin/groups/view")) {
permissions["LIST_ALL_GROUPS"] = true;
}
if (publicMethods.isAuthorized("/permission/admin/device-mgt/groups/view")) {
permissions["LIST_GROUPS"] = true;
}
if (publicMethods.isAuthorized("/permission/admin/device-mgt/users/list")) {
permissions["LIST_USERS"] = true;
}
if (publicMethods.isAuthorized("/permission/admin/device-mgt/roles/list")) {
permissions["LIST_ROLES"] = true;
}
if (publicMethods.isAuthorized("/permission/admin/device-mgt/policies/list")) {
permissions["LIST_ALL_POLICIES"] = true;
}
if (publicMethods.isAuthorized("/permission/admin/device-mgt/user/policies/list")) {
permissions["LIST_POLICIES"] = true;
}
if (publicMethods.isAuthorized("/permission/admin/device-mgt/devices/enroll")) {
permissions["ADD_DEVICE"] = true;
}
if (publicMethods.isAuthorized("/permission/admin/device-mgt/groups/add")) {
permissions["ADD_GROUP"] = true;
}
if (publicMethods.isAuthorized("/permission/admin/device-mgt/users/add")) {
permissions["ADD_USER"] = true;
}
if (publicMethods.isAuthorized("/permission/admin/device-mgt/groups/devices/add")) {
permissions["ADD_GROUP_DEVICES"] = true;
}
if (publicMethods.isAuthorized("/permission/admin/device-mgt/groups/devices/remove")) {
permissions["REMOVE_GROUP_DEVICES"] = true;
}
if (publicMethods.isAuthorized("/permission/admin/device-mgt/groups/devices/view")) {
permissions["VIEW_GROUP_DEVICES"] = true;
}
if (publicMethods.isAuthorized("/permission/admin/device-mgt/groups/roles/view")) {
permissions["VIEW_GROUP_ROLES"] = true;
}
if (publicMethods.isAuthorized("/permission/admin/device-mgt/groups/update")) {
permissions["UPDATE_GROUP"] = true;
}
if (publicMethods.isAuthorized("/permission/admin/device-mgt/groups/share")) {
permissions["SHARE_GROUP"] = true;
}
if (publicMethods.isAuthorized("/permission/admin/device-mgt/users/remove")) {
permissions["REMOVE_USER"] = true;
}
if (publicMethods.isAuthorized("/permission/admin/device-mgt/groups/remove")) {
permissions["REMOVE_GROUP"] = true;
}
if (publicMethods.isAuthorized("/permission/admin/device-mgt/roles/add")) {
permissions["ADD_ROLE"] = true;
}
if (publicMethods.isAuthorized("/permission/admin/device-mgt/policies/add")) {
permissions["ADD_ADMIN_POLICY"] = true;
}
if (publicMethods.isAuthorized("/permission/admin/device-mgt/user/policies/add")) {
permissions["ADD_POLICY"] = true;
}
if (publicMethods.isAuthorized("/permission/admin/device-mgt/policies/priority")) {
permissions["CHANGE_POLICY_PRIORITY"] = true;
}
if (publicMethods.isAuthorized("/permission/admin/device-mgt/dashboard/view")) {
permissions["VIEW_DASHBOARD"] = true;
}
if (publicMethods.isAuthorized("/permission/admin/device-mgt/platform-configurations/view")) {
permissions["TENANT_CONFIGURATION"] = true;
}
if (publicMethods.isAuthorized("/permission/admin/device-mgt/certificates/manage")) {
permissions["CERTIFICATE_MANAGEMENT"] = true;
}
if (publicMethods.isAuthorized("/permission/admin/device-mgt/devices/change-status")) {
permissions["CHANGE_DEVICE_STATUS"] = true;
}
if (publicMethods.isAuthorized("/permission/admin/device-mgt")) {
permissions["IS_ADMIN"] = true;
}
if (publicMethods.isAuthorized("/permission/admin/device-mgt/topics/view")) {
permissions["VIEW_TOPICS"] = true;
}
if (publicMethods.isAuthorized("/permission/admin/device-mgt/admin/devices/update-enrollment")) {
permissions["UPDATE_ENROLLMENT"] = true;
}
if (publicMethods.isAuthorized("/permission/admin/device-mgt/admin/devices/permanent-delete")) {
permissions["PERMANENT_DELETE"] = true;
}
return permissions;
};
/**
* Add new role with permissions.
*
* @param roleName Name of the role
* @param users List of users to assign the role
* @param permissions List of permissions
*/
publicMethods.addRole = function (roleName, users, permissions) {
var carbon = require('carbon');
var tenantId = carbon.server.tenantId();
var url = carbon.server.address('https') + "/admin/services";
var server = new carbon.server.Server(url);
var userManager = new carbon.user.UserManager(server, tenantId);
try {
if (!userManager.roleExists(roleName)) {
userManager.addRole(roleName, users, permissions);
} else {
var array = Object.keys(permissions);
var i, permission;
for (i = 0; i < array.length; i++) {
permission = array[i];
userManager.authorizeRole(roleName, permission, "ui.execute");
}
}
} catch (e) {
throw e;
}
};
publicMethods.addPermissions = function (permissionList, path, init) {
var registry, carbon = require("carbon");
var carbonServer = application.get("carbonServer");
var utility = require('/app/modules/utility.js').utility;
var options = {system: true};
if (init == "login") {
try {
var carbonUser = session.get(constants.USER_SESSION_KEY);
if (!carbonUser) {
log.error("User object was not found in the session");
throw constants.ERRORS.USER_NOT_FOUND;
}
utility.startTenantFlow(carbonUser);
var tenantId = carbon.server.tenantId();
if (carbonUser) {
options.tenantId = tenantId;
}
registry = new carbon.registry.Registry(carbonServer, options);
var i, permission, resource;
for (i = 0; i < permissionList.length; i++) {
permission = permissionList[i];
resource = {
collection: true,
name: permission.name,
properties: {
name: permission.name
}
};
if (path != "") {
registry.put("/_system/governance/permission/admin/" + path + "/" + permission.key, resource);
} else {
registry.put("/_system/governance/permission/admin/" + permission.key, resource);
}
}
} catch (e) {
throw e;
} finally {
utility.endTenantFlow();
}
} else {
registry = new carbon.registry.Registry(carbonServer, options);
var i, permission, resource;
for (i = 0; i < permissionList.length; i++) {
permission = permissionList[i];
resource = {
collection: true,
name: permission.name,
properties: {
name: permission.name
}
};
if (path != "") {
registry.put("/_system/governance/permission/admin/" + path + "/" + permission.key, resource);
} else {
registry.put("/_system/governance/permission/admin/" + permission.key, resource);
}
}
}
};
/**
* Private method to be used by addUser() to
* retrieve secondary user stores.
* This needs Authentication since the method access admin services.
*
* @returns Array of secondary user stores.
*/
publicMethods.getSecondaryUserStores = function () {
var returnVal = [];
// To call the userstore admin service, user needs to have admin permission
if (publicMethods.isAuthorized("/permission/admin")) {
var endpoint = devicemgtProps["adminService"] + constants["USER_STORE_CONFIG_ADMIN_SERVICE_END_POINT"];
var wsPayload = "<xsd:getSecondaryRealmConfigurations xmlns:xsd='http://org.apache.axis2/xsd'/>";
serviceInvokers.WS.soapRequest(
"urn:getSecondaryRealmConfigurations",
wsPayload,
endpoint,
function (wsResponse) {
var domainIDs = stringify(wsResponse. * ::['return']. * ::domainId.text());
if (domainIDs != "\"\"") {
var regExpForSearch = new RegExp(constants["USER_STORES_NOISY_CHAR"], "g");
domainIDs = domainIDs.replace(regExpForSearch, "");
returnVal = domainIDs.split(constants["USER_STORES_SPLITTING_CHAR"]);
}
}, function (e) {
log.error("Error retrieving secondary user stores", e);
},
constants["SOAP_VERSION"]);
} else {
if (log.isDebugEnabled()) {
log.debug("User does not have admin permission to get the secondary user store details.");
}
}
return returnVal;
};
return publicMethods;
}();

View File

@ -1,62 +0,0 @@
/*
* Copyright (c) 2018 - 2023, Entgra (Pvt) Ltd. (http://www.entgra.io) All Rights Reserved.
*
* Entgra (Pvt) Ltd. licenses this file to you under the Apache License,
* Version 2.0 (the "License"); you may not use this file except
* in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
var conf = function () {
var cloudConf = application.get("CLOUD_CONF");
if (!cloudConf) {
cloudConf = require("/app/conf/toplink-menu.json");
var pinch = require("/app/modules/conf-reader/pinch.min.js")["pinch"];
var server = require("carbon")["server"];
var process = require("process");
pinch(cloudConf, /^/,
function (path, key, value) {
if ((typeof value === "string") && value.indexOf("%https.ip%") > -1) {
//noinspection JSUnresolvedFunction
return value.replace("%https.ip%", server.address("https"));
} else if ((typeof value === "string") && value.indexOf("%http.ip%") > -1) {
//noinspection JSUnresolvedFunction
return value.replace("%http.ip%", server.address("http"));
} else if ((typeof value === "string") && value.indexOf("%date-year%") > -1) {
var year = new Date().getFullYear();
return value.replace("%date-year%", year);
} else if ((typeof value === "string") && value.indexOf("%server.ip%") > -1) {
var getProperty = require("process").getProperty;
return value.replace("%server.ip%", getProperty("carbon.local.ip"));
} else {
var paramPattern = new RegExp("%(.*?)%", "g");
var out = value;
while ((matches = paramPattern.exec(value)) !== null) {
// This is necessary to avoid infinite loops with zero-width matches
if (matches.index === paramPattern.lastIndex) {
paramPattern.lastIndex++;
}
if (matches.length == 2) {
var property = process.getProperty(matches[1]);
if (property) {
out = out.replace(new RegExp("%" + matches[1] + "%", "g"), property);
}
}
}
return out;
}
}
);
application.put("CLOUD_CONF", cloudConf);
}
return cloudConf;
}();

View File

@ -1,64 +0,0 @@
/*
* Copyright (c) 2018 - 2023, Entgra (Pvt) Ltd. (http://www.entgra.io) All Rights Reserved.
*
* Entgra (Pvt) Ltd. licenses this file to you under the Apache License,
* Version 2.0 (the "License"); you may not use this file except
* in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
var conf = function () {
var conf = application.get("CONF");
if (!conf) {
conf = require("/app/conf/config.json");
var pinch = require("/app/modules/conf-reader/pinch.min.js")["pinch"];
var server = require("carbon")["server"];
var process = require("process");
pinch(conf, /^/,
function (path, key, value) {
if ((typeof value === "string") && value.indexOf("%https.ip%") > -1) {
//noinspection JSUnresolvedFunction
return value.replace("%https.ip%", server.address("https"));
} else if ((typeof value === "string") && value.indexOf("%http.ip%") > -1) {
//noinspection JSUnresolvedFunction
return value.replace("%http.ip%", server.address("http"));
} else if ((typeof value === "string") && value.indexOf("%date-year%") > -1) {
var year = new Date().getFullYear();
return value.replace("%date-year%", year);
} else if ((typeof value === "string") && value.indexOf("%server.ip%") > -1) {
var getProperty = require("process").getProperty;
return value.replace("%server.ip%", getProperty("carbon.local.ip"));
} else {
var paramPattern = new RegExp("%(.*?)%", "g");
var out = value;
while ((matches = paramPattern.exec(value)) !== null) {
// This is necessary to avoid infinite loops with zero-width matches
if (matches.index === paramPattern.lastIndex) {
paramPattern.lastIndex++;
}
if (matches.length == 2) {
var property = process.getProperty(matches[1]);
if (property) {
out = out.replace(new RegExp("%" + matches[1] + "%", "g"), property);
}
}
}
return out;
}
}
);
var DeviceConfigurationManager = Packages.io.entgra.device.mgt.core.device.mgt.core.config.DeviceConfigurationManager;
conf["serverConfig"] = DeviceConfigurationManager.getInstance().getDeviceManagementConfig();
application.put("CONF", conf);
}
return conf;
}();

View File

@ -1,26 +0,0 @@
/*
* Copyright (c) 2011 František Hába <hello@frantisekhaba.com>
*
* Permission is hereby granted, free of charge, to any person obtaining a copy of
* this software and associated documentation files (the 'Software'), to deal in
* the Software without restriction, including without limitation the rights to use,
* copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the
* Software, and to permit persons to whom the Software is furnished to do so,
* subject to the following conditions:
* The above copyright notice and this permission notice shall be included in all
* copies or substantial portions of the Software.
* THE SOFTWARE IS PROVIDED 'AS IS', WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL
* THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
* SOFTWARE.
*
* Reference:- https://github.com/Baggz/Pinch
* */
(function(){var k=function(a,c){return a.length!==c.length?!1:a.every(function(a,b){return c[b]===a})},j=function(a,c,d){var b,e;if("[object Array]"===Object.prototype.toString.call(a)){b=0;for(e=a.length;b<e;b++)c.apply(d,[b,a[b],a])}else for(b in a)a.hasOwnProperty(b)&&c.apply(d,[b,a[b],a])},h=function(a){for(var c=[],d=!1,b=0,e=a.length,f="",g=function(){f&&(c.push(f),f="")};b<e;b++)a[b].match(/\[|\]/)?(g(),d="]"===a[b]?!1:!0):'"'!==a[b]&&"'"!==a[b]&&("."===a[b]&&!d?g():f+=a[b]),b===e-1&&g();return c},
g=function(a,c,d){var b=-1!==["string","object"].indexOf(typeof a),e="string"===typeof c||c&&c.test&&c.exec,f=-1!==["string","object","function"].indexOf(typeof d);b&&e&&f&&("string"===typeof a?(this.instance=JSON.parse(a),this.json=!0):this.instance=a,this.pattern="string"===typeof c?c.replace(/'/g,'"'):c,this.replacement=d,this.createIndex(this.instance))};g.prototype.createIndex=function(a,c){var d=this;this.index=this.index||[];c=c||"";j(a,function(a,e){var f,a=a+"";f=a.match(/^[a-zA-Z]+$/)?c?
c+"."+a:a:a.match(/\d+/)?c+"["+a+"]":c+'["'+a+'"]';d.index.push(f);"object"===typeof e&&d.createIndex(e,f)})};g.prototype.replace=function(){var a=this;j(this.index,function(c,d){if(a.pattern&&a.pattern.test&&a.pattern.exec&&d.match(a.pattern))return a.replaceValue(d);if("string"===typeof a.pattern){var b=h(d),e=h(a.pattern);if(k(b,e))return a.replaceValue(d)}});return this.json?JSON.stringify(this.instance):this.instance};g.prototype.replaceValue=function(a){var c=this,d=h(a);d.reduce(function(b,
e,f){if(f===d.length-1)f="function"===typeof c.replacement?c.replacement(a,e,b[e]):c.replacement,b[e]=f;else return b[e]},this.instance)};var i=function(a,c,d,b){a=(new g(a,c,d)).replace();return"function"===typeof b?b(null,a):a};"undefined"!==typeof module&&module.exports?module.exports=i:"undefined"!==typeof define?define(function(){return i}):this.pinch=i})();

View File

@ -1,87 +0,0 @@
/*
* Copyright (c) 2018 - 2023, Entgra (Pvt) Ltd. (http://www.entgra.io) All Rights Reserved.
*
* Entgra (Pvt) Ltd. licenses this file to you under the Apache License,
* Version 2.0 (the "License"); you may not use this file except
* in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
var USER_SESSION_KEY = "_UUF_USER";
var UNSPECIFIED = "Unspecified";
var httpURL = "httpURL";
var httpsURL = "httpsURL";
var DEVICE_IDENTIFIER = "deviceIdentifier";
var DEVICE_NAME = "name";
var DEVICE_OWNERSHIP = "ownership";
var DEVICE_OWNER = "owner";
var DEVICE_TYPE = "type";
var DEVICE_VENDOR = "vendor";
var DEVICE_MODEL = "model";
var DEVICE_PRODUCT = "PRODUCT";
var DEVICE_OS_VERSION = "osVersion";
var DEVICE_OS_BUILD_DATE = "osBuildDate";
var DEVICE_PROPERTIES = "properties";
var DEVICE_ENROLLMENT_INFO = "enrolmentInfo";
var DEVICE_STATUS = "status";
var DEVICE_INFO = "deviceInfo";
var FEATURE_NAME = "featureName";
var FEATURE_DESCRIPTION = "featureDescription";
var PLATFORM_ANDROID = "android";
var PLATFORM_WINDOWS = "windows";
var PLATFORM_IOS = "ios";
var LANGUAGE_US = "en_US";
var VENDOR_APPLE = "Apple";
var ERRORS = {
"USER_NOT_FOUND": "USER_NOT_FOUND",
"UNKNOWN_ERROR": "Unknown Error"
};
var USER_STORES_NOISY_CHAR = "\"";
var USER_STORES_SPLITTING_CHAR = "\\n";
var USER_STORE_CONFIG_ADMIN_SERVICE_END_POINT =
"/services/UserStoreConfigAdminService.UserStoreConfigAdminServiceHttpsSoap12Endpoint/";
var SOAP_VERSION = 1.2;
var WEB_SERVICE_ADDRESSING_VERSION = 1.0;
var TOKEN_PAIR = "tokenPair";
var ENCODED_TENANT_BASED_CLIENT_APP_CREDENTIALS = "encodedTenantBasedClientAppCredentials";
var CONTENT_TYPE_IDENTIFIER = "Content-Type";
var ENCODED_TENANT_BASED_WEB_SOCKET_CLIENT_CREDENTIALS = "encodedTenantBasedWebSocketClientCredentials";
var CONTENT_DISPOSITION_IDENTIFIER = "Content-Disposition";
var APPLICATION_JSON = "application/json";
var APPLICATION_ZIP = "application/zip";
var STREAMING_FILES_ACCEPT_HEADERS = ["application/zip", "application/pdf", "application/octet-stream"];
var ACCEPT_IDENTIFIER = "Accept";
var AUTHORIZATION_HEADER= "Authorization";
var BEARER_PREFIX = "Bearer ";
var HTTP_GET = "GET";
var HTTP_POST = "POST";
var HTTP_PUT = "PUT";
var HTTP_DELETE = "DELETE";
var HTTP_CONFLICT = 409;
var HTTP_CREATED = 201;
var CACHED_CREDENTIALS = "tenantBasedCredentials";
var CACHED_CREDENTIALS_FOR_WEBSOCKET_APP = "tenantBasedWebSocketClientCredentials";
var ALLOWED_SCOPES = "scopes";
var SAML_TOKEN_KEY = "samlToken";
var SKIP_WELCOME_SCREEN ="skipWelcomeScreen";

View File

@ -1,51 +0,0 @@
/*
* Copyright (c) 2018 - 2023, Entgra (Pvt) Ltd. (http://www.entgra.io) All Rights Reserved.
*
* Entgra (Pvt) Ltd. licenses this file to you under the Apache License,
* Version 2.0 (the "License"); you may not use this file except
* in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
var carbonModule = require("carbon");
var devicemgtProps = require("/app/modules/conf-reader/main.js")["conf"];
var userModule = require("/app/modules/business-controllers/user.js")["userModule"];
//noinspection JSUnresolvedFunction Server
var carbonServer = new carbonModule.server.Server({
tenanted: true,
url: devicemgtProps["httpsURL"] + "/admin"
});
application.put("carbonServer", carbonServer);
var permissions = {
"/permission/admin/Login": ["ui.execute"],
"/permission/admin/manage/api/subscribe": ["ui.execute"],
"/permission/admin/device-mgt/device/api/subscribe": ["ui.execute"],
"/permission/admin/device-mgt/devices/enroll": ["ui.execute"],
"/permission/admin/device-mgt/devices/disenroll": ["ui.execute"],
"/permission/admin/device-mgt/devices/owning-device/view": ["ui.execute"],
"/permission/admin/manage/portal": ["ui.execute"]
};
var adminPermissions = {
"/permission/admin/device-mgt": ["ui.execute"],
"/permission/admin/manage/api": ["ui.execute"],
"/permission/admin/manage/portal": ["ui.execute"]
};
//On Startup, admin user will get both roles: devicemgt-admin and devicemgt-user
//Average user through sign-up will only receive the role: devicemgt-user.
//Admin can setup necessary permissions for the role: devicemgt-user
userModule.addRole("internal/devicemgt-user", ["admin"], permissions);
userModule.addRole("internal/devicemgt-admin", ["admin"], adminPermissions);

View File

@ -1,61 +0,0 @@
/*
* Copyright (c) 2018 - 2023, Entgra (Pvt) Ltd. (http://www.entgra.io) All Rights Reserved.
*
* Entgra (Pvt) Ltd. licenses this file to you under the Apache License,
* Version 2.0 (the "License"); you may not use this file except
* in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
var onSuccess;
var onFail;
(function () {
var log = new Log("/app/modules/login.js");
var constants = require("/app/modules/constants.js");
onSuccess = function (context) {
var utility = require("/app/modules/utility.js").utility;
var apiWrapperUtil = require("/app/modules/oauth/token-handlers.js")["handlers"];
try {
utility.startTenantFlow(context.user);
var APIManagementProviderService = utility.getAPIManagementProviderService();
var isLoaded = APIManagementProviderService.isTierLoaded();
if(!isLoaded && context.input.samlToken) {
session.put(constants.SKIP_WELCOME_SCREEN, false);
session.put(constants.SAML_TOKEN_KEY, context.input.samlToken);
return;
}
} finally {
utility.endTenantFlow();
}
session.put(constants.SKIP_WELCOME_SCREEN, true);
if (context.input.samlToken) {
//apiWrapperUtil.setupTokenPairBySamlGrantType(context.user.username + '@' + context.user.domain, context.input.samlToken);
/**
* Since the user can be verified using the sso.client.js we can use JWT grant type to issue the token for the user.
*/
apiWrapperUtil.setupTokenPairByJWTGrantType(context.user.username + '@' + context.user.domain, context.input.samlToken);
} else {
apiWrapperUtil.setupTokenPairByPasswordGrantType(context.input.username, context.input.password);
}
var devicemgtProps = require("/app/modules/conf-reader/main.js")["conf"];
var carbonServer = require("carbon").server;
if (!context.input.samlToken) {
(new carbonServer.Server({url: devicemgtProps["adminService"]}))
.login(context.input.username, context.input.password);
}
};
onFail = function (error) {
log.error(error.message);
}
})();

View File

@ -1,406 +0,0 @@
/*
* Copyright (c) 2018 - 2023, Entgra (Pvt) Ltd. (http://www.entgra.io) All Rights Reserved.
*
* Entgra (Pvt) Ltd. licenses this file to you under the Apache License,
* Version 2.0 (the "License"); you may not use this file except
* in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
var utils = function () {
var log = new Log("/app/modules/oauth/token-handler-utils.js");
var deviceMgtProps = require("/app/modules/conf-reader/main.js")["conf"];
var constants = require("/app/modules/constants.js");
var carbon = require("carbon");
var authModule = require("/lib/modules/auth/auth.js").module;
var utility = require('/app/modules/utility.js').utility;
//noinspection JSUnresolvedVariable
var Base64 = Packages.org.apache.commons.codec.binary.Base64;
//noinspection JSUnresolvedVariable
var String = Packages.java.lang.String;
var publicMethods = {};
var privateMethods = {};
publicMethods["encode"] = function (payload) {
//noinspection JSUnresolvedFunction
return String(Base64.encodeBase64(String(payload).getBytes()));
};
publicMethods["decode"] = function (payload) {
//noinspection JSUnresolvedFunction
return String(Base64.decodeBase64(String(payload).getBytes()));
};
publicMethods["getDynamicClientAppCredentials"] = function () {
// setting up dynamic client application properties
var dcAppProperties = {
"applicationType": deviceMgtProps["oauthProvider"]["appRegistration"]["appType"],
"clientName": deviceMgtProps["oauthProvider"]["appRegistration"]["clientName"],
"owner": deviceMgtProps["oauthProvider"]["appRegistration"]["owner"],
"tokenScope": deviceMgtProps["oauthProvider"]["appRegistration"]["tokenScope"],
"grantType": deviceMgtProps["oauthProvider"]["appRegistration"]["grantType"],
"callbackUrl": deviceMgtProps["oauthProvider"]["appRegistration"]["callbackUrl"],
"saasApp" : true
};
// calling dynamic client app registration service endpoint
var requestURL = deviceMgtProps["oauthProvider"]["appRegistration"]
["dynamicClientAppRegistrationServiceURL"];
var requestPayload = dcAppProperties;
var xhr = new XMLHttpRequest();
xhr.open("POST", requestURL, false);
xhr.setRequestHeader("Content-Type", "application/json");
xhr.send(stringify(requestPayload));
var dynamicClientAppCredentials = {};
if (xhr["status"] == 201 && xhr["responseText"]) {
var responsePayload = parse(xhr["responseText"]);
dynamicClientAppCredentials["clientId"] = responsePayload["client_id"];
dynamicClientAppCredentials["clientSecret"] = responsePayload["client_secret"];
} else if (xhr["status"] == 400) {
log.error("{/app/modules/oauth/token-handler-utils.js - getDynamicClientAppCredentials()} " +
"Bad request. Invalid data provided as dynamic client application properties.");
dynamicClientAppCredentials = null;
} else {
log.error("{/app/modules/oauth/token-handler-utils.js - getDynamicClientAppCredentials()} " +
"Error in retrieving dynamic client credentials.");
dynamicClientAppCredentials = null;
}
// returning dynamic client credentials
return dynamicClientAppCredentials;
};
publicMethods["getTenantBasedClientAppCredentials"] = function (username) {
if (!username) {
log.error("{/app/modules/oauth/token-handler-utils.js} Error in retrieving tenant " +
"based client app credentials. No username " +
"as input - getTenantBasedClientAppCredentials(x)");
return null;
} else {
//noinspection JSUnresolvedFunction, JSUnresolvedVariable
var tenantDomain = carbon.server.tenantDomain({username: username});
if (!tenantDomain) {
log.error("{/app/modules/oauth/token-handler-utils.js} Error in retrieving tenant " +
"based client application credentials. Unable to obtain a valid tenant domain for provided " +
"username - getTenantBasedClientAppCredentials(x, y)");
return null;
} else {
var cachedTenantBasedClientAppCredentials = privateMethods.
getCachedTenantBasedClientAppCredentials(tenantDomain);
if (cachedTenantBasedClientAppCredentials) {
return cachedTenantBasedClientAppCredentials;
} else {
var adminUsername = deviceMgtProps["adminUser"];
var adminUserTenantId = deviceMgtProps["adminUserTenantId"];
//claims required for jwtAuthenticator.
var claims = {"http://wso2.org/claims/enduserTenantId": adminUserTenantId,
"http://wso2.org/claims/enduser": adminUsername};
var jwtToken = publicMethods.getJwtToken(adminUsername, claims);
// register a tenant based client app at API Manager
var applicationName = deviceMgtProps["oauthProvider"]["appRegistration"]
["clientName"] + "_" + tenantDomain;
var requestURL = deviceMgtProps["oauthProvider"]["appRegistration"]
["apiManagerClientAppRegistrationServiceURL"] +
"?tenantDomain=" + tenantDomain + "&applicationName=" + applicationName;
var xhr = new XMLHttpRequest();
xhr.open("POST", requestURL, false);
xhr.setRequestHeader("Content-Type", "application/json");
xhr.setRequestHeader("X-JWT-Assertion", "" + jwtToken);
xhr.send();
if (xhr["status"] == 201 && xhr["responseText"]) {
var responsePayload = parse(xhr["responseText"]);
var tenantBasedClientAppCredentials = {};
tenantBasedClientAppCredentials["clientId"] = responsePayload["client_id"];
tenantBasedClientAppCredentials["clientSecret"] = responsePayload["client_secret"];
privateMethods.
setCachedTenantBasedClientAppCredentials(tenantDomain, tenantBasedClientAppCredentials);
return tenantBasedClientAppCredentials;
} else {
log.error("{/app/modules/oauth/token-handler-utils.js} Error in retrieving tenant " +
"based client application credentials from API " +
"Manager - getTenantBasedClientAppCredentials(x, y)");
return null;
}
}
}
}
};
publicMethods["getTenantBasedWebSocketClientAppCredentials"] = function (username) {
if (!username) {
log.error("{/app/modules/oauth/token-handler-utils.js} Error in retrieving tenant " +
"based client app credentials. No username " +
"as input - getTenantBasedWebSocketClientAppCredentials(x)");
return null;
} else {
//noinspection JSUnresolvedFunction, JSUnresolvedVariable
var tenantDomain = carbon.server.tenantDomain({username: username});
if (!tenantDomain) {
log.error("{/app/modules/oauth/token-handler-utils.js} Error in retrieving tenant " +
"based client application credentials. Unable to obtain a valid tenant domain for provided " +
"username - getTenantBasedWebSocketClientAppCredentials(x, y)");
return null;
} else {
var cachedBasedWebsocketClientAppCredentials = privateMethods.
getCachedBasedWebSocketClientAppCredentials(tenantDomain);
if (cachedBasedWebsocketClientAppCredentials) {
return cachedBasedWebsocketClientAppCredentials;
} else {
var adminUsername = deviceMgtProps["adminUser"];
var adminUserTenantId = deviceMgtProps["adminUserTenantId"];
//claims required for jwtAuthenticator.
var claims = {"http://wso2.org/claims/enduserTenantId": adminUserTenantId,
"http://wso2.org/claims/enduser": adminUsername};
var jwtToken = publicMethods.getJwtToken(adminUsername, claims);
// register a tenant based app at API Manager
var applicationName = "websocket_webapp_" + tenantDomain;
var requestURL = (deviceMgtProps["oauthProvider"]["appRegistration"]
["apiManagerClientAppRegistrationServiceURL"]).replace("/tenants","");
var xhr = new XMLHttpRequest();
xhr.open("POST", requestURL, false);
xhr.setRequestHeader("Content-Type", "application/json");
xhr.setRequestHeader("X-JWT-Assertion", "" + jwtToken);
xhr.send(stringify({applicationName:applicationName, tags:["device_management"],
isAllowedToAllDomains:false, isMappingAnExistingOAuthApp:false, validityPeriod: 3600}));
if (xhr["status"] == 201 && xhr["responseText"]) {
var responsePayload = parse(xhr["responseText"]);
var tenantTenantBasedWebsocketClientAppCredentials = {};
tenantTenantBasedWebsocketClientAppCredentials["clientId"] = responsePayload["client_id"];
tenantTenantBasedWebsocketClientAppCredentials["clientSecret"] =
responsePayload["client_secret"];
privateMethods.setCachedBasedWebSocketClientAppCredentials(tenantDomain,
tenantTenantBasedWebsocketClientAppCredentials);
return tenantTenantBasedWebsocketClientAppCredentials;
} else {
log.error("{/app/modules/oauth/token-handler-utils.js} Error in retrieving tenant " +
"based client application credentials from API " +
"Manager - getTenantBasedWebSocketClientAppCredentials(x, y)");
return null;
}
}
}
}
};
privateMethods["setCachedTenantBasedClientAppCredentials"] = function (tenantDomain, clientAppCredentials) {
var cachedTenantBasedClientAppCredentialsMap = application.get(constants["CACHED_CREDENTIALS"]);
if (!cachedTenantBasedClientAppCredentialsMap) {
cachedTenantBasedClientAppCredentialsMap = {};
cachedTenantBasedClientAppCredentialsMap[tenantDomain] = clientAppCredentials;
application.put(constants["CACHED_CREDENTIALS"], cachedTenantBasedClientAppCredentialsMap);
} else if (!cachedTenantBasedClientAppCredentialsMap[tenantDomain]) {
cachedTenantBasedClientAppCredentialsMap[tenantDomain] = clientAppCredentials;
}
};
privateMethods["getCachedTenantBasedClientAppCredentials"] = function (tenantDomain) {
var cachedTenantBasedClientAppCredentialsMap = application.get(constants["CACHED_CREDENTIALS"]);
if (!cachedTenantBasedClientAppCredentialsMap ||
!cachedTenantBasedClientAppCredentialsMap[tenantDomain]) {
return null;
} else {
return cachedTenantBasedClientAppCredentialsMap[tenantDomain];
}
};
privateMethods["getCachedBasedWebSocketClientAppCredentials"] = function (tenantDomain) {
var cachedBasedWebSocketClientAppCredentialsMap
= application.get(constants["CACHED_CREDENTIALS_FOR_WEBSOCKET_APP"]);
if (!cachedBasedWebSocketClientAppCredentialsMap ||
!cachedBasedWebSocketClientAppCredentialsMap[tenantDomain]) {
return null;
} else {
return cachedBasedWebSocketClientAppCredentialsMap[tenantDomain];
}
};
privateMethods["setCachedBasedWebSocketClientAppCredentials"] = function (tenantDomain, clientAppCredentials) {
var cachedBasedWebSocketClientAppCredentialsMap
= application.get(constants["CACHED_CREDENTIALS_FOR_WEBSOCKET_APP"]);
if (!cachedBasedWebSocketClientAppCredentialsMap) {
cachedBasedWebSocketClientAppCredentialsMap = {};
cachedBasedWebSocketClientAppCredentialsMap[tenantDomain] = clientAppCredentials;
application.put(constants["CACHED_CREDENTIALS_FOR_WEBSOCKET_APP"]
, cachedBasedWebSocketClientAppCredentialsMap);
} else if (!cachedBasedWebSocketClientAppCredentialsMap[tenantDomain]) {
cachedBasedWebSocketClientAppCredentialsMap[tenantDomain] = clientAppCredentials;
}
};
publicMethods["getTokenPairAndScopesByPasswordGrantType"] = function (username, password
, encodedClientAppCredentials, scopes) {
if (!username || !password || !encodedClientAppCredentials || !scopes) {
log.error("{/app/modules/oauth/token-handler-utils.js} Error in retrieving access token by password " +
"grant type. No username, password, encoded client app credentials or scopes are " +
"found - getTokenPairAndScopesByPasswordGrantType(a, b, c, d)");
return null;
} else {
// calling oauth provider token service endpoint
var requestURL = deviceMgtProps["oauthProvider"]["tokenServiceURL"];
var requestPayload = "grant_type=password&username=" +
username + "&password=" + password + "&scope=" + scopes;
var xhr = new XMLHttpRequest();
xhr.open("POST", requestURL, false);
xhr.setRequestHeader("Content-Type", "application/x-www-form-urlencoded");
xhr.setRequestHeader("Authorization", "Basic " + encodedClientAppCredentials);
xhr.send(requestPayload);
if (xhr["status"] == 200 && xhr["responseText"]) {
var responsePayload = parse(xhr["responseText"]);
var tokenData = {};
tokenData["accessToken"] = responsePayload["access_token"];
tokenData["refreshToken"] = responsePayload["refresh_token"];
tokenData["scopes"] = responsePayload["scope"];
return tokenData;
} else {
log.error("{/app/modules/oauth/token-handler-utils.js} Error in retrieving access token " +
"by password grant type - getTokenPairAndScopesByPasswordGrantType(a, b, c, d)");
return null;
}
}
};
publicMethods["getTokenPairAndScopesByJWTGrantType"] = function (assertion, encodedClientAppCredentials, scopes) {
if (!assertion || !encodedClientAppCredentials || !scopes) {
log.error("{/app/modules/oauth/token-handler-utils.js} Error in retrieving access token by jwt " +
"grant type. No assertion, encoded client app credentials or scopes are " +
"found - getTokenPairAndScopesByJWTGrantType(x, y, z)");
return null;
} else {
var ssoLoginUser = authModule.ssoLogin(assertion);
if (!ssoLoginUser.user.username) {
return null;
}
var endUsername = ssoLoginUser.user.username + "@" + ssoLoginUser.user.domain;
var JWTClientManagerServicePackagePath =
"io.entgra.device.mgt.core.identity.jwt.client.extension.service.JWTClientManagerService";
//noinspection JSUnresolvedFunction, JSUnresolvedVariable
var JWTClientManagerService = carbon.server.osgiService(JWTClientManagerServicePackagePath);
//noinspection JSUnresolvedFunction
var jwtClient = JWTClientManagerService.getJWTClient();
// returning access token by JWT grant type
var tokenInfo = jwtClient.getAccessToken(encodedClientAppCredentials,
endUsername, scopes);
if (tokenInfo) {
var tokenData = {};
tokenData["accessToken"] = tokenInfo.getAccessToken();
tokenData["refreshToken"] = tokenInfo.getRefreshToken();
tokenData["scopes"] = tokenInfo.getScopes();
return tokenData;
} else {
log.error("{/app/modules/oauth/token-handler-utils.js} Error in retrieving access token " +
"by jwt grant type - getTokenPairAndScopesByJWTGrantType()");
return null;
}
}
};
publicMethods["getNewTokenPairByRefreshToken"] = function (refreshToken, encodedClientAppCredentials, scopes) {
if (!refreshToken || !encodedClientAppCredentials) {
log.error("{/app/modules/oauth/token-handler-utils.js} Error in retrieving new access token " +
"by current refresh token. No refresh token or encoded client app credentials are " +
"found - getNewTokenPairByRefreshToken(x, y, z)");
return null;
} else {
var requestURL = deviceMgtProps["oauthProvider"]["tokenServiceURL"];
var requestPayload = "grant_type=refresh_token&refresh_token=" + refreshToken;
if (scopes) {
requestPayload = requestPayload + "&scope=" + scopes;
}
var xhr = new XMLHttpRequest();
xhr.open("POST", requestURL, false);
xhr.setRequestHeader("Content-Type", "application/x-www-form-urlencoded");
xhr.setRequestHeader("Authorization", "Basic " + encodedClientAppCredentials);
xhr.send(requestPayload);
if (xhr["status"] == 200 && xhr["responseText"]) {
var responsePayload = parse(xhr["responseText"]);
var tokenPair = {};
tokenPair["accessToken"] = responsePayload["access_token"];
tokenPair["refreshToken"] = responsePayload["refresh_token"];
return tokenPair;
} else {
log.error("{/app/modules/oauth/token-handler-utils.js} Error in retrieving new access token by " +
"current refresh token - getNewTokenPairByRefreshToken(x, y, z)");
return null;
}
}
};
publicMethods["getAccessTokenByJWTGrantType"] = function (clientAppCredentials) {
if (!clientAppCredentials) {
log.error("{/app/modules/oauth/token-handler-utils.js} Error in retrieving new access token " +
"by current refresh token. No client app credentials are found " +
"as input - getAccessTokenByJWTGrantType(x)");
return null;
} else {
var JWTClientManagerServicePackagePath =
"io.entgra.device.mgt.core.identity.jwt.client.extension.service.JWTClientManagerService";
//noinspection JSUnresolvedFunction, JSUnresolvedVariable
var JWTClientManagerService = carbon.server.osgiService(JWTClientManagerServicePackagePath);
//noinspection JSUnresolvedFunction
var jwtClient = JWTClientManagerService.getJWTClient();
// returning access token by JWT grant type
return jwtClient.getAccessToken(clientAppCredentials["clientId"], clientAppCredentials["clientSecret"],
deviceMgtProps["oauthProvider"]["appRegistration"]["owner"], null)["accessToken"];
}
};
publicMethods["getJwtToken"] = function (username, claims) {
if (!username) {
log.error("{/app/modules/oauth/token-handler-utils.js} Error in retrieving new jwt token");
return null;
} else {
var JWTClientManagerServicePackagePath =
"io.entgra.device.mgt.core.identity.jwt.client.extension.service.JWTClientManagerService";
//noinspection JSUnresolvedFunction, JSUnresolvedVariable
var JWTClientManagerService = carbon.server.osgiService(JWTClientManagerServicePackagePath);
//noinspection JSUnresolvedFunction
var jwtClient = JWTClientManagerService.getJWTClient();
// returning access token by JWT grant type
if (claims) {
return jwtClient.getJwtToken(username, claims);
} else {
return jwtClient.getJwtToken(username);
}
}
};
publicMethods["removeClientAppCredentials"] = function (tenantDomain) {
var cachedTenantBasedClientAppCredentialsMap = application.get(constants["CACHED_CREDENTIALS"]);
if (cachedTenantBasedClientAppCredentialsMap) {
if (cachedTenantBasedClientAppCredentialsMap[tenantDomain]) {
delete cachedTenantBasedClientAppCredentialsMap[tenantDomain];
}
}
};
publicMethods["getUniqueBrowserScope"] = function () {
var deviceScope = "device_" + utility.md5(request.getHeader("User-Agent") + "::" + request.getRemoteAddr());
deviceScope = deviceScope + " ";
return deviceScope;
};
return publicMethods;
}();

View File

@ -1,282 +0,0 @@
/*
* Copyright (c) 2018 - 2023, Entgra (Pvt) Ltd. (http://www.entgra.io) All Rights Reserved.
*
* Entgra (Pvt) Ltd. licenses this file to you under the Apache License,
* Version 2.0 (the "License"); you may not use this file except
* in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
/**
* -----------------------------------------------------
* Following module includes handlers
* at Jaggery Layer for handling OAuth tokens.
* -----------------------------------------------------
*/
var handlers = function () {
var log = new Log("/app/modules/oauth/token-handlers.js");
var tokenUtil = require("/app/modules/oauth/token-handler-utils.js")["utils"];
var constants = require("/app/modules/constants.js");
var devicemgtProps = require("/app/modules/conf-reader/main.js")["conf"];
var utility = require("/app/modules/utility.js")["utility"];
var publicMethods = {};
var privateMethods = {};
publicMethods["setupTokenPairByPasswordGrantType"] = function (username, password) {
if (!username || !password) {
throw new Error("{/app/modules/oauth/token-handlers.js} Could not set up access token pair by " +
"password grant type. Either username of logged in user, password or both are missing " +
"as input - setupTokenPairByPasswordGrantType(x, y)");
} else {
privateMethods.setUpEncodedTenantBasedClientAppCredentials(username);
privateMethods.setUpEncodedTenantBasedWebSocketClientAppCredentials(username);
var encodedClientAppCredentials = session.get(constants["ENCODED_TENANT_BASED_CLIENT_APP_CREDENTIALS"]);
if (!encodedClientAppCredentials) {
throw new Error("{/app/modules/oauth/token-handlers.js} Could not set up access token pair by " +
"password grant type. Encoded client credentials are " +
"missing - setupTokenPairByPasswordGrantType(x, y)");
} else {
var tokenData;
// tokenPair will include current access token as well as current refresh token
var arrayOfScopes = devicemgtProps["scopes"];
arrayOfScopes = arrayOfScopes.concat(utility.getDeviceTypesScopesList());
var stringOfScopes = tokenUtil.getUniqueBrowserScope();
arrayOfScopes.forEach(function (entry) {
stringOfScopes += entry + " ";
});
tokenData = tokenUtil.
getTokenPairAndScopesByPasswordGrantType(username,
encodeURIComponent(password), encodedClientAppCredentials, stringOfScopes);
if (!tokenData) {
throw new Error("{/app/modules/oauth/token-handlers.js} Could not set up " +
"token pair by password grant type. Error in token " +
"retrieval - setupTokenPairByPasswordGrantType(x, y)");
} else {
var tokenPair = {};
tokenPair["accessToken"] = tokenData["accessToken"];
tokenPair["refreshToken"] = tokenData["refreshToken"];
// setting up token pair into session context as a string
session.put(constants["TOKEN_PAIR"], stringify(tokenPair));
var scopes = tokenData.scopes.split(" ");
// adding allowed scopes to the session
session.put(constants["ALLOWED_SCOPES"], scopes);
}
}
}
};
publicMethods["setupTokenPairBySamlGrantType"] = function (username, samlToken) {
if (!username || !samlToken) {
throw new Error("{/app/modules/oauth/token-handlers.js} Could not set up access token pair by " +
"saml grant type. Either username of logged in user, samlToken or both are missing " +
"as input - setupTokenPairBySamlGrantType(x, y)");
} else {
privateMethods.setUpEncodedTenantBasedClientAppCredentials(username);
privateMethods.setUpEncodedTenantBasedWebSocketClientAppCredentials(username);
var encodedClientAppCredentials = session.get(constants["ENCODED_TENANT_BASED_CLIENT_APP_CREDENTIALS"]);
if (!encodedClientAppCredentials) {
throw new Error("{/app/modules/oauth/token-handlers.js} Could not set up access token pair " +
"by saml grant type. Encoded client credentials are " +
"missing - setupTokenPairBySamlGrantType(x, y)");
} else {
var tokenData;
var arrayOfScopes = devicemgtProps["scopes"];
arrayOfScopes = arrayOfScopes.concat(utility.getDeviceTypesScopesList());
var stringOfScopes = tokenUtil.getUniqueBrowserScope();
arrayOfScopes.forEach(function (entry) {
stringOfScopes += entry + " ";
});
// accessTokenPair will include current access token as well as current refresh token
tokenData = tokenUtil.
getTokenPairAndScopesBySAMLGrantType(samlToken, encodedClientAppCredentials, stringOfScopes);
if (!tokenData) {
throw new Error("{/app/modules/oauth/token-handlers.js} Could not set up token " +
"pair by password grant type. Error in token " +
"retrieval - setupTokenPairBySamlGrantType(x, y)");
} else {
var tokenPair = {};
tokenPair["accessToken"] = tokenData["accessToken"];
tokenPair["refreshToken"] = tokenData["refreshToken"];
// setting up access token pair into session context as a string
session.put(constants["TOKEN_PAIR"], stringify(tokenPair));
var scopes = tokenData.scopes.split(" ");
// adding allowed scopes to the session
session.put(constants["ALLOWED_SCOPES"], scopes);
}
}
}
};
publicMethods["setupTokenPairByJWTGrantType"] = function (username, samlToken) {
//samlToken is used to validate then if the user is a valid user then token is issued with JWT Grant Type.
if (!username || !samlToken) {
throw new Error("{/app/modules/oauth/token-handlers.js} Could not set up access token pair by " +
"saml grant type. Either username of logged in user, samlToken or both are missing " +
"as input - setupTokenPairBySamlGrantType(x, y)");
} else {
privateMethods.setUpEncodedTenantBasedClientAppCredentials(username);
privateMethods.setUpEncodedTenantBasedWebSocketClientAppCredentials(username);
var encodedClientAppCredentials = session.get(constants["ENCODED_TENANT_BASED_CLIENT_APP_CREDENTIALS"]);
if (!encodedClientAppCredentials) {
throw new Error("{/app/modules/oauth/token-handlers.js} Could not set up access token pair " +
"by saml grant type. Encoded client credentials are " +
"missing - setupTokenPairBySamlGrantType(x, y)");
} else {
var tokenData;
var arrayOfScopes = devicemgtProps["scopes"];
arrayOfScopes = arrayOfScopes.concat(utility.getDeviceTypesScopesList());
var stringOfScopes = tokenUtil.getUniqueBrowserScope();
arrayOfScopes.forEach(function (entry) {
stringOfScopes += entry + " ";
});
// accessTokenPair will include current access token as well as current refresh token
tokenData = tokenUtil.
getTokenPairAndScopesByJWTGrantType(samlToken, encodedClientAppCredentials, stringOfScopes);
if (!tokenData) {
throw new Error("{/app/modules/oauth/token-handlers.js} Could not set up token. Error in token " +
"retrieval - setupTokenPairBySamlGrantType(x, y)");
} else {
var tokenPair = {};
tokenPair["accessToken"] = tokenData["accessToken"];
tokenPair["refreshToken"] = tokenData["refreshToken"];
// setting up access token pair into session context as a string
session.put(constants["TOKEN_PAIR"], stringify(tokenPair));
var scopes = tokenData.scopes.split(" ");
// adding allowed scopes to the session
session.put(constants["ALLOWED_SCOPES"], scopes);
}
}
}
};
publicMethods["refreshTokenPair"] = function () {
var currentTokenPair = parse(session.get(constants["TOKEN_PAIR"]));
// currentTokenPair includes current access token as well as current refresh token
var encodedClientAppCredentials = session.get(constants["ENCODED_TENANT_BASED_CLIENT_APP_CREDENTIALS"]);
if (!currentTokenPair || !encodedClientAppCredentials) {
throw new Error("{/app/modules/oauth/token-handlers.js} Error in refreshing tokens. Either the " +
"token pair, encoded client app credentials or both input are not found under " +
"session context - refreshTokenPair()");
} else {
var newTokenPair = tokenUtil.
getNewTokenPairByRefreshToken(currentTokenPair["refreshToken"], encodedClientAppCredentials);
if (!newTokenPair) {
log.error("{/app/modules/oauth/token-handlers.js} Error in refreshing token pair. " +
"Unable to update session context with new access token pair - refreshTokenPair()");
userModule.logout(function () {
response.sendRedirect(devicemgtProps["appContext"] + "login");
});
} else {
session.put(constants["TOKEN_PAIR"], stringify(newTokenPair));
}
}
};
privateMethods["setUpEncodedTenantBasedClientAppCredentials"] = function (username) {
if (!username) {
throw new Error("{/app/modules/oauth/token-handlers.js} Could not set up encoded tenant based " +
"client credentials to session context. No username of logged in user is found as " +
"input - setUpEncodedTenantBasedClientAppCredentials(x)");
} else {
if (devicemgtProps["gatewayEnabled"]) {
var tenantBasedClientAppCredentials = tokenUtil.getTenantBasedClientAppCredentials(username);
if (!tenantBasedClientAppCredentials) {
throw new Error("{/app/modules/oauth/token-handlers.js} Could not set up encoded tenant " +
"based client credentials to session context as the server is unable " +
"to obtain such credentials - setUpEncodedTenantBasedClientAppCredentials(x)");
} else {
var encodedTenantBasedClientAppCredentials =
tokenUtil.encode(tenantBasedClientAppCredentials["clientId"] + ":" +
tenantBasedClientAppCredentials["clientSecret"]);
// setting up encoded tenant based client credentials to session context.
session.put(constants["ENCODED_TENANT_BASED_CLIENT_APP_CREDENTIALS"],
encodedTenantBasedClientAppCredentials);
}
} else {
var dynamicClientAppCredentials = tokenUtil.getDynamicClientAppCredentials();
if (!dynamicClientAppCredentials) {
throw new Error("{/app/modules/oauth/token-handlers.js} Could not set up encoded tenant based " +
"client credentials to session context as the server is unable to obtain " +
"dynamic client credentials - setUpEncodedTenantBasedClientAppCredentials(x)");
}
var encodedTenantBasedClientAppCredentials =
tokenUtil.encode(dynamicClientAppCredentials["clientId"] + ":" +
dynamicClientAppCredentials["clientSecret"]);
// setting up encoded tenant based client credentials to session context.
session.put(constants["ENCODED_TENANT_BASED_CLIENT_APP_CREDENTIALS"],
encodedTenantBasedClientAppCredentials);
}
}
};
privateMethods["setUpEncodedTenantBasedWebSocketClientAppCredentials"] = function (username) {
if (!username) {
throw new Error("{/app/modules/oauth/token-handlers.js} Could not set up encoded tenant based " +
"client credentials to session context. No username of logged in user is found as " +
"input - setUpEncodedTenantBasedWebSocketClientAppCredentials(x)");
} else {
if (devicemgtProps["gatewayEnabled"]) {
var tenantBasedWebSocketClientAppCredentials
= tokenUtil.getTenantBasedWebSocketClientAppCredentials(username);
if (!tenantBasedWebSocketClientAppCredentials) {
throw new Error("{/app/modules/oauth/token-handlers.js} Could not set up encoded tenant " +
"based client credentials to session context as the server is unable " +
"to obtain such credentials - setUpEncodedTenantBasedWebSocketClientAppCredentials(x)");
} else {
var encodedTenantBasedWebSocketClientAppCredentials =
tokenUtil.encode(tenantBasedWebSocketClientAppCredentials["clientId"] + ":" +
tenantBasedWebSocketClientAppCredentials["clientSecret"]);
// setting up encoded tenant based client credentials to session context.
session.put(constants["ENCODED_TENANT_BASED_WEB_SOCKET_CLIENT_CREDENTIALS"],
encodedTenantBasedWebSocketClientAppCredentials);
}
} else {
var dynamicClientAppCredentials = tokenUtil.getDynamicClientAppCredentials();
if (!dynamicClientAppCredentials) {
throw new Error("{/app/modules/oauth/token-handlers.js} Could not set up encoded tenant based " +
"client credentials to session context as the server is unable to obtain " +
"dynamic client credentials - setUpEncodedTenantBasedWebSocketClientAppCredentials(x)");
}
var encodedTenantBasedWebSocketClientAppCredentials =
tokenUtil.encode(dynamicClientAppCredentials["clientId"] + ":" +
dynamicClientAppCredentials["clientSecret"]);
// setting up encoded tenant based client credentials to session context.
session.put(constants["ENCODED_TENANT_BASED_WEB_SOCKET_CLIENT_CREDENTIALS"],
encodedTenantBasedWebSocketClientAppCredentials);
}
}
};
publicMethods["removeClientDetails"] = function () {
var user = session.get(constants.USER_SESSION_KEY);
if (!user) {
log.error("User object was not found in the session");
throw constants.ERRORS.USER_NOT_FOUND;
}
tokenUtil.removeClientAppCredentials(user.domain);
session.remove(constants["ENCODED_TENANT_BASED_WEB_SOCKET_CLIENT_CREDENTIALS"]);
session.remove(constants["ENCODED_TENANT_BASED_CLIENT_APP_CREDENTIALS"]);
session.remove(constants["TOKEN_PAIR"]);
session.remove(constants["ALLOWED_SCOPES"]);
};
return publicMethods;
}();

View File

@ -1,503 +0,0 @@
/*
* Copyright (c) 2018 - 2023, Entgra (Pvt) Ltd. (http://www.entgra.io) All Rights Reserved.
*
* Entgra (Pvt) Ltd. licenses this file to you under the Apache License,
* Version 2.0 (the "License"); you may not use this file except
* in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
/**
* ----------------------------------------------------------------------------
* Following module includes invokers
* at Jaggery Layer for calling Backend Services, protected by OAuth Tokens.
* These Services include both REST and SOAP Services.
* ----------------------------------------------------------------------------
*/
var invokers = function () {
var log = new Log("/app/modules/oauth/token-protected-service-invokers.js");
var publicXMLHTTPInvokers = {};
var publicHTTPClientInvokers = {};
var privateMethods = {};
var publicWSInvokers = {};
var TOKEN_EXPIRED = "Access token expired";
var TOKEN_INVALID = "Invalid input. Access token validation failed";
var devicemgtProps = require("/app/modules/conf-reader/main.js")["conf"];
var constants = require("/app/modules/constants.js");
var userModule = require("/app/modules/business-controllers/user.js")["userModule"];
var tokenUtil = require("/app/modules/oauth/token-handlers.js")["handlers"];
var tokenHandler = require("/app/modules/oauth/token-handler-utils.js")["utils"];
/**
* This method reads the token pair from the session and return the access token.
* If the token pair is not set in the session, this will return null.
*/
privateMethods.getAccessToken = function () {
if (session) {
var tokenPair = session.get(constants["TOKEN_PAIR"]);
if (tokenPair) {
return parse(tokenPair)["accessToken"];
}
}
return null;
};
/**
* ---------------------------------------------------------------------------
* Start of XML-HTTP-REQUEST based Interceptor implementations
* ---------------------------------------------------------------------------
*/
/**
* 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 headers a list of name value pairs for additional http headers
*/
privateMethods["execute"] = function (httpMethod, requestPayload, endpoint, responseCallback, count, headers) {
var xmlHttpRequest = new XMLHttpRequest();
xmlHttpRequest.open(httpMethod, endpoint);
var contentTypeFound = false;
var acceptTypeFound = false;
for (var i in headers) {
xmlHttpRequest.setRequestHeader(headers[i].name, headers[i].value);
if(constants["CONTENT_TYPE_IDENTIFIER"] == headers[i].name){
contentTypeFound = true;
}
if(constants["ACCEPT_IDENTIFIER"] == headers[i].name){
acceptTypeFound = true;
}
}
if (!contentTypeFound) {
xmlHttpRequest.setRequestHeader(constants["CONTENT_TYPE_IDENTIFIER"], constants["APPLICATION_JSON"]);
}
if (!acceptTypeFound) {
xmlHttpRequest.setRequestHeader(constants["ACCEPT_IDENTIFIER"], constants["APPLICATION_JSON"]);
}
if (devicemgtProps["isOAuthEnabled"]) {
var accessToken = privateMethods.getAccessToken();
if (accessToken == null) {
userModule.logout(function () {
response.sendRedirect(devicemgtProps["appContext"] + "login");
});
} else {
xmlHttpRequest.setRequestHeader(constants["AUTHORIZATION_HEADER"],
constants["BEARER_PREFIX"] + accessToken);
}
}
if (requestPayload) {
xmlHttpRequest.send(requestPayload);
} else {
xmlHttpRequest.send();
}
log.debug("Request : " + httpMethod + " " + endpoint);
log.debug("Request payload if any : " + stringify(requestPayload));
log.debug("Response status : " + xmlHttpRequest.status);
log.debug("Response payload if any : " + xmlHttpRequest.responseText);
if (devicemgtProps["isCloud"]) {
log.info("Request : " + httpMethod + " " + endpoint);
log.info("Request payload if any : " + stringify(requestPayload));
log.info("Response status : " + xmlHttpRequest.status);
}
if (xmlHttpRequest.status == 401) {
if ((xmlHttpRequest.responseText == TOKEN_EXPIRED ||
xmlHttpRequest.responseText == TOKEN_INVALID ) && count < 5) {
tokenUtil.refreshTokenPair();
return privateMethods.execute(httpMethod, requestPayload, endpoint, responseCallback, ++count, headers);
} else if (privateMethods.isInvalidClientCredential(xmlHttpRequest.responseText)) {
log.error("API application has been removed.");
tokenUtil.removeClientDetails();
session.invalidate();
response.sendRedirect(devicemgtProps["appContext"] + "login");
} else if (privateMethods.isInvalidCredential(xmlHttpRequest.responseText)) {
tokenUtil.refreshTokenPair();
return privateMethods.execute(httpMethod, requestPayload, endpoint, responseCallback, ++count, headers);
}
} else {
return responseCallback(xmlHttpRequest);
}
};
/**
* This method verify whether the access token is expired using response payload.
* This is required when using API gateway.
* @param responsePayload response payload.
* return true if it is invalid otherwise false.
*/
privateMethods["isInvalidCredential"] =
function (responsePayload) {
if (responsePayload) {
try {
payload = parse(responsePayload);
if (payload["fault"]["code"] == 900901) {
log.debug("Access token is invalid: " + payload["fault"]["code"]);
log.debug(payload["fault"]["description"]);
return true;
}
} catch (err) {
// do nothing
}
}
return false;
};
/**
* This method verify whether the client credential is removed/blocked using response payload.
* This is required when using API gateway.
* @param responsePayload response payload.
* return true if it is invalid otherwise false.
*/
privateMethods["isInvalidClientCredential"] =
function (responsePayload) {
if (responsePayload) {
try {
payload = parse(responsePayload);
if (payload["fault"]["message"] == "Invalid Credentials") {
return true;
}
} catch (err) {
// do nothing
}
}
return false;
};
/**
* 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.
*/
privateMethods["initiateXMLHTTPRequest"] =
function (httpMethod, requestPayload, endpoint, responseCallback, headers) {
return privateMethods.execute(httpMethod, requestPayload, endpoint, responseCallback, 0, headers);
};
/**
* 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, headers) {
var requestPayload = null;
return privateMethods.initiateXMLHTTPRequest(constants["HTTP_GET"], requestPayload, endpoint, responseCallback,
headers);
};
/**
* 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, headers) {
return privateMethods.initiateXMLHTTPRequest(constants["HTTP_POST"], requestPayload, endpoint, responseCallback,
headers);
};
/**
* 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, headers) {
return privateMethods.initiateXMLHTTPRequest(constants["HTTP_PUT"], requestPayload, endpoint, responseCallback,
headers);
};
/**
* 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, headers) {
var requestPayload = null;
return privateMethods.initiateXMLHTTPRequest(constants["HTTP_DELETE"], requestPayload, endpoint,
responseCallback, headers);
};
/**
* ---------------------------------------------------------------------------
* 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 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");
//noinspection JSUnresolvedFunction
var wsRequest = new ws.WSRequest();
var options = [];
if (devicemgtProps["isOAuthEnabled"]) {
var adminUsername = devicemgtProps["adminUser"];
var accessToken = tokenHandler.getJwtToken(adminUsername);
var decoded = tokenHandler.encode(accessToken);
if (accessToken) {
var authenticationHeaderName = String(constants["AUTHORIZATION_HEADER"]);
var authenticationHeaderValue = String(constants["BEARER_PREFIX"] + decoded);
var headers = [];
var oAuthAuthenticationData = {};
oAuthAuthenticationData.name = authenticationHeaderName;
oAuthAuthenticationData.value = authenticationHeaderValue;
headers.push(oAuthAuthenticationData);
options.HTTPHeaders = headers;
} else {
response.sendRedirect(devicemgtProps["appContext"] + "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, requestPayload, endpoint,
successCallback, errorCallback, soapVersion) {
return privateMethods.initiateWSRequest(action, endpoint, successCallback,
errorCallback, soapVersion, requestPayload);
};
/**
* ---------------------------------------------------------------------------
* Start of HTTP-CLIENT-REQUEST based Interceptor implementations
* ---------------------------------------------------------------------------
*/
/**
* 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 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.
* @param headers a list of name value pairs for additional http headers.
*/
privateMethods["initiateHTTPClientRequest"] =
function (method, url, successCallback, errorCallback, payload, headers) {
//noinspection JSUnresolvedVariable
var HttpClient = Packages.org.apache.commons.httpclient.HttpClient;
var httpMethodObject;
switch (method) {
case constants["HTTP_GET"]:
//noinspection JSUnresolvedVariable
var GetMethod = Packages.org.apache.commons.httpclient.methods.GetMethod;
httpMethodObject = new GetMethod(url);
break;
case constants["HTTP_POST"]:
//noinspection JSUnresolvedVariable
var PostMethod = Packages.org.apache.commons.httpclient.methods.PostMethod;
httpMethodObject = new PostMethod(url);
break;
case constants["HTTP_PUT"]:
//noinspection JSUnresolvedVariable
var PutMethod = Packages.org.apache.commons.httpclient.methods.PutMethod;
httpMethodObject = new PutMethod(url);
break;
case constants["HTTP_DELETE"]:
//noinspection JSUnresolvedVariable
var DeleteMethod = Packages.org.apache.commons.httpclient.methods.DeleteMethod;
httpMethodObject = new DeleteMethod(url);
break;
default:
//noinspection JSUnresolvedFunction
throw new IllegalArgumentException("Invalid HTTP request method: " + method);
}
//noinspection JSUnresolvedVariable
var Header = Packages.org.apache.commons.httpclient.Header;
var contentTypeFound = false;
var acceptTypeFound = false;
var acceptTypeValue = constants["APPLICATION_JSON"];
for (var i in headers) {
var header = new Header();
header.setName(headers[i].name);
header.setValue(headers[i].value);
httpMethodObject.addRequestHeader(header);
if(constants["CONTENT_TYPE_IDENTIFIER"] == headers[i].name){
contentTypeFound = true;
}
if(constants["ACCEPT_IDENTIFIER"] == headers[i].name){
acceptTypeFound = true;
acceptTypeValue = headers[i].value;
}
}
var header = new Header();
if(!contentTypeFound){
header.setName(constants["CONTENT_TYPE_IDENTIFIER"]);
header.setValue(constants["APPLICATION_JSON"]);
//noinspection JSUnresolvedFunction
httpMethodObject.addRequestHeader(header);
}
if(!acceptTypeFound) {
header = new Header();
header.setName(constants["ACCEPT_IDENTIFIER"]);
header.setValue(constants["APPLICATION_JSON"]);
//noinspection JSUnresolvedFunction
httpMethodObject.addRequestHeader(header);
}
if (devicemgtProps["isOAuthEnabled"]) {
var accessToken = privateMethods.getAccessToken();
if (accessToken) {
header = new Header();
header.setName(constants["AUTHORIZATION_HEADER"]);
header.setValue(constants["BEARER_PREFIX"] + accessToken);
//noinspection JSUnresolvedFunction
httpMethodObject.addRequestHeader(header);
} else {
response.sendRedirect(devicemgtProps["appContext"] + "login");
}
}
//noinspection JSUnresolvedFunction
if (payload != null) {
var StringRequestEntity = Packages.org.apache.commons.httpclient.methods.StringRequestEntity;
var stringRequestEntity = new StringRequestEntity(stringify(payload));
//noinspection JSUnresolvedFunction
httpMethodObject.setRequestEntity(stringRequestEntity);
}
var client = new HttpClient();
try {
//noinspection JSUnresolvedFunction
client.executeMethod(httpMethodObject);
//noinspection JSUnresolvedFunction
var status = httpMethodObject.getStatusCode();
if (status >= 200 && status < 300) {
if (constants["STREAMING_FILES_ACCEPT_HEADERS"].indexOf(acceptTypeValue) > -1) {
return successCallback(httpMethodObject.getResponseBodyAsStream(),
httpMethodObject.getResponseHeaders());
} else {
return successCallback(httpMethodObject.getResponseBodyAsString(),
httpMethodObject.getResponseHeaders());
}
} else {
return errorCallback(httpMethodObject.getResponseBodyAsString(),
httpMethodObject.getResponseHeaders());
}
} catch (e) {
return errorCallback(response);
} finally {
//noinspection JSUnresolvedFunction
if (method != constants["HTTP_GET"]) {
method.releaseConnection();
}
}
};
/**
* This method invokes return initiateHTTPClientRequest 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.
* @param headers a list of name value pairs for additional http headers.
*/
publicHTTPClientInvokers["get"] = function (url, successCallback, errorCallback, headers) {
var requestPayload = null;
return privateMethods.initiateHTTPClientRequest(constants["HTTP_GET"], url, successCallback, errorCallback,
requestPayload, headers);
};
/**
* This method invokes return initiateHTTPClientRequest 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.
* @param headers a list of name value pairs for additional http headers.
*/
publicHTTPClientInvokers["post"] = function (url, payload, successCallback, errorCallback, headers) {
return privateMethods.initiateHTTPClientRequest(constants["HTTP_POST"], url, successCallback, errorCallback,
payload, headers);
};
/**
* This method invokes return initiateHTTPClientRequest 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.
* @param headers a list of name value pairs for additional http headers.
*/
publicHTTPClientInvokers["put"] = function (url, payload, successCallback, errorCallback, headers) {
return privateMethods.initiateHTTPClientRequest(constants["HTTP_PUT"], url, successCallback, errorCallback,
payload, headers);
};
/**
* This method invokes return initiateHTTPClientRequest 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.
* @param headers a list of name value pairs for additional http headers.
*/
publicHTTPClientInvokers["delete"] = function (url, successCallback, errorCallback, headers) {
var requestPayload = null;
return privateMethods.initiateHTTPClientRequest(constants["HTTP_DELETE"], url, successCallback, errorCallback,
requestPayload, headers);
};
var publicMethods = {};
publicMethods.XMLHttp = publicXMLHTTPInvokers;
publicMethods.WS = publicWSInvokers;
publicMethods.HttpClient = publicHTTPClientInvokers;
return publicMethods;
}();

View File

@ -1,396 +0,0 @@
/*
* Copyright (c) 2018 - 2023, Entgra (Pvt) Ltd. (http://www.entgra.io) All Rights Reserved.
*
* Entgra (Pvt) Ltd. licenses this file to you under the Apache License,
* Version 2.0 (the "License"); you may not use this file except
* in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
var utility;
utility = function () {
var constants = require('/app/modules/constants.js');
var devicemgtProps = require("/app/modules/conf-reader/main.js")["conf"];
var log = new Log("/app/modules/utility.js");
var JavaClass = Packages.java.lang.Class;
var PrivilegedCarbonContext = Packages.org.wso2.carbon.context.PrivilegedCarbonContext;
var server = require("carbon")["server"];
var getOsgiService = function (className) {
return PrivilegedCarbonContext.getThreadLocalCarbonContext().getOSGiService(JavaClass.forName(className));
};
var deviceTypeConfigMap = {};
var publicMethods = {};
publicMethods.startTenantFlow = function (userInfo) {
var context, carbon = require('carbon');
PrivilegedCarbonContext.startTenantFlow();
context = PrivilegedCarbonContext.getThreadLocalCarbonContext();
context.setTenantDomain(carbon.server.tenantDomain({
tenantId: userInfo.tenantId
}));
context.setTenantId(userInfo.tenantId);
context.setUsername(userInfo.username || null);
};
publicMethods.endTenantFlow = function () {
PrivilegedCarbonContext.endTenantFlow();
};
publicMethods.getDeviceManagementService = function () {
return getOsgiService('io.entgra.device.mgt.core.device.mgt.core.service.DeviceManagementProviderService');
};
publicMethods.getAPIManagementProviderService = function () {
return getOsgiService('io.entgra.device.mgt.core.apimgt.application.extension.APIManagementProviderService');
};
publicMethods.getUserManagementService = function () {
return getOsgiService("org.wso2.carbon.device.mgt.user.core.UserManager");
};
publicMethods.getPolicyManagementService = function () {
return getOsgiService("io.entgra.device.mgt.core.policy.mgt.core.PolicyManagerService");
};
publicMethods.getDeviceTypeConfig = function (deviceType) {
var unitName = publicMethods.getTenantedDeviceUnitName(deviceType, "type-view");
if (!unitName) {
return null;
}
if (deviceType in deviceTypeConfigMap) {
return deviceTypeConfigMap[deviceType];
}
var deviceTypeConfig;
var deviceTypeConfigFile = new File("/app/units/" + unitName + "/private/config.json");
if (deviceTypeConfigFile.isExists()) {
try {
deviceTypeConfigFile.open("r");
var config = deviceTypeConfigFile.readAll();
config = config.replace("%https.ip%", server.address("https"));
config = config.replace("%http.ip%", server.address("http"));
deviceTypeConfig = parse(config);
} catch (err) {
log.error("Error while reading device config file for `" + deviceType + "`: " + err);
} finally {
deviceTypeConfigFile.close();
}
}
deviceTypeConfigMap[deviceType] = deviceTypeConfig;
return deviceTypeConfig;
};
publicMethods.getOperationIcon = function (deviceType, operation) {
var unitName = publicMethods.getTenantedDeviceUnitName(deviceType, "type-view");
var iconPath = "/app/units/" + unitName + "/public/images/operations/" + operation + ".png";
var icon = new File(iconPath);
if (icon.isExists()) {
return devicemgtProps["appContext"] + "public/" + unitName + "/images/operations/" + operation + ".png";
} else {
return null;
}
};
publicMethods.getDeviceThumb = function (deviceType) {
var unitName = publicMethods.getTenantedDeviceUnitName(deviceType, "type-view");
if (!unitName) {
unitName = "cdmf.unit.default.device.type.type-view";
}
var iconPath = "/app/units/" + unitName + "/public/images/thumb.png";
var icon = new File(iconPath);
if (icon.isExists()) {
return devicemgtProps["appContext"] + "public/" + unitName + "/images/thumb.png";
} else {
return null;
}
};
publicMethods.getTenantedDeviceUnitName = function (deviceType, unitPostfix) {
var user = session.get(constants.USER_SESSION_KEY);
if (!user) {
log.error("User object was not found in the session");
throw constants.ERRORS.USER_NOT_FOUND;
}
var unitName = user.domain + ".cdmf.unit.device.type." + deviceType + "." + unitPostfix;
if (new File("/app/units/" + unitName).isExists()) {
return unitName;
}
unitName = "cdmf.unit.device.type." + deviceType + "." + unitPostfix;
if (new File("/app/units/" + unitName).isExists()) {
return unitName;
}
return null;
};
publicMethods.getDeviceTypesScopesList = function () {
var dirs = new File("/app/units/").listFiles();
var scopesList = [];
for (var i = 0; i < dirs.length; i++) {
var unitName = dirs[i].getName();
if (unitName.match(/^cdmf\.unit\.device\.type\..*\.type-view$/g)) {
var deviceTypeConfigFile = new File("/app/units/" + unitName + "/private/config.json");
if (deviceTypeConfigFile.isExists()) {
try {
deviceTypeConfigFile.open("r");
var config = deviceTypeConfigFile.readAll();
config = config.replace("%https.ip%", server.address("https"));
config = config.replace("%http.ip%", server.address("http"));
var deviceTypeConfig = parse(config);
if (deviceTypeConfig.deviceType && deviceTypeConfig.deviceType.scopes) {
scopesList = scopesList.concat(deviceTypeConfig.deviceType.scopes);
}
} catch (err) {
log.error("Error while reading device config file for `" + deviceType + "`: " + err);
} finally {
deviceTypeConfigFile.close();
}
}
}
}
return scopesList;
};
/**
* Escapes special characters such as <,>,',",...etc
* This will prevent XSS attacks upon JSON.
* @param text
* @returns {*}
*/
publicMethods.encodeJson = function (text) {
if (text) {
return text
.replace(/\\u003c/g, "&lt;")
.replace(/</g, "&lt;")
.replace(/\\u003e/g, "&gt;")
.replace(/>/g, "&gt;")
.replace(/\\u0027/g, "&#39;")
.replace(/'/g, "&#39;")
.replace(/\\"/g, "&quot;")
.replace(/\\u0022/g, "&quot;");
} else {
return "";
}
};
publicMethods.md5 = function (s) {
function L(k, d) {
return (k << d) | (k >>> (32 - d))
}
function K(G, k) {
var I, d, F, H, x;
F = (G & 2147483648);
H = (k & 2147483648);
I = (G & 1073741824);
d = (k & 1073741824);
x = (G & 1073741823) + (k & 1073741823);
if (I & d) {
return (x ^ 2147483648 ^ F ^ H)
}
if (I | d) {
if (x & 1073741824) {
return (x ^ 3221225472 ^ F ^ H)
} else {
return (x ^ 1073741824 ^ F ^ H)
}
} else {
return (x ^ F ^ H)
}
}
function r(d, F, k) {
return (d & F) | ((~d) & k)
}
function q(d, F, k) {
return (d & k) | (F & (~k))
}
function p(d, F, k) {
return (d ^ F ^ k)
}
function n(d, F, k) {
return (F ^ (d | (~k)))
}
function u(G, F, aa, Z, k, H, I) {
G = K(G, K(K(r(F, aa, Z), k), I));
return K(L(G, H), F)
}
function f(G, F, aa, Z, k, H, I) {
G = K(G, K(K(q(F, aa, Z), k), I));
return K(L(G, H), F)
}
function D(G, F, aa, Z, k, H, I) {
G = K(G, K(K(p(F, aa, Z), k), I));
return K(L(G, H), F)
}
function t(G, F, aa, Z, k, H, I) {
G = K(G, K(K(n(F, aa, Z), k), I));
return K(L(G, H), F)
}
function e(G) {
var Z;
var F = G.length;
var x = F + 8;
var k = (x - (x % 64)) / 64;
var I = (k + 1) * 16;
var aa = Array(I - 1);
var d = 0;
var H = 0;
while (H < F) {
Z = (H - (H % 4)) / 4;
d = (H % 4) * 8;
aa[Z] = (aa[Z] | (G.charCodeAt(H) << d));
H++
}
Z = (H - (H % 4)) / 4;
d = (H % 4) * 8;
aa[Z] = aa[Z] | (128 << d);
aa[I - 2] = F << 3;
aa[I - 1] = F >>> 29;
return aa
}
function B(x) {
var k = "", F = "", G, d;
for (d = 0; d <= 3; d++) {
G = (x >>> (d * 8)) & 255;
F = "0" + G.toString(16);
k = k + F.substr(F.length - 2, 2)
}
return k
}
function J(k) {
k = k.replace(/rn/g, "n");
var d = "";
for (var F = 0; F < k.length; F++) {
var x = k.charCodeAt(F);
if (x < 128) {
d += String.fromCharCode(x)
} else {
if ((x > 127) && (x < 2048)) {
d += String.fromCharCode((x >> 6) | 192);
d += String.fromCharCode((x & 63) | 128)
} else {
d += String.fromCharCode((x >> 12) | 224);
d += String.fromCharCode(((x >> 6) & 63) | 128);
d += String.fromCharCode((x & 63) | 128)
}
}
}
return d
}
var C = Array();
var P, h, E, v, g, Y, X, W, V;
var S = 7, Q = 12, N = 17, M = 22;
var A = 5, z = 9, y = 14, w = 20;
var o = 4, m = 11, l = 16, j = 23;
var U = 6, T = 10, R = 15, O = 21;
s = J(s);
C = e(s);
Y = 1732584193;
X = 4023233417;
W = 2562383102;
V = 271733878;
for (P = 0; P < C.length; P += 16) {
h = Y;
E = X;
v = W;
g = V;
Y = u(Y, X, W, V, C[P + 0], S, 3614090360);
V = u(V, Y, X, W, C[P + 1], Q, 3905402710);
W = u(W, V, Y, X, C[P + 2], N, 606105819);
X = u(X, W, V, Y, C[P + 3], M, 3250441966);
Y = u(Y, X, W, V, C[P + 4], S, 4118548399);
V = u(V, Y, X, W, C[P + 5], Q, 1200080426);
W = u(W, V, Y, X, C[P + 6], N, 2821735955);
X = u(X, W, V, Y, C[P + 7], M, 4249261313);
Y = u(Y, X, W, V, C[P + 8], S, 1770035416);
V = u(V, Y, X, W, C[P + 9], Q, 2336552879);
W = u(W, V, Y, X, C[P + 10], N, 4294925233);
X = u(X, W, V, Y, C[P + 11], M, 2304563134);
Y = u(Y, X, W, V, C[P + 12], S, 1804603682);
V = u(V, Y, X, W, C[P + 13], Q, 4254626195);
W = u(W, V, Y, X, C[P + 14], N, 2792965006);
X = u(X, W, V, Y, C[P + 15], M, 1236535329);
Y = f(Y, X, W, V, C[P + 1], A, 4129170786);
V = f(V, Y, X, W, C[P + 6], z, 3225465664);
W = f(W, V, Y, X, C[P + 11], y, 643717713);
X = f(X, W, V, Y, C[P + 0], w, 3921069994);
Y = f(Y, X, W, V, C[P + 5], A, 3593408605);
V = f(V, Y, X, W, C[P + 10], z, 38016083);
W = f(W, V, Y, X, C[P + 15], y, 3634488961);
X = f(X, W, V, Y, C[P + 4], w, 3889429448);
Y = f(Y, X, W, V, C[P + 9], A, 568446438);
V = f(V, Y, X, W, C[P + 14], z, 3275163606);
W = f(W, V, Y, X, C[P + 3], y, 4107603335);
X = f(X, W, V, Y, C[P + 8], w, 1163531501);
Y = f(Y, X, W, V, C[P + 13], A, 2850285829);
V = f(V, Y, X, W, C[P + 2], z, 4243563512);
W = f(W, V, Y, X, C[P + 7], y, 1735328473);
X = f(X, W, V, Y, C[P + 12], w, 2368359562);
Y = D(Y, X, W, V, C[P + 5], o, 4294588738);
V = D(V, Y, X, W, C[P + 8], m, 2272392833);
W = D(W, V, Y, X, C[P + 11], l, 1839030562);
X = D(X, W, V, Y, C[P + 14], j, 4259657740);
Y = D(Y, X, W, V, C[P + 1], o, 2763975236);
V = D(V, Y, X, W, C[P + 4], m, 1272893353);
W = D(W, V, Y, X, C[P + 7], l, 4139469664);
X = D(X, W, V, Y, C[P + 10], j, 3200236656);
Y = D(Y, X, W, V, C[P + 13], o, 681279174);
V = D(V, Y, X, W, C[P + 0], m, 3936430074);
W = D(W, V, Y, X, C[P + 3], l, 3572445317);
X = D(X, W, V, Y, C[P + 6], j, 76029189);
Y = D(Y, X, W, V, C[P + 9], o, 3654602809);
V = D(V, Y, X, W, C[P + 12], m, 3873151461);
W = D(W, V, Y, X, C[P + 15], l, 530742520);
X = D(X, W, V, Y, C[P + 2], j, 3299628645);
Y = t(Y, X, W, V, C[P + 0], U, 4096336452);
V = t(V, Y, X, W, C[P + 7], T, 1126891415);
W = t(W, V, Y, X, C[P + 14], R, 2878612391);
X = t(X, W, V, Y, C[P + 5], O, 4237533241);
Y = t(Y, X, W, V, C[P + 12], U, 1700485571);
V = t(V, Y, X, W, C[P + 3], T, 2399980690);
W = t(W, V, Y, X, C[P + 10], R, 4293915773);
X = t(X, W, V, Y, C[P + 1], O, 2240044497);
Y = t(Y, X, W, V, C[P + 8], U, 1873313359);
V = t(V, Y, X, W, C[P + 15], T, 4264355552);
W = t(W, V, Y, X, C[P + 6], R, 2734768916);
X = t(X, W, V, Y, C[P + 13], O, 1309151649);
Y = t(Y, X, W, V, C[P + 4], U, 4149444226);
V = t(V, Y, X, W, C[P + 11], T, 3174756917);
W = t(W, V, Y, X, C[P + 2], R, 718787259);
X = t(X, W, V, Y, C[P + 9], O, 3951481745);
Y = K(Y, h);
X = K(X, E);
W = K(W, v);
V = K(V, g)
}
var i = B(Y) + B(X) + B(W) + B(V);
return i.toLowerCase()
};
return publicMethods;
}();

View File

@ -1,111 +0,0 @@
{{!
Copyright (c) 2016, WSO2 Inc. (http://www.wso2.org) All Rights Reserved.
WSO2 Inc. licenses this file to you under the Apache License,
Version 2.0 (the "License"); you may not use this file except
in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing,
software distributed under the License is distributed on an
"AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
KIND, either express or implied. See the License for the
specific language governing permissions and limitations
under the License.
}}
{{unit "cdmf.unit.ui.title" pageTitle="Add Certificate"}}
{{#zone "breadcrumbs"}}
<li>
<a href="{{@app.context}}/">
<i class="icon fw fw-home"></i>
</a>
</li>
<li>
<a href="{{@app.context}}/certificates">
Certificates
</a>
</li>
<li>
<a href="{{@app.context}}/certificates/add">
Add
</a>
</li>
{{/zone}}
{{#zone "content"}}
{{#if isAuthorized}}
<!-- content/body -->
<div class="row">
<div class="col-md-12">
<!-- content -->
<div id="certificate-create-form" class="container col-centered wr-content">
<div class="wr-form">
<p class="page-sub-title">Add Certificate</p>
<p>Please note that * sign represents required fields of data.</p>
<hr/>
<div class="row">
<div class="col-lg-8">
<div id="certificate-create-error-msg" class="alert alert-danger hidden" role="alert">
<i class="icon fw fw-error"></i><span></span>
</div>
<label class="wr-input-label ">
Serial Number *
</label>
<br>
<div id="serialNoInputField" class="form-group wr-input-control">
<input type="text" id="serialNo" class="form-control"/>
</div>
<label class="wr-input-label">Certificate *</label>
<div id="certificateField" class="form-group wr-input-control">
<input type="file" id="certificate" class="form-control"/>
</div>
</div>
</div>
<br>
<div class="row">
<div class="col-lg-8">
<button id="add-certificate-btn" class="wr-btn">Add Certificate</button>
</div>
</div>
</div>
</div>
<div id="certificate-created-msg" class="container col-centered wr-content hidden">
<div class="wr-form">
<p class="page-sub-title">Certificate was added successfully.</p>
<br>
<br>Please click <b>"Add Another Certificate"</b>, if you wish to add another certificate or
click
<b>"View Certificate List"</b> to complete the process and go back to the certificate list.
<hr/>
<button class="wr-btn" onclick="window.location.href='{{@app.context}}/certificates'">View Certificate List
</button>
<a href="{{@app.context}}/certificates/add" class="cu-btn-inner">
<span class="fw-stack">
<i class="fw fw-circle-outline fw-stack-2x"></i>
<i class="fw fw-add fw-stack-1x"></i>
</span>
Add Another Certificate
</a>
</div>
</div>
<!-- /content -->
</div>
</div>
<!-- /content/body -->
{{else}}
<h1 class="page-sub-title">
Permission Denied
</h1>
<br>
You not authorized to enter Certificate Management Section.
<br>
{{/if}}
{{/zone}}
{{#zone "bottomJs"}}
{{js "/js/certificate-create.js"}}
{{/zone}}

View File

@ -1,46 +0,0 @@
/*
* Copyright (c) 2018 - 2023, Entgra (Pvt) Ltd. (http://www.entgra.io) All Rights Reserved.
*
* Entgra (Pvt) Ltd. licenses this file to you under the Apache License,
* Version 2.0 (the "License"); you may not use this file except
* in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
/**
* Returns the dynamic state to be populated by add-user page.
*
* @param viewModel Object that gets updated with the dynamic state of this page to be presented
* @returns {*} A viewModel object that returns the dynamic state of this page to be presented
*/
function onRequest(context) {
// var log = new Log("units/user-create/create.js");
var userModule = require("/app/modules/business-controllers/user.js")["userModule"];
var mdmProps = require("/app/modules/conf-reader/main.js")["conf"];
var viewModel = {};
viewModel.isAuthorized = userModule.isAuthorized("/permission/admin/device-mgt/certificates/manage");
var response = userModule.getRolesByUserStore();
if (response["status"] == "success") {
viewModel["roles"] = response["content"];
}
viewModel["charLimit"] = mdmProps["userValidationConfig"]["usernameLength"];
viewModel["usernameJSRegEx"] = mdmProps["userValidationConfig"]["usernameJSRegEx"];
viewModel["usernameHelpText"] = mdmProps["userValidationConfig"]["usernameHelpMsg"];
viewModel["usernameRegExViolationErrorMsg"] = mdmProps["userValidationConfig"]["usernameRegExViolationErrorMsg"];
viewModel["firstnameJSRegEx"] = mdmProps["userValidationConfig"]["firstnameJSRegEx"];
viewModel["firstnameRegExViolationErrorMsg"] = mdmProps["userValidationConfig"]["firstnameRegExViolationErrorMsg"];
viewModel["lastnameJSRegEx"] = mdmProps["userValidationConfig"]["lastnameJSRegEx"];
viewModel["lastnameRegExViolationErrorMsg"] = mdmProps["userValidationConfig"]["lastnameRegExViolationErrorMsg"];
return viewModel;
}

View File

@ -1,5 +0,0 @@
{
"version": "1.0.0",
"uri": "/certificates/add",
"layout": "cdmf.layout.default"
}

View File

@ -1,129 +0,0 @@
/*
* Copyright (c) 2018 - 2023, Entgra (Pvt) Ltd. (http://www.entgra.io) All Rights Reserved.
*
* Entgra (Pvt) Ltd. licenses this file to you under the Apache License,
* Version 2.0 (the "License"); you may not use this file except
* in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
var pemContent = "";
var errorMsgWrapper = "#certificate-create-error-msg";
var errorMsg = "#certificate-create-error-msg span";
var validateInline = {};
var clearInline = {};
var base_api_url = "/api/certificate-mgt/v1.0";
var enableInlineError = function (inputField, errorMsg, errorSign) {
var fieldIdentifier = "#" + inputField;
var errorMsgIdentifier = "#" + inputField + " ." + errorMsg;
var errorSignIdentifier = "#" + inputField + " ." + errorSign;
if (inputField) {
$(fieldIdentifier).addClass(" has-error has-feedback");
}
if (errorMsg) {
$(errorMsgIdentifier).removeClass(" hidden");
}
if (errorSign) {
$(errorSignIdentifier).removeClass(" hidden");
}
};
var disableInlineError = function (inputField, errorMsg, errorSign) {
var fieldIdentifier = "#" + inputField;
var errorMsgIdentifier = "#" + inputField + " ." + errorMsg;
var errorSignIdentifier = "#" + inputField + " ." + errorSign;
if (inputField) {
$(fieldIdentifier).removeClass(" has-error has-feedback");
}
if (errorMsg) {
$(errorMsgIdentifier).addClass(" hidden");
}
if (errorSign) {
$(errorSignIdentifier).addClass(" hidden");
}
};
function readSingleFile(evt) {
var f = evt.target.files[0];
if (f) {
var r = new FileReader();
r.onload = function (e) {
var contents = e.target.result;
if (f.type == "application/x-x509-ca-cert") {
pemContent = contents;
console.log(contents);
console.log(pemContent);
pemContent = pemContent.substring(28, pemContent.length - 27);
console.log(pemContent);
$(errorMsgWrapper).addClass("hidden");
} else {
$(errorMsg).text("Certificate must be a .pem file containing a valid certificate data.");
$(errorMsgWrapper).removeClass("hidden");
}
}
r.readAsText(f);
} else {
//inline error
}
}
$(document).ready(function () {
pemContent = "";
document.getElementById('certificate').addEventListener('change', readSingleFile, false);
/**
* Following click function would execute
* when a user clicks on "Add Certificate" button.
*/
$("button#add-certificate-btn").click(function () {
var serialNoInput = $("input#serialNo");
var serialNo = serialNoInput.val();
if (!serialNo) {
$(errorMsg).text("Serial Number is a required field. It cannot be empty.");
$(errorMsgWrapper).removeClass("hidden");
} else if (!pemContent) {
$(errorMsg).text(" .pem file must contains certificate information.");
$(errorMsgWrapper).removeClass("hidden");
} else {
var addCertificateFormData = {};
addCertificateFormData.serial = serialNo;
addCertificateFormData.pem = pemContent;
var certificateList = [];
certificateList.push(addCertificateFormData);
var serviceUrl = base_api_url + "/admin/certificates";
invokerUtil.post(
serviceUrl,
certificateList,
function (data) {
// Refreshing with success message
$("#certificate-create-form").addClass("hidden");
$("#certificate-created-msg").removeClass("hidden");
}, function (data) {
if (data["status"] == 500) {
$(errorMsg).text("An unexpected error occurred at backend server. Please try again later.");
} else {
$(errorMsg).text(data);
}
$(errorMsgWrapper).removeClass("hidden");
}
);
}
});
});

View File

@ -1,122 +0,0 @@
{{!
Copyright (c) 2016, WSO2 Inc. (http://www.wso2.org) All Rights Reserved.
WSO2 Inc. licenses this file to you under the Apache License,
Version 2.0 (the "License"); you may not use this file except
in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing,
software distributed under the License is distributed on an
"AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
KIND, either express or implied. See the License for the
specific language governing permissions and limitations
under the License.
}}
{{unit "cdmf.unit.ui.title" pageTitle="Add Certificate"}}
{{unit "cdmf.unit.ui.modal"}}
{{#zone "breadcrumbs"}}
<li>
<a href="{{@app.context}}/">
<i class="icon fw fw-home"></i>
</a>
</li>
<li>
<a href="{{@app.context}}/certificates">
Certificate
</a>
</li>
{{/zone}}
{{#zone "navbarActions"}}
{{#if removePermitted}}
<li>
<a href="{{@app.context}}/certificates/add">
<span class="fw-stack">
<i class="fw fw-circle-outline fw-stack-2x"></i>
<i class="fw fw-document fw-stack-1x"></i>
</span>
Add Certificate
</a>
</li>
{{/if}}
{{/zone}}
{{#zone "content"}}
{{unit "cdmf.unit.data-tables-extended"}}
<!-- content -->
<div id="loading-content" class="col-centered">
{{#if removePermitted}}
<input type="hidden" id="can-remove" value="true"/>
{{/if}}
{{#if viewPermitted}}
<input type="hidden" id="can-view" value="true"/>
{{/if}}
<i class="fw fw-settings fw-spin fw-2x"></i>
Loading Certificates . . .
<br>
</div>
<div id="certificate-listing-status" class="raw hidden">
<ul style="list-style-type: none;">
<li class="message message-info" >
<h4>
<i class="icon fw fw-info"></i>
<a id="certificate-listing-status-msg"></a>
</h4>
</li>
</ul>
</div>
<div id="certificate-table" class="hidden" data-user={{adminUser}}>
<table class="table table-striped table-hover list-table display responsive nowrap data-table grid-view"
id="certificate-grid">
<thead>
<tr class="sort-row">
<th class="no-sort"></th>
<th>By Serial Number</th>
<th class="no-sort"></th>
<th class="no-sort"></th>
</tr>
<tr class="filter-row filter-box">
<th colspan="3">
<label class="wr-input-label" for="search-by-certificate">
By Serial Number
</label>
<input id="search-by-certificate" type="text" class="form-control"
placeholder="Search By Serial Number">
</th>
<th style="vertical-align:bottom;">
<button id="search-btn" class="wr-btn">
Search
</button>
</th>
</tr>
</thead>
<tbody id="ast-container">
<br class="c-both"/>
</tbody>
</table>
</div>
<br class="c-both"/>
<div id="content-filter-types" style="display: none">
<div class="sort-title">Sort By</div>
<div class="sort-options">
<a href="#">By Serial Number</a>
</div>
</div>
{{/zone}}
{{#zone "bottomJs"}}
<script id="certificate-listing" data-current-user="{{@user.username}}"
src="{{@page.publicUri}}/templates/certificate-listing.hbs"
type="text/x-handlebars-template"></script>
{{js "/js/certificate-listing.js"}}
{{/zone}}

View File

@ -1,5 +0,0 @@
{
"version": "1.0.0",
"uri": "/certificates",
"layout": "cdmf.layout.default"
}

View File

@ -1,201 +0,0 @@
/*
* Copyright (c) 2018 - 2023, Entgra (Pvt) Ltd. (http://www.entgra.io) All Rights Reserved.
*
* Entgra (Pvt) Ltd. licenses this file to you under the Apache License,
* Version 2.0 (the "License"); you may not use this file except
* in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
/*
* Sorting function of certificates
* listed on Certificate Management page in WSO2 MDM Console.
*/
$(function () {
var sortableElem = '.wr-sortable';
$(sortableElem).sortable({
beforeStop: function () {
var sortedIDs = $(this).sortable('toArray');
}
});
$(sortableElem).disableSelection();
});
var modalPopup = ".modal";
var modalPopupContainer = modalPopup + " .modal-content";
var modalPopupContent = modalPopup + " .modal-content";
var body = "body";
var isInit = true;
var base_api_url = "/api/certificate-mgt/v1.0";
$(".icon .text").res_text(0.2);
/*
* set popup maximum height function.
*/
function setPopupMaxHeight() {
$(modalPopupContent).css('max-height', ($(body).height() - ($(body).height() / 100 * 30)));
$(modalPopupContainer).css('margin-top', (-($(modalPopupContainer).height() / 2)));
}
/*
* show popup function.
*/
function showPopup() {
$(modalPopup).modal('show');
}
/*
* hide popup function.
*/
function hidePopup() {
$(modalPopupContent).html('');
$(modalPopup).modal('hide');
$('body').removeClass('modal-open').css('padding-right','0px');
$('.modal-backdrop').remove();
}
/**
* Following click function would execute
* when a user clicks on "Remove" link
* on Certificate Listing page in WSO2 MDM Console.
*/
function removeCertificate(serialNumber) {
var serviceUrl = base_api_url + "/admin/certificates/" + serialNumber;
modalDialog.header('Do you really want to remove this certificate ?');
modalDialog.footer('<div class="buttons"><a href="#" id="remove-certificate-yes-link" class="btn-operations">' +
'Remove</a><a href="#" id="remove-certificate-cancel-link" class="btn-operations btn-default">Cancel</a>' +
'</div>');
modalDialog.show();
$("a#remove-certificate-yes-link").click(function () {
invokerUtil.delete(
serviceUrl,
function () {
$("#" + serialNumber).remove();
var newCertificateListCount = $(".user-list > span").length;
$("#certificate-listing-status-msg").text("Total number of Certificates found : " +
newCertificateListCount);
modalDialog.header('Done. Certificate was successfully removed.');
modalDialog.footer('<div class="buttons"><a href="#" id="remove-certificate-success-link" ' +
'class="btn-operations">Ok</a></div>');
$("a#remove-certificate-success-link").click(function () {
modalDialog.hide();
});
},
function () {
modalDialog.header('An unexpected error occurred. Please try again later.');
modalDialog.footer('<div class="buttons"><a href="#" id="remove-certificate-error-link" ' +
'class="btn-operations">Ok</a></div>');
modalDialog.showAsError();
$("a#remove-certificate-error-link").click(function () {
modalDialog.hide();
});
}
);
});
$("a#remove-certificate-cancel-link").click(function () {
modalDialog.hide();
});
}
/**
* Following on click function would execute
* when a user type on the search field on certificate Listing page in
* WSO2 MDM Console then click on the search button.
*/
$("#search-btn").click(function () {
var searchQuery = $("#search-by-certificate").val();
$("#ast-container").empty();
loadCertificates(searchQuery);
});
/**
* Following function would execute
* when a user clicks on the list item
* initial mode and with out select mode.
*/
function InitiateViewOption() {
if ($("#can-view").val()) {
$(location).attr('href', $(this).data("url"));
} else {
modalDialog.header('Unauthorized action!');
modalDialog.content('You do not have permission to view this certificate.');
modalDialog.showAsAWarning();
}
}
function loadCertificates(searchParam) {
$("#loading-content").show();
var certificateListing = $("#certificate-listing");
var certificateListingSrc = certificateListing.attr("src");
$.template("certificate-listing", certificateListingSrc, function (template) {
var serviceURL = base_api_url + "/admin/certificates";
if (searchParam != null && searchParam != undefined && searchParam.trim() != '') {
serviceURL = base_api_url + "/admin/certificates?" + searchParam;
}
var successCallback = function (data, textStatus, jqXHR) {
if (jqXHR.status == 200 && data) {
data = JSON.parse(data);
var viewModel = {};
viewModel.certificates = data.certificates;
for (var i = 0; i < viewModel.certificates.length; i++) {
viewModel.certificates[i].removePermitted = true;
viewModel.certificates[i].viewPermitted = true;
}
if (viewModel.certificates.length > 0) {
$('#certificate-table').removeClass('hidden');
$('#ast-container').removeClass('hidden');
$('#certificate-listing-status-msg').text("");
var content = template(viewModel);
$("#ast-container").html(content);
} else {
$('#certificate-table').addClass('hidden');
$('#certificate-listing-status-msg').text('No certificate is available to be displayed.');
$('#certificate-listing-status').removeClass('hidden');
}
$("#loading-content").hide();
if (isInit) {
$('#certificate-grid').datatables_extended();
isInit = false;
}
$(".icon .text").res_text(0.2);
}
};
invokerUtil.get(serviceURL,
successCallback,
function (message) {
$('#ast-container').addClass('hidden');
$('#certificate-listing-status-msg').
text('Invalid search query. Try again with a valid search query');
}
);
});
}
$(document).ready(function () {
loadCertificates();
$(".viewEnabledIcon").click(function () {
InitiateViewOption();
});
});

View File

@ -1,30 +0,0 @@
{{#each certificates}}
<tr data-type="selectable" id="{{serialNumber}}" data-username="{{serialNumber}}">
<td class="remove-padding icon-only content-fill viewEnabledIcon" data-username="{{serialNumber}}">
<div class="thumbnail icon">
<i class="square-element text fw fw-document"></i>
</div>
</td>
<td class="remove-padding-top" data-search="{{serialNumber}}" data-display="{{serialNumber}}"><i
class="fw-mobile"></i> {{serialNumber}}</td>
<td class="remove-padding-top" data-search="{{subject}}" data-display="{{subject}}"><i
class="fw-policy"></i> {{subject}}</td>
<td class="text-right content-fill text-left-on-grid-view no-wrap">
{{#unequal adminUser serialNumber }}
{{#if removePermitted}}
<a href="#" data-username="{{serialNumber}}" data-userid="{{userid}}"
data-click-event="remove-form" onclick="javascript:removeCertificate('{{serialNumber}}')"
class="btn padding-reduce-on-grid-view remove-user-link">
<span class="fw-stack">
<i class="fw fw-circle-outline fw-stack-2x"></i>
<i class="fw fw-delete fw-stack-1x"></i>
</span>
<span class="hidden-xs hidden-on-grid-view">Remove</span>
</a>
{{/if}}
{{/unequal}}
</td>
</tr>
{{/each}}

View File

@ -1,172 +0,0 @@
{{!
Copyright (c) 2018, WSO2 Inc. (http://www.wso2.org) All Rights Reserved.
WSO2 Inc. licenses this file to you under the Apache License,
Version 2.0 (the "License"); you may not use this file except
in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing,
software distributed under the License is distributed on an
"AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
KIND, either express or implied. See the License for the
specific language governing permissions and limitations
under the License.
}}
{{#zone "title"}}{{! to override parent page title }}{{/zone}}
{{unit "cdmf.unit.ui.title" pageTitle="Consent Page"}}
{{#zone "content"}}
<div class="row">
<div class="col-xs-12 col-sm-8 col-md-8 col-lg-8 col-sm-offset-2 col-md-offset-2 col-lg-offset-2">
<div class="alert alert-info"><h3>COOKIE POLICY</h3></div>
<div class="panel-body">
<h3>About Entgra IoT Server</h3>
<p>Entgra IoT Server 4.1.0 is a complete solution that enables device manufacturers and enterprises to
connect and manage their devices, build apps, manage events, secure devices and data, and visualize
sensor data in a scalable manner.</p>
<p>It also offers a complete and secure Enterprise Mobility Management (EMM/MDM) solution that aims to
address mobile computing challenges faced by enterprises today. Supporting iOS, Android, and Windows
devices, it helps organizations deal with both Corporate Owned, Personally Enabled (COPE) and
employee-owned devices with the Bring Your Own Device (BYOD) concept.</p>
<p>Entgra IoT Server 4.1.0 comes with advanced analytics, enabling users to analyze speed, proximity,
and
geo-fencing information of devices including details of those in motion and stationary state.</p>
</p>
<h2>Cookie Policy</h2>
<p>IoT Server uses cookies to provide you with the best user experience, and to securely identify you.
You can disable cookies if you so wish . However you might not be able to access some of the services
if you disable cookies.</p>
<h3>What is a cookie?</h3>
<p>A browser cookie is a small piece of data that is stored on your device to help websites and mobile
apps remember things about you. Other technologies, including Web storage and identifiers associated
with your device, may be used for similar purposes. In this policy, we use the term “cookies” to
discuss all of these technologies.</p>
<h3>How does Entgra IoT Server 4.1.0 process cookies?</h3>
<p>Entgra IoT Server 4.1.0 uses cookies to store and retrieve information on your browser. This
information is used to provide a better user experience. Some cookies serve the purpose of allowing a
user to log in to the system, maintain sessions, and keep track of activities within the login
session.</p>
<p>Some cookies in Entgra IoT Server 4.1.0 are used to personally identify you. However, the cookie
lifetime ends once your session ends, i.e., after you log-out, or after the session expiry time has
elapsed.</p>
<p>Some cookies are simply used to give you a more personalised web experience, and these cannot be used
to identify you or your activities personally.</p>
<p>This Cookie Policy is part of the IoT Server <a href="{{@app.context}}/privacy-policy">Privacy Policy.</a>
</p>
<h3>What does Entgra IoT Server 4.1.0 use cookies for?</h3>
<p>Cookies are used for two purposes in Entgra IoT Server 4.1.0.</p>
<ol>
<li>To identify you and provide security</li>
<li>To provide a satisfying user experience.</li>
</ol>
<h4><u>Preferences</u></h4>
<p>Entgra IoT Server 4.1.0 uses cookies to remember your settings and preferences and to auto-fill the
fields to make your interactions with the site easier.</p>
<p>These cookies can not be used to personally identify you.</p>
<h4><u>Security</u></h4>
<ol>
<li>Entgra IoT Server 4.1.0 uses selected cookies to identify and prevent security risks. For
example,
Entgra IoT Server 4.1.0 may use cookies to store your session information to prevent others from
changing your password without your username and password.
</li>
<li>Entgra IoT Server 4.1.0 uses session cookie to maintain your active session.</li>
<li>Entgra IoT Server 4.1.0 may use a temporary cookie when performing multi-factor authentication
and
federated authentication.
</li>
<li>Entgra IoT Server 4.1.0 may use permanent cookies to detect the devices you have logged in
previously. This is to to calculate the <b>risk level</b> associated with your current login
attempt. Using these cookies protects you and your account from possible attacks.
</li>
</ol>
<h4><u>Performance</u></h4>
<p>Entgra IoT Server 4.1.0 may use cookies to allow <b>Remember Me</b> functionalities.</p>
<h4><u>Analytics</u></h4>
<p>Entgra IoT Server 4.1.0 as a product does not use cookies for analytical purposes.</p>
<h4><u>Third party cookies</u></h4>
<p>Using Entgra IoT Server 4.1.0 may cause third-party cookie to be set in your browser. Entgra IoT
Server
4.1.0 has no control over how any of them operate. The third-party cookies that maybe set
include:</p>
<ol>
<li>Any social login sites. For example, third-party cookies may be set when Entgra IoT Server 4.1.0
is configured to use “social” or “federated” login, and you opt to login with your “Social
Account”.
</li>
<li>Any third party federated login.</li>
</ol>
<p>Entgra strongly advises you to refer the respective cookie policies of such sites carefully as Entgra has
no knowledge or use on these cookies.</p>
<h3>What type of cookies does Entgra IoT Server 4.1.0 use?</h3>
<p>Entgra IoT Server 4.1.0 uses persistent cookies and session cookies. A persistent cookie helps
Entgra IS
3.8.0 to recognize you as an existing user so that it is easier to return to Entgra or interact with
Entgra IS 3.8.0 without signing in again. After you sign in, a persistent cookie stays in your browser
and will be read by Entgra IoT Server 4.1.0 when you return to Entgra IoT Server 4.1.0.</p>
<p>A session cookie is a cookie that is erased when the user closes the Web browser. The session cookie
is stored in temporarily and is not retained after the browser is closed. Session cookies do not
collect information from the users computer.</p>
<h3>How do I control my cookies?</h3>
<p>Most browsers allow you to control cookies through settings. However, if you limit the given ability
for websites to set cookies, you may worsen your overall user experience since it will no longer be
personalized to you. It may also stop you from saving customized settings like login information.
Most likely, disabling cookies will make it unable for you to use authentication and authorization
functionalities offered by Entgra IoT Server 4.1.0.</p>
<p>If you have any questions or concerns regarding the use of cookies, please contact the entity or
individuals (or their data protection officer, if applicable) running this Entgra IoT Server 4.1.0
instance.</p>
<h3>What are the cookies used?</h3>
<table class="table table-striped table-bordered">
<thead>
<tr>
<th>Cookie Name</th>
<th>Purpose</th>
<th>Retention</th>
</thead>
<tbody>
<tr>
<td>JSESSIONID</td>
<td>To keep your session data in order to give you a good user experience.</td>
<td>Session</td>
</tr>
<tr>
<td>commonAuthId</td>
<td>Used to authenticate the the logged in session.</td>
<td>Session</td>
</tr>
<tr>
<td>samlssoTokenId</td>
<td>Used to map the logged in user with the SAML token.</td>
<td>Request</td>
</tr>
<tr>
<td>requestedURI</td>
<td>The URI you are accessing.</td>
<td>Session</td>
</tr>
</tbody>
</table>
<h3>Disclaimer</h3>
<p>This cookie policy is only for illustrative purposes of the product Entgra IoT Server 4.1.0. The
content in the policy is technically correct at the time of the product shipment. The
entity,organization or individual that runs this Entgra IoT Server 4.1.0 instance has full authority
and responsibility with regard to the effective Cookie Policy. Entgra, its employees, partners, and
affiliates do not have access to and do not require, store, process or control any of the data,
including personal data contained in Entgra IoT Server 4.1.0. All data, including personal data is
controlled and processed by the entity, organization or individual running Entgra IoT Server 4.1.0.
Entgra, its employees partners and affiliates are not a data processor or a data controller within the
meaning of any data privacy regulations. Entgra does not provide any warranties or undertake any
responsibility or liability in connection with the lawfulness or the manner and purposes for which
Entgra IoT Server 4.1.0 is used by such entities, organizations or persons.</p>
</div>
</div>
</div>
{{/zone}}

View File

@ -1,6 +0,0 @@
{
"version": "1.0.0",
"layout": "uuf.layout.sign-in",
"uri": "/cookie-policy",
"isAnonymous": true
}

View File

@ -1,234 +0,0 @@
{{!
Copyright (c) 2016, WSO2 Inc. (http://www.wso2.org) All Rights Reserved.
WSO2 Inc. licenses this file to you under the Apache License,
Version 2.0 (the "License"); you may not use this file except
in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing,
software distributed under the License is distributed on an
"AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
KIND, either express or implied. See the License for the
specific language governing permissions and limitations
under the License.
}}
{{unit "cdmf.unit.ui.title" pageTitle="Home"}}
{{#zone "breadcrumbs"}}
<li>
<a href="{{@app.context}}/">
<i class="icon fw fw-home"></i>
</a>
</li>
{{/zone}}
{{#zone "content"}}
<div class="row">
{{#if permissions.VIEW_DASHBOARD}}
<div class="col-md-3 wr-stats-board">
<div class="wr-stats-board-tile">
<div class="tile-name">Devices</div>
<div>
<div class="tile-icon"><i class="fw fw-mobile"></i></div>
<div class="tile-stats">
<span id="device-count">{{deviceCount}}</span>
<span class="tile-stats-free">
<!--suppress HtmlUnknownTarget -->
{{#if deviceCount}}
<a href="{{@app.context}}/devices">
<span class="fw-stack">
<i class="fw fw-circle-outline fw-stack-2x"></i>
<i class="fw fw-view fw-stack-1x"></i>
</span>
View
</a>
{{/if}}
<!--suppress HtmlUnknownTarget -->
<a href="{{@app.context}}/device/enroll">
<span class="fw-stack">
<i class="fw fw-circle-outline fw-stack-2x"></i>
<i class="fw fw-add fw-stack-1x"></i>
</span>
Add
</a>
</span>
</div>
</div>
</div>
</div>
<div class="col-md-3 wr-stats-board">
<div class="wr-stats-board-tile">
<div class="tile-name">Groups</div>
<div>
<div class="tile-icon"><i class="fw fw-group"></i></div>
<div class="tile-stats">
<span id="group-count">{{groupCount}}</span>
<span class="tile-stats-free">
{{#if groupCount}}
<!--suppress HtmlUnknownTarget -->
<a href="{{@app.context}}/groups">
<span class="fw-stack">
<i class="fw fw-circle-outline fw-stack-2x"></i>
<i class="fw fw-view fw-stack-1x"></i>
</span>
View
</a>
{{/if}}
<!--suppress HtmlUnknownTarget -->
<a href="{{@app.context}}/group/add">
<span class="fw-stack">
<i class="fw fw-circle-outline fw-stack-2x"></i>
<i class="fw fw-add fw-stack-1x"></i>
</span>
Add
</a>
</span>
</div>
</div>
</div>
</div>
<div class="col-md-3 wr-stats-board">
<div class="wr-stats-board-tile">
<div class="tile-name">Users</div>
<div>
<div class="tile-icon"><i class="fw fw-user"></i></div>
<div class="tile-stats">
<span id="user-count">{{userCount}}</span>
<span class="tile-stats-free">
{{#if userCount}}
<!--suppress HtmlUnknownTarget -->
<a href="{{@app.context}}/users">
<span class="fw-stack">
<i class="fw fw-circle-outline fw-stack-2x"></i>
<i class="fw fw-view fw-stack-1x"></i>
</span>
View
</a>
{{/if}}
<!--suppress HtmlUnknownTarget -->
{{#unless isCloud}}
<a href="{{@app.context}}/user/add">
<span class="fw-stack">
<i class="fw fw-circle-outline fw-stack-2x"></i>
<i class="fw fw-add fw-stack-1x"></i>
</span>
Add
</a>
{{/unless}}
</span>
</div>
</div>
</div>
</div>
<div class="col-md-3 wr-stats-board">
<div class="wr-stats-board-tile">
<div class="tile-name">Policies</div>
<div>
<div class="tile-icon"><i class="fw fw-policy"></i></div>
<div class="tile-stats">
<span id="policy-count">{{policyCount}}</span>
<span class="tile-stats-free">
{{#if policyCount}}
<!--suppress HtmlUnknownTarget -->
<a href="{{@app.context}}/policies">
<span class="fw-stack">
<i class="fw fw-circle-outline fw-stack-2x"></i>
<i class="fw fw-view fw-stack-1x"></i>
</span>
View
</a>
{{/if}}
<!--suppress HtmlUnknownTarget -->
<a href="{{@app.context}}/policy/add">
<span class="fw-stack">
<i class="fw fw-circle-outline fw-stack-2x"></i>
<i class="fw fw-add fw-stack-1x"></i>
</span>
Add
</a>
</span>
</div>
</div>
</div>
</div>
<div class="col-md-3 wr-stats-board">
<div class="wr-stats-board-tile">
<div class="tile-name">Roles</div>
<div>
<div class="tile-icon"><i class="fw fw-bookmark"></i></div>
<div class="tile-stats">
<span id="role-count">{{roleCount}}</span>
<span class="tile-stats-free">
{{#if roleCount}}
<!--suppress HtmlUnknownTarget -->
<a id="device-count-view-btn" href="{{@app.context}}/roles">
<span class="fw-stack">
<i class="fw fw-circle-outline fw-stack-2x"></i>
<i class="fw fw-view fw-stack-1x"></i>
</span>
View
</a>
{{/if}}
<!--suppress HtmlUnknownTarget -->
{{#unless isCloud}}
<a href="{{@app.context}}/role/add">
<span class="fw-stack">
<i class="fw fw-circle-outline fw-stack-2x"></i>
<i class="fw fw-add fw-stack-1x"></i>
</span>
Add
</a>
{{/unless}}
</span>
</div>
</div>
</div>
</div>
{{#if permissions.IS_ADMIN}}
<div class="col-md-3 wr-stats-board">
<div class="wr-stats-board-tile">
<div class="tile-name">Device Types</div>
<div>
<div class="tile-icon"><i class="fw fw-devices"></i></div>
<div class="tile-stats">
<span id="device-types-count">{{deviceTypeCount}}</span>
<span class="tile-stats-free">
<!--suppress HtmlUnknownTarget -->
{{#if deviceTypeCount}}
<a href="{{@app.context}}/device-types">
<span class="fw-stack">
<i class="fw fw-circle-outline fw-stack-2x"></i>
<i class="fw fw-view fw-stack-1x"></i>
</span>
View
</a>
{{/if}}
<!--suppress HtmlUnknownTarget -->
<a href="{{@app.context}}/device-type/add">
<span class="fw-stack">
<i class="fw fw-circle-outline fw-stack-2x"></i>
<i class="fw fw-add fw-stack-1x"></i>
</span>
Add
</a>
</span>
</div>
</div>
</div>
</div>
{{/if}}
{{else}}
<h1 class="page-sub-title">
Permitted None
</h1>
{{/if}}
</div>
{{/zone}}

View File

@ -1,55 +0,0 @@
/*
* Copyright (c) 2018 - 2023, Entgra (Pvt) Ltd. (http://www.entgra.io) All Rights Reserved.
*
* Entgra (Pvt) Ltd. licenses this file to you under the Apache License,
* Version 2.0 (the "License"); you may not use this file except
* in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
function onRequest(context) {
var constants = require("/app/modules/constants.js");
var userModule = require("/app/modules/business-controllers/user.js")["userModule"];
var devicemgtProps = require("/app/modules/conf-reader/main.js")["conf"];
var deviceModule = require("/app/modules/business-controllers/device.js")["deviceModule"];
var groupModule = require("/app/modules/business-controllers/group.js")["groupModule"];
var policyModule = require("/app/modules/business-controllers/policy.js")["policyModule"];
if(!session.get(constants["TOKEN_PAIR"])){
response.sendRedirect(context.app.context + "/welcome");
return;
}
var user = session.get(constants["USER_SESSION_KEY"]);
var permissions = userModule.getUIPermissions();
if (!permissions.VIEW_DASHBOARD) {
response.sendRedirect(devicemgtProps["appContext"] + "devices");
return;
}
var viewModel = {};
viewModel.permissions = permissions;
viewModel.enrollmentURL = devicemgtProps.enrollmentURL;
viewModel.deviceCount = deviceModule.getDevicesCount();
viewModel.groupCount = groupModule.getGroupCount();
viewModel.userCount = userModule.getUsersCount();
viewModel.policyCount = policyModule.getPoliciesCount();
viewModel.deviceTypeCount = deviceModule.getDeviceTypeCount();
viewModel.isCloud = devicemgtProps.isCloud;
if (devicemgtProps.isCloud) {
viewModel.roleCount = userModule.getFilteredRoles("devicemgt").content.count;
} else {
viewModel.roleCount = userModule.getRolesCount();
}
return viewModel;
}

View File

@ -1,5 +0,0 @@
{
"version": "1.0.0",
"uri": "/",
"layout": "cdmf.layout.default"
}

View File

@ -1,67 +0,0 @@
{{!
Copyright (c) 2016, WSO2 Inc. (http://www.wso2.org) All Rights Reserved.
WSO2 Inc. licenses this file to you under the Apache License,
Version 2.0 (the "License"); you may not use this file except
in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing,
software distributed under the License is distributed on an
"AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
KIND, either express or implied. See the License for the
specific language governing permissions and limitations
under the License.
}}
{{#zone "topCss"}}
{{css "css/analytics.css"}}
{{/zone}}
{{unit "cdmf.unit.ui.title" pageTitle="Analytics"}}
{{unit "cdmf.unit.ui.content.title" pageHeader=title}}
{{unit "cdmf.unit.lib.service-invoker-utility"}}
{{unit "cdmf.unit.lib.handlebars"}}
{{unit "cdmf.unit.lib.rickshaw-graph"}}
{{#zone "breadcrumbs"}}
<li>
<a href="{{@app.context}}/">
<i class="icon fw fw-home"></i>
</a>
</li>
<li>
<a href="{{@app.context}}/devices">
Devices
</a>
</li>
<li>
<a href="{{@app.context}}/device/{{deviceType}}?id={{deviceId}}">
{{deviceName}}
</a>
</li>
<li>
<a href="#">
Analytics
</a>
</li>
{{/zone}}
{{#zone "content"}}
<div class="container container-bg white-bg">
<div class=" margin-top-double">
<div class="row padding-top-double padding-bottom-double margin-bottom-double">
<div class="col-lg-3 margin-top-double">
<h1 class="grey ">{{deviceName}} Analytics</h1>
</div>
{{unit "cdmf.unit.analytics.date-range-picker"}}
</div>
<hr>
<div class="clear"></div>
<div id="div-chart">
{{unit deviceAnalyticsViewUnitName}}
</div>
</div>
</div>
{{/zone}}

View File

@ -1,34 +0,0 @@
/*
* Copyright (c) 2018 - 2023, Entgra (Pvt) Ltd. (http://www.entgra.io) All Rights Reserved.
*
* Entgra (Pvt) Ltd. licenses this file to you under the Apache License,
* Version 2.0 (the "License"); you may not use this file except
* in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
function onRequest(context) {
var utility = require("/app/modules/utility.js").utility;
var deviceType = context.uriParams.deviceType;
var deviceName = request.getParameter("deviceName");
var deviceId = request.getParameter("deviceId");
var unitName = utility.getTenantedDeviceUnitName(deviceType, "analytics-view");
if (!unitName) {
unitName = "cdmf.unit.default.device.type.analytics-view";
}
return {
"deviceAnalyticsViewUnitName": unitName,
"deviceType": deviceType,
"deviceName": deviceName,
"deviceId": deviceId
};
}

View File

@ -1,5 +0,0 @@
{
"version": "1.0.0",
"uri": "/device/{deviceType}/analytics",
"layout": "cdmf.layout.default"
}

View File

@ -1,56 +0,0 @@
/*
* Copyright (c) 2018 - 2023, Entgra (Pvt) Ltd. (http://www.entgra.io) All Rights Reserved.
*
* Entgra (Pvt) Ltd. licenses this file to you under the Apache License,
* Version 2.0 (the "License"); you may not use this file except
* in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
#rangeSliderWrapper {
margin-top: 25px;
}
#chart {
display: inline-block;
}
#legend {
display: inline-block;
position: relative;
left: 8px;
}
#legend_container {
position: absolute;
right: 0;
bottom: 26px;
width: 0;
}
#chart_container {
float: left;
position: relative;
}
.ast-container {
padding-bottom: 30px;
}
.container {
width: auto;
}
.shrink {
margin-right: 20px;
margin-left: 20px;
}

View File

@ -1,66 +0,0 @@
{{!
Copyright (c) 2016, WSO2 Inc. (http://www.wso2.org) All Rights Reserved.
WSO2 Inc. licenses this file to you under the Apache License,
Version 2.0 (the "License"); you may not use this file except
in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing,
software distributed under the License is distributed on an
"AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
KIND, either express or implied. See the License for the
specific language governing permissions and limitations
under the License.
}}
{{unit "cdmf.unit.ui.title" pageTitle="Device Types"}}
{{unit "cdmf.unit.ui.content.title" pageHeader="Device List"}}
{{unit "cdmf.unit.lib.data-table"}}
{{unit "cdmf.unit.lib.handlebars"}}
{{unit "cdmf.unit.lib.service-invoker-utility"}}
{{#zone "breadcrumbs"}}
<li>
<a href="{{@app.context}}/">
<i class="icon fw fw-home"></i>
</a>
</li>
<li>
<a href="{{@app.context}}/devices">
Devices
</a>
</li>
<li>
<a href="{{@app.context}}/device/enroll">
Enroll Device
</a>
</li>
{{/zone}}
{{#zone "navbarActions"}}
{{#if isCloud}}
<li>
<a href="{{contact_form_url}}" class="cu-btn">
<span class="icon fw-stack">
<i class="fw fw-mail fw-stack-1x"></i>
<i class="fw fw-circle-outline fw-stack-2x"></i>
</span>
Request new device type
</a>
</li>
{{/if}}
{{/zone}}
{{#zone "content"}}
<div class="wr-device-list row">
<div class="wr-hidden-operations wr-advance-operations"></div>
<div class="col-md-12 wr-page-content">
<div>
{{unit "cdmf.unit.device.types.listing"}}
</div>
</div>
</div>
{{/zone}}

View File

@ -1,31 +0,0 @@
/*
* Copyright (c) 2018 - 2023, Entgra (Pvt) Ltd. (http://www.entgra.io) All Rights Reserved.
*
* Entgra (Pvt) Ltd. licenses this file to you under the Apache License,
* Version 2.0 (the "License"); you may not use this file except
* in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
/**
* Returns the dynamic state to be populated by device-enrollment page.
*
* @param context Object that gets updated with the dynamic state of this page to be presented
* @returns {*} A context object that returns the dynamic state of this page to be presented
*/
function onRequest(context) {
var devicemgtProps = require("/app/modules/conf-reader/main.js")["conf"];
var page = {};
page["isCloud"] = devicemgtProps.isCloud;
page["contact_form_url"] = "https://cloudmgt.cloud.wso2.com/cloudmgt/site/pages/contact-us.jag?cloud-type=device_cloud&subject=Requesting for a new device type";
return page;
}

View File

@ -1,5 +0,0 @@
{
"version": "1.0.0",
"uri": "/device/enroll",
"layout": "cdmf.layout.default"
}

Some files were not shown because too many files have changed in this diff Show More