Merge pull request #667 from wso2/cloud-3.1.0

Cloud 3.1.0 changes
revert-70aa11f8
Amal Gunatilake 8 years ago committed by GitHub
commit 56b5f82ef8

@ -423,6 +423,83 @@ public interface DeviceManagementService {
@HeaderParam("If-Modified-Since") @HeaderParam("If-Modified-Since")
String ifModifiedSince); String ifModifiedSince);
@GET
@Path("/{type}/{id}/location")
@ApiOperation(
produces = MediaType.APPLICATION_JSON,
httpMethod = "GET",
value = "Getting Location Details of a Device",
notes = "Get the location details of a device by specifying the device type and device identifier.",
tags = "Device Management",
extensions = {
@Extension(properties = {
@ExtensionProperty(name = Constants.SCOPE, value = "perm:devices:details")
})
}
)
@ApiResponses(
value = {
@ApiResponse(
code = 200,
message = "OK. \n Successfully fetched the location details of the device.",
response = Device.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. Empty body because the client already has the latest version" +
" of the requested resource.\n"),
@ApiResponse(
code = 400,
message = "Bad Request. \n Invalid request or validation error.",
response = ErrorResponse.class),
@ApiResponse(
code = 404,
message = "Not Found. \n Location data for the specified device was not found.",
response = ErrorResponse.class),
@ApiResponse(
code = 500,
message = "Internal Server Error. \n " +
"Server error occurred while retrieving the device details.",
response = ErrorResponse.class)
})
Response getDeviceLocation(
@ApiParam(
name = "type",
value = "The device type name, such as ios, android, windows or fire-alarm.",
required = true)
@PathParam("type")
@Size(max = 45)
String type,
@ApiParam(
name = "id",
value = "The device identifier of the device you want ot get details.",
required = true)
@PathParam("id")
@Size(max = 45)
String id,
@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",
required = false)
@HeaderParam("If-Modified-Since")
String ifModifiedSince);
//device rename request would looks like follows //device rename request would looks like follows
//POST devices/type/virtual_firealarm/id/us06ww93auzp/rename //POST devices/type/virtual_firealarm/id/us06ww93auzp/rename
@POST @POST
@ -575,7 +652,7 @@ public interface DeviceManagementService {
produces = MediaType.APPLICATION_JSON, produces = MediaType.APPLICATION_JSON,
httpMethod = "GET", httpMethod = "GET",
value = "Getting Feature Details of a Device", value = "Getting Feature Details of a Device",
notes = "WSO2 EMM features enable you to carry out many operations based on the device platform. " + notes = "WSO2 IoTS features enable you to carry out many operations based on the device platform. " +
"Using this REST API you can get the features that can be carried out on a preferred device type," + "Using this REST API you can get the features that can be carried out on a preferred device type," +
" such as iOS, Android or Windows.", " such as iOS, Android or Windows.",
tags = "Device Management", tags = "Device Management",
@ -644,7 +721,7 @@ public interface DeviceManagementService {
@ApiParam( @ApiParam(
name = "id", name = "id",
value = "The device identifier of the device.\n" + value = "The device identifier of the device.\n" +
"INFO: Make sure to add the ID of a device that is already registered with WSO2 EMM.", "INFO: Make sure to add the ID of a device that is already registered with WSO2 IoTS.",
required = true) required = true)
@PathParam("id") @PathParam("id")
@Size(max = 45) @Size(max = 45)
@ -911,7 +988,7 @@ public interface DeviceManagementService {
@ApiParam( @ApiParam(
name = "id", name = "id",
value = "The device identifier of the device you wish to get details.\n" + value = "The device identifier of the device you wish to get details.\n" +
"INFO: Make sure to add the ID of a device that is already registered with WSO2 EMM.", "INFO: Make sure to add the ID of a device that is already registered with WSO2 IoTS.",
required = true) required = true)
@PathParam("id") @PathParam("id")
@Size(max = 45) @Size(max = 45)
@ -952,8 +1029,8 @@ public interface DeviceManagementService {
produces = MediaType.APPLICATION_JSON, produces = MediaType.APPLICATION_JSON,
httpMethod = "GET", httpMethod = "GET",
value = "Get the details of the policy that is enforced on a device.", value = "Get the details of the policy that is enforced on a device.",
notes = "A policy is enforced on all the devices that register with WSO2 EMM." + notes = "A policy is enforced on all the devices that register with WSO2 IoTS." +
"WSO2 EMM filters the policies based on the device platform (device type)," + "WSO2 IoTS filters the policies based on the device platform (device type)," +
"the device ownership type, the user role or name and finally, the policy that matches these filters will be enforced on the device.", "the device ownership type, the user role or name and finally, the policy that matches these filters will be enforced on the device.",
tags = "Device Management", tags = "Device Management",
extensions = { extensions = {
@ -1041,7 +1118,7 @@ public interface DeviceManagementService {
produces = MediaType.APPLICATION_JSON, produces = MediaType.APPLICATION_JSON,
httpMethod = "GET", httpMethod = "GET",
value = "Getting Policy Compliance Details of a Device", value = "Getting Policy Compliance Details of a Device",
notes = "A policy is enforced on the devices that register with WSO2 EMM. " + notes = "A policy is enforced on the devices that register with WSO2 IoTS. " +
"The server checks if the settings in the device comply with the policy that is enforced on the device using this REST API.", "The server checks if the settings in the device comply with the policy that is enforced on the device using this REST API.",
tags = "Device Management", tags = "Device Management",
extensions = { extensions = {

@ -18,17 +18,7 @@
*/ */
package org.wso2.carbon.device.mgt.jaxrs.service.api; package org.wso2.carbon.device.mgt.jaxrs.service.api;
import io.swagger.annotations.SwaggerDefinition; import io.swagger.annotations.*;
import io.swagger.annotations.Info;
import io.swagger.annotations.ExtensionProperty;
import io.swagger.annotations.Extension;
import io.swagger.annotations.Tag;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;
import io.swagger.annotations.ApiResponse;
import io.swagger.annotations.ApiResponses;
import io.swagger.annotations.ResponseHeader;
import org.wso2.carbon.apimgt.annotations.api.Scope; import org.wso2.carbon.apimgt.annotations.api.Scope;
import org.wso2.carbon.apimgt.annotations.api.Scopes; import org.wso2.carbon.apimgt.annotations.api.Scopes;
import org.wso2.carbon.device.mgt.jaxrs.beans.ErrorResponse; import org.wso2.carbon.device.mgt.jaxrs.beans.ErrorResponse;
@ -120,7 +110,7 @@ public interface RoleManagementService {
produces = MediaType.APPLICATION_JSON, produces = MediaType.APPLICATION_JSON,
httpMethod = "GET", httpMethod = "GET",
value = "Getting the List of Roles", value = "Getting the List of Roles",
notes = "WSO2 EMM supports role-based access control (RBAC) and role management. Using this API you can the list of roles that are in WSO2 EMM.\n" + notes = "WSO2 IoTS supports role-based access control (RBAC) and role management. Using this API you can the list of roles that are in WSO2 IoTS.\n" +
"Note: Internal roles, roles created for service-providers, and application related roles will not be given in the output.", "Note: Internal roles, roles created for service-providers, and application related roles will not be given in the output.",
tags = "Role Management", tags = "Role Management",
extensions = { extensions = {
@ -133,7 +123,7 @@ public interface RoleManagementService {
value = { value = {
@ApiResponse( @ApiResponse(
code = 200, code = 200,
message = "OK. \n Successfully fetched the list of roles in WSO2 EMM.", message = "OK. \n Successfully fetched the list of roles in WSO2 IoTS.",
response = RoleList.class, response = RoleList.class,
responseHeaders = { responseHeaders = {
@ResponseHeader( @ResponseHeader(
@ -190,6 +180,88 @@ public interface RoleManagementService {
defaultValue = "5") defaultValue = "5")
@QueryParam("limit") int limit); @QueryParam("limit") int limit);
@GET
@Path("/filter/{prefix}")
@ApiOperation(
produces = MediaType.APPLICATION_JSON,
httpMethod = "GET",
value = "Getting the List of Roles filtered by the given prefix",
notes = "WSO2 IoTS supports role-based access control (RBAC) and role management. Using this API you can the list of roles that are in WSO2 IoTS.\n" +
"Note: Internal roles, roles created for service-providers, and application related roles will not be given in the output.",
tags = "Role Management",
extensions = {
@Extension(properties = {
@ExtensionProperty(name = Constants.SCOPE, value = "perm:roles:view")
})
}
)
@ApiResponses(
value = {
@ApiResponse(
code = 200,
message = "OK. \n Successfully fetched the list of roles in WSO2 IoTS.",
response = RoleList.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 has been modified the last time.\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."),
@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 list of roles.",
response = ErrorResponse.class)
})
Response getFilteredRoles(
@ApiParam(
name = "prefix",
value = "Filtering prefix of the role.",
required = true,
defaultValue = "")
@PathParam("prefix") String prefix,
@ApiParam(
name = "filter",
value = "Provide a character or a few characters in the role name.",
required = false)
@QueryParam("filter") String filter,
@ApiParam(
name = "user-store",
value = "The name of the UserStore you wish to get the list of roles.",
required = false)
@QueryParam("user-store") String userStoreName,
@ApiParam(
name = "If-Modified-Since",
value = "Checks if the requested variant was modified, since the specified date-time." +
"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",
required = false)
@HeaderParam("If-Modified-Since") String ifModifiedSince,
@ApiParam(
name = "offset",
value = "The starting pagination index for the complete list of qualified items.",
required = false,
defaultValue = "0")
@QueryParam("offset") int offset,
@ApiParam(
name = "limit",
value = "Provide how many role details you require from the starting pagination index/offset.",
required = false,
defaultValue = "5")
@QueryParam("limit") int limit);
@GET @GET
@Path("/{roleName}/permissions") @Path("/{roleName}/permissions")
@ApiOperation( @ApiOperation(
@ -197,7 +269,7 @@ public interface RoleManagementService {
httpMethod = "GET", httpMethod = "GET",
value = "Getting Permission Details of a Role", value = "Getting Permission Details of a Role",
notes = "An individual is associated a with set of responsibilities based on their " + notes = "An individual is associated a with set of responsibilities based on their " +
"role. In WSO2 EMM you are able to configure permissions based on the responsibilities carried " + "role. In WSO2 IoTS you are able to configure permissions based on the responsibilities carried " +
"out by various roles. Therefore, if you wish to retrieve the permission details of a role, you can do " + "out by various roles. Therefore, if you wish to retrieve the permission details of a role, you can do " +
"so using this REST API.", "so using this REST API.",
response = UIPermissionNode.class, response = UIPermissionNode.class,
@ -350,7 +422,7 @@ public interface RoleManagementService {
produces = MediaType.APPLICATION_JSON, produces = MediaType.APPLICATION_JSON,
httpMethod = "POST", httpMethod = "POST",
value = "Adding a Role", value = "Adding a Role",
notes = "WSO2 EMM supports role-based access control (RBAC) and role management. Add a new role to WSO2 EMM using this REST API.", notes = "WSO2 IoTS supports role-based access control (RBAC) and role management. Add a new role to WSO2 IoTS using this REST API.",
tags = "Role Management", tags = "Role Management",
extensions = { extensions = {
@Extension(properties = { @Extension(properties = {
@ -410,7 +482,7 @@ public interface RoleManagementService {
produces = MediaType.APPLICATION_JSON, produces = MediaType.APPLICATION_JSON,
httpMethod = "POST", httpMethod = "POST",
value = "Adding a combined Role", value = "Adding a combined Role",
notes = "WSO2 EMM supports role-based access control (RBAC) and role management. Add a new combined role to WSO2 EMM using this REST API.", notes = "WSO2 IoTS supports role-based access control (RBAC) and role management. Add a new combined role to WSO2 IoTS using this REST API.",
tags = "Role Management", tags = "Role Management",
extensions = { extensions = {
@Extension(properties = { @Extension(properties = {

@ -18,6 +18,7 @@
*/ */
package org.wso2.carbon.device.mgt.jaxrs.service.impl; package org.wso2.carbon.device.mgt.jaxrs.service.impl;
import io.swagger.annotations.ApiParam;
import org.apache.commons.lang.StringUtils; import org.apache.commons.lang.StringUtils;
import org.apache.commons.logging.Log; import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory; import org.apache.commons.logging.LogFactory;
@ -34,6 +35,7 @@ import org.wso2.carbon.device.mgt.common.app.mgt.Application;
import org.wso2.carbon.device.mgt.common.app.mgt.ApplicationManagementException; import org.wso2.carbon.device.mgt.common.app.mgt.ApplicationManagementException;
import org.wso2.carbon.device.mgt.common.authorization.DeviceAccessAuthorizationException; import org.wso2.carbon.device.mgt.common.authorization.DeviceAccessAuthorizationException;
import org.wso2.carbon.device.mgt.common.authorization.DeviceAccessAuthorizationService; import org.wso2.carbon.device.mgt.common.authorization.DeviceAccessAuthorizationService;
import org.wso2.carbon.device.mgt.common.device.details.DeviceLocation;
import org.wso2.carbon.device.mgt.common.operation.mgt.Operation; import org.wso2.carbon.device.mgt.common.operation.mgt.Operation;
import org.wso2.carbon.device.mgt.common.operation.mgt.OperationManagementException; import org.wso2.carbon.device.mgt.common.operation.mgt.OperationManagementException;
import org.wso2.carbon.device.mgt.common.policy.mgt.Policy; import org.wso2.carbon.device.mgt.common.policy.mgt.Policy;
@ -41,6 +43,8 @@ import org.wso2.carbon.device.mgt.common.policy.mgt.monitor.NonComplianceData;
import org.wso2.carbon.device.mgt.common.policy.mgt.monitor.PolicyComplianceException; import org.wso2.carbon.device.mgt.common.policy.mgt.monitor.PolicyComplianceException;
import org.wso2.carbon.device.mgt.common.search.SearchContext; import org.wso2.carbon.device.mgt.common.search.SearchContext;
import org.wso2.carbon.device.mgt.core.app.mgt.ApplicationManagementProviderService; import org.wso2.carbon.device.mgt.core.app.mgt.ApplicationManagementProviderService;
import org.wso2.carbon.device.mgt.core.device.details.mgt.DeviceDetailsMgtException;
import org.wso2.carbon.device.mgt.core.device.details.mgt.DeviceInformationManager;
import org.wso2.carbon.device.mgt.core.search.mgt.SearchManagerService; import org.wso2.carbon.device.mgt.core.search.mgt.SearchManagerService;
import org.wso2.carbon.device.mgt.core.search.mgt.SearchMgtException; import org.wso2.carbon.device.mgt.core.search.mgt.SearchMgtException;
import org.wso2.carbon.device.mgt.core.service.DeviceManagementProviderService; import org.wso2.carbon.device.mgt.core.service.DeviceManagementProviderService;
@ -359,6 +363,32 @@ public class DeviceManagementServiceImpl implements DeviceManagementService {
return Response.status(Response.Status.OK).entity(device).build(); return Response.status(Response.Status.OK).entity(device).build();
} }
@GET
@Path("/{type}/{id}/location")
@Override
public Response getDeviceLocation(
@PathParam("type") @Size(max = 45) String type,
@PathParam("id") @Size(max = 45) String id,
@HeaderParam("If-Modified-Since") String ifModifiedSince) {
DeviceInformationManager informationManager;
DeviceLocation deviceLocation;
try {
DeviceIdentifier deviceIdentifier = new DeviceIdentifier();
deviceIdentifier.setId(id);
deviceIdentifier.setType(type);
informationManager = DeviceMgtAPIUtils.getDeviceInformationManagerService();
deviceLocation = informationManager.getDeviceLocation(deviceIdentifier);
} catch (DeviceDetailsMgtException e) {
String msg = "Error occurred while getting the device location.";
log.error(msg, e);
return Response.serverError().entity(
new ErrorResponse.ErrorResponseBuilder().setMessage(msg).build()).build();
}
return Response.status(Response.Status.OK).entity(deviceLocation).build();
}
@GET @GET
@Path("/{type}/{id}/features") @Path("/{type}/{id}/features")
@Override @Override

@ -30,37 +30,20 @@ import org.wso2.carbon.device.mgt.jaxrs.service.impl.util.FilteringUtil;
import org.wso2.carbon.device.mgt.jaxrs.service.impl.util.RequestValidationUtil; import org.wso2.carbon.device.mgt.jaxrs.service.impl.util.RequestValidationUtil;
import org.wso2.carbon.device.mgt.jaxrs.util.DeviceMgtAPIUtils; import org.wso2.carbon.device.mgt.jaxrs.util.DeviceMgtAPIUtils;
import org.wso2.carbon.device.mgt.jaxrs.util.SetReferenceTransformer; import org.wso2.carbon.device.mgt.jaxrs.util.SetReferenceTransformer;
import org.wso2.carbon.user.api.AuthorizationManager; import org.wso2.carbon.user.api.*;
import org.wso2.carbon.user.api.Permission;
import org.wso2.carbon.user.api.UserRealm;
import org.wso2.carbon.user.api.UserStoreException;
import org.wso2.carbon.user.api.UserStoreManager;
import org.wso2.carbon.user.core.common.AbstractUserStoreManager; import org.wso2.carbon.user.core.common.AbstractUserStoreManager;
import org.wso2.carbon.user.mgt.UserRealmProxy; import org.wso2.carbon.user.mgt.UserRealmProxy;
import org.wso2.carbon.user.mgt.common.UIPermissionNode; import org.wso2.carbon.user.mgt.common.UIPermissionNode;
import org.wso2.carbon.user.mgt.common.UserAdminException; import org.wso2.carbon.user.mgt.common.UserAdminException;
import javax.ws.rs.Consumes; import javax.ws.rs.*;
import javax.ws.rs.DELETE;
import javax.ws.rs.GET;
import javax.ws.rs.HeaderParam;
import javax.ws.rs.POST;
import javax.ws.rs.PUT;
import javax.ws.rs.Path;
import javax.ws.rs.PathParam;
import javax.ws.rs.Produces;
import javax.ws.rs.QueryParam;
import javax.ws.rs.core.MediaType; import javax.ws.rs.core.MediaType;
import javax.ws.rs.core.Response; import javax.ws.rs.core.Response;
import java.io.UnsupportedEncodingException; import java.io.UnsupportedEncodingException;
import java.net.URI; import java.net.URI;
import java.net.URISyntaxException; import java.net.URISyntaxException;
import java.net.URLEncoder; import java.net.URLEncoder;
import java.util.ArrayList; import java.util.*;
import java.util.Arrays;
import java.util.HashSet;
import java.util.List;
import java.util.Set;
import static org.wso2.carbon.device.mgt.jaxrs.util.Constants.PRIMARY_USER_STORE; import static org.wso2.carbon.device.mgt.jaxrs.util.Constants.PRIMARY_USER_STORE;
@ -105,6 +88,48 @@ public class RoleManagementServiceImpl implements RoleManagementService {
} }
} }
@GET
@Path("/filter/{prefix}")
@Override
public Response getFilteredRoles(
@PathParam("prefix") String prefix,
@QueryParam("filter") String filter,
@QueryParam("user-store") String userStore,
@HeaderParam("If-Modified-Since") String ifModifiedSince,
@QueryParam("offset") int offset, @QueryParam("limit") int limit) {
RequestValidationUtil.validatePaginationParameters(offset, limit);
List<String> finalRoleList;
RoleList targetRoles = new RoleList();
//if user store is null set it to primary
if (userStore == null || "".equals(userStore)) {
userStore = PRIMARY_USER_STORE;
}
try {
//Get the total role count that matches the given filter
List<String> filteredRoles = getRolesFromUserStore(filter, userStore);
finalRoleList = new ArrayList<String>();
filteredRoles = FilteringUtil.getFilteredList(getRolesFromUserStore(filter, userStore), offset, limit);
for (String rolename : filteredRoles){
if (rolename.startsWith(prefix)){
finalRoleList.add(rolename);
}
}
targetRoles.setCount(finalRoleList.size());
targetRoles.setList(finalRoleList);
return Response.ok().entity(targetRoles).build();
} catch (UserStoreException e) {
String msg = "Error occurred while retrieving roles from the underlying user stores";
log.error(msg, e);
return Response.serverError().entity(
new ErrorResponse.ErrorResponseBuilder().setMessage(msg).build()).build();
}
}
@GET @GET
@Path("/{roleName}/permissions") @Path("/{roleName}/permissions")
@Override @Override

@ -1,5 +1,5 @@
{ {
"appName": "WSO2 IoT Server", "appName": "WSO2 Device Cloud",
"cachingEnabled": false, "cachingEnabled": false,
"debuggingEnabled": false, "debuggingEnabled": false,
"permissionRoot": "/", "permissionRoot": "/",

@ -98,6 +98,26 @@ deviceModule = function () {
locationTimeData.push(gpsReadingTimes); locationTimeData.push(gpsReadingTimes);
} }
} }
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"]; var utility = require('/app/modules/utility.js')["utility"];
try { try {
utility.startTenantFlow(carbonUser); utility.startTenantFlow(carbonUser);
@ -174,11 +194,26 @@ deviceModule = function () {
} }
if (device["deviceInfo"]) { if (device["deviceInfo"]) {
filteredDeviceData["latestDeviceInfo"] = device["deviceInfo"]; filteredDeviceData["latestDeviceInfo"] = device["deviceInfo"];
}
//location related verification and modifications
// adding the location histry for the movement path.
var locationHistory = {}; var locationHistory = {};
locationHistory.locations = locationData; locationHistory.locations = locationData;
locationHistory.times = locationTimeData; locationHistory.times = locationTimeData;
filteredDeviceData["locationHistory"] = locationHistory; filteredDeviceData["locationHistory"] = locationHistory;
//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;
}
}
}
response["content"] = filteredDeviceData; response["content"] = filteredDeviceData;
response["status"] = "success"; response["status"] = "success";
return response; return response;

@ -302,6 +302,32 @@ var userModule = function () {
} }
}; };
/**
* 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). * Get User Roles count from user store (Internal roles not included).
*/ */

@ -161,6 +161,7 @@ utility = function () {
* @returns {*} * @returns {*}
*/ */
publicMethods.encodeJson = function (text) { publicMethods.encodeJson = function (text) {
if (text) {
return text return text
.replace(/\\u003c/g, "&lt;") .replace(/\\u003c/g, "&lt;")
.replace(/</g, "&lt;") .replace(/</g, "&lt;")
@ -169,7 +170,10 @@ utility = function () {
.replace(/\\u0027/g, "&#39;") .replace(/\\u0027/g, "&#39;")
.replace(/'/g, "&#39;") .replace(/'/g, "&#39;")
.replace(/\\"/g, "&quot;") .replace(/\\"/g, "&quot;")
.replace(/\\u0022/g, "&quot;") .replace(/\\u0022/g, "&quot;");
} else {
return "";
}
}; };
return publicMethods; return publicMethods;

@ -39,8 +39,11 @@ function onRequest() {
viewModel.groupCount = groupModule.getGroupCount(); viewModel.groupCount = groupModule.getGroupCount();
viewModel.userCount = userModule.getUsersCount(); viewModel.userCount = userModule.getUsersCount();
viewModel.policyCount = policyModule.getPoliciesCount(); viewModel.policyCount = policyModule.getPoliciesCount();
viewModel.roleCount = userModule.getRolesCount();
viewModel.isCloud = devicemgtProps.isCloud; viewModel.isCloud = devicemgtProps.isCloud;
if (devicemgtProps.isCloud) {
viewModel.roleCount = userModule.getFilteredRoles("devicemgt").content.count;
} else {
viewModel.roleCount = userModule.getRolesCount();
}
return viewModel; return viewModel;
} }

@ -98,42 +98,22 @@ function loadRoles() {
var dataFilter = function (data) { var dataFilter = function (data) {
data = JSON.parse(data); data = JSON.parse(data);
var objects = []; var objects = [];
var count = 0; var count = 0;
$(data.roles).each(function (index) { $(data.roles).each(function (index) {
if (isCloud && data.roles[index].startsWith("devicemgt")) {
count++;
objects.push(
{
name: htmlspecialchars(data.roles[index]),
DT_RowId: "role-" + htmlspecialchars(data.roles[index])
}
)
} else if (!isCloud) {
objects.push( objects.push(
{ {
name: htmlspecialchars(data.roles[index]), name: htmlspecialchars(data.roles[index]),
DT_RowId: "role-" + htmlspecialchars(data.roles[index]) DT_RowId: "role-" + htmlspecialchars(data.roles[index])
} }
) )
}
}); });
var json = {}; var json = {
if (isCloud) {
json = {
"recordsTotal": count,
"recordsFiltered": count,
"data": objects
};
} else {
json = {
"recordsTotal": data.count, "recordsTotal": data.count,
"recordsFiltered": data.count, "recordsFiltered": data.count,
"data": objects "data": objects
}; };
}
return JSON.stringify(json); return JSON.stringify(json);
}; };
@ -156,7 +136,7 @@ function loadRoles() {
class: "", class: "",
data: "name", data: "name",
render: function (name, type, row, meta) { render: function (name, type, row, meta) {
return '<h4>' + name + '</h4>'; return '<h4>' + name.replace("devicemgt", ""); + '</h4>';
} }
}, },
{ {
@ -225,8 +205,12 @@ function loadRoles() {
var settings = { var settings = {
"sorting": false "sorting": false
}; };
var roleApiUrl = '/api/device-mgt/v1.0/roles?user-store=all';
if (isCloud) {
roleApiUrl = '/api/device-mgt/v1.0/roles/filter/devicemgt?user-store=all';
}
$('#role-grid').datatables_extended_serverside_paging(settings, '/api/device-mgt/v1.0/roles?user-store=all', dataFilter, columns, fnCreatedRow, null, options); $('#role-grid').datatables_extended_serverside_paging(settings, roleApiUrl, dataFilter, columns, fnCreatedRow, null, options);
loadingContent.hide(); loadingContent.hide();
} }

@ -50,6 +50,7 @@
{{/zone}} {{/zone}}
{{#zone "content"}} {{#zone "content"}}
{{#if hasRoles}}
<div id="loading-content" class="col-centered"> <div id="loading-content" class="col-centered">
{{#unless isCloud}} {{#unless isCloud}}
{{#if removePermitted}} {{#if removePermitted}}
@ -89,6 +90,26 @@
<th>By Role name</th> <th>By Role name</th>
</div> </div>
</div> </div>
{{else}}
<div id="user-created-msg" class="container col-centered wr-content">
<div class="wr-form">
<p class="page-sub-title">You Haven't created roles yet.</p>
<br>Please click <b>"Add A New Role"</b>, if you wish to add a role.
<hr/>
<a href="{{@app.context}}/role/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 Role
</a>
</div>
</div>
{{/if}}
{{/zone}} {{/zone}}
{{#zone "bottomJs"}} {{#zone "bottomJs"}}

@ -33,6 +33,16 @@ function onRequest(context) {
context["adminRole"] = deviceMgtProps["adminRole"]; context["adminRole"] = deviceMgtProps["adminRole"];
context["isCloud"] = deviceMgtProps["isCloud"]; context["isCloud"] = deviceMgtProps["isCloud"];
var roleCount = userModule.getRolesCount()
if (deviceMgtProps["isCloud"]) {
roleCount = userModule.getFilteredRoles("devicemgt").content.count;
}
if (roleCount > 0) {
context["hasRoles"] = true;
} else {
context["hasRoles"] = false;
}
return context; return context;
} }

@ -37,6 +37,7 @@
{{#zone "content"}} {{#zone "content"}}
{{#if canView}} {{#if canView}}
{{#if exists}}
{{#zone "contentTitle"}} {{#zone "contentTitle"}}
<div class="row wr-device-board"> <div class="row wr-device-board">
<div class="col-lg-12 wr-secondary-bar"> <div class="col-lg-12 wr-secondary-bar">
@ -96,7 +97,7 @@
<td class="sorting_1" style="padding:10px 15px;">Roles</td> <td class="sorting_1" style="padding:10px 15px;">Roles</td>
<td style="padding:10px 15px;"> <td style="padding:10px 15px;">
{{#each userRoles}} {{#each userRoles}}
<option>{{this}}</option> <option selected="selected">{{this}}</option>
{{/each}} {{/each}}
</td> </td>
</tr> </tr>
@ -172,6 +173,25 @@
{{/defineZone}} {{/defineZone}}
</div> </div>
</div> </div>
{{else}}
<div id="user-created-msg" class="container col-centered wr-content">
<div class="wr-form">
<p class="page-sub-title">User not found.</p>
<br>Please click <b>"Add A New User"</b>, if you wish to add user or click
<b>"View User List"</b> to navigate to the user list.
<hr/>
<button class="wr-btn" onclick="window.location.href='{{@app.context}}/users'">View User List
</button>
<a href="{{@app.context}}/user/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 User
</a>
</div>
</div>
{{/if}}
{{else}} {{else}}
<h1 class="page-sub-title"> <h1 class="page-sub-title">
Permission Denied Permission Denied

@ -21,7 +21,7 @@ function onRequest(context) {
var username = request.getParameter("username"); var username = request.getParameter("username");
var user = userModule.getUser(username)["content"]; var user = userModule.getUser(username)["content"];
var deviceMgtProps = require("/app/modules/conf-reader/main.js")["conf"]; var deviceMgtProps = require("/app/modules/conf-reader/main.js")["conf"];
var isExsistingUser = false;
var userName = request.getParameter("username"); var userName = request.getParameter("username");
var user, userRoles, devices; var user, userRoles, devices;
@ -32,6 +32,7 @@ function onRequest(context) {
if (response["status"] == "success") { if (response["status"] == "success") {
user = response["content"]; user = response["content"];
user.domain = response["userDomain"]; user.domain = response["userDomain"];
isExsistingUser = true;
} }
response = userModule.getRolesByUsername(userName); response = userModule.getRolesByUsername(userName);
@ -49,5 +50,5 @@ function onRequest(context) {
var isCloud = deviceMgtProps.isCloud; var isCloud = deviceMgtProps.isCloud;
return {"user": user, "userRoles": userRoles, "devices": devices, "canView": canView, "isCloud" : isCloud}; return {"exists": isExsistingUser, "user": user, "userRoles": userRoles, "devices": devices, "canView": canView, "isCloud" : isCloud};
} }

Loading…
Cancel
Save