Merge pull request #229 from charithag/master

Fix and improve group UI functionality
revert-70aa11f8
sumedharubasinghe 9 years ago
commit 956cc23978

@ -22,14 +22,15 @@ import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory; import org.apache.commons.logging.LogFactory;
import org.wso2.carbon.context.PrivilegedCarbonContext; import org.wso2.carbon.context.PrivilegedCarbonContext;
import org.wso2.carbon.device.mgt.common.DeviceIdentifier; import org.wso2.carbon.device.mgt.common.DeviceIdentifier;
import org.wso2.carbon.device.mgt.common.EnrolmentInfo;
import org.wso2.carbon.device.mgt.common.PaginationResult; import org.wso2.carbon.device.mgt.common.PaginationResult;
import org.wso2.carbon.device.mgt.common.group.mgt.DeviceGroup; import org.wso2.carbon.device.mgt.common.group.mgt.DeviceGroup;
import org.wso2.carbon.device.mgt.common.group.mgt.DeviceGroupConstants;
import org.wso2.carbon.device.mgt.common.group.mgt.GroupAlreadyEixistException; import org.wso2.carbon.device.mgt.common.group.mgt.GroupAlreadyEixistException;
import org.wso2.carbon.device.mgt.common.group.mgt.GroupManagementException; import org.wso2.carbon.device.mgt.common.group.mgt.GroupManagementException;
import org.wso2.carbon.device.mgt.common.group.mgt.GroupUser; import org.wso2.carbon.device.mgt.common.group.mgt.GroupUser;
import org.wso2.carbon.device.mgt.core.service.GroupManagementProviderService; import org.wso2.carbon.device.mgt.core.service.GroupManagementProviderService;
import org.wso2.carbon.device.mgt.jaxrs.api.util.DeviceMgtAPIUtils; import org.wso2.carbon.device.mgt.jaxrs.api.util.DeviceMgtAPIUtils;
import org.wso2.carbon.user.core.multiplecredentials.UserDoesNotExistException;
import javax.ws.rs.Consumes; import javax.ws.rs.Consumes;
import javax.ws.rs.DELETE; import javax.ws.rs.DELETE;
@ -42,26 +43,13 @@ import javax.ws.rs.PathParam;
import javax.ws.rs.Produces; import javax.ws.rs.Produces;
import javax.ws.rs.QueryParam; import javax.ws.rs.QueryParam;
import javax.ws.rs.core.Response; import javax.ws.rs.core.Response;
import java.util.Arrays;
import java.util.Date; import java.util.Date;
import java.util.List; import java.util.List;
@SuppressWarnings("NonJaxWsWebServices") @SuppressWarnings("NonJaxWsWebServices")
public class Group { public class Group {
private static final String DEFAULT_ADMIN_ROLE = "admin";
private static final String DEFAULT_OPERATOR_ROLE = "invoke-device-operations";
private static final String DEFAULT_STATS_MONITOR_ROLE = "view-statistics";
private static final String DEFAULT_VIEW_POLICIES = "view-policies";
private static final String DEFAULT_MANAGE_POLICIES = "mange-policies";
private static final String DEFAULT_VIEW_EVENTS = "view-events";
private static final String[] DEFAULT_ADMIN_PERMISSIONS = {"/permission/device-mgt/admin/groups",
"/permission/device-mgt/user/groups"};
private static final String[] DEFAULT_OPERATOR_PERMISSIONS = {"/permission/device-mgt/user/groups/device_operation"};
private static final String[] DEFAULT_STATS_MONITOR_PERMISSIONS = {"/permission/device-mgt/user/groups/device_monitor"};
private static final String[] DEFAULT_MANAGE_POLICIES_PERMISSIONS = {"/permission/device-mgt/user/groups/device_policies/add"};
private static final String[] DEFAULT_VIEW_POLICIES_PERMISSIONS = {"/permission/device-mgt/user/groups/device_policies/view"};
private static final String[] DEFAULT_VIEW_EVENTS_PERMISSIONS = {"/permission/device-mgt/user/groups/device_events"};
private static Log log = LogFactory.getLog(Group.class); private static Log log = LogFactory.getLog(Group.class);
@POST @POST
@ -76,18 +64,18 @@ public class Group {
group.setDateOfLastUpdate(new Date().getTime()); group.setDateOfLastUpdate(new Date().getTime());
try { try {
GroupManagementProviderService groupManagementService = DeviceMgtAPIUtils.getGroupManagementProviderService(); GroupManagementProviderService groupManagementService = DeviceMgtAPIUtils.getGroupManagementProviderService();
groupManagementService.createGroup(group, DEFAULT_ADMIN_ROLE, DEFAULT_ADMIN_PERMISSIONS); groupManagementService.createGroup(group, DeviceGroupConstants.Roles.DEFAULT_ADMIN_ROLE, DeviceGroupConstants.Permissions.DEFAULT_ADMIN_PERMISSIONS);
groupManagementService.addGroupSharingRole(owner, group.getName(), owner, groupManagementService.addGroupSharingRole(owner, group.getName(), owner,
DEFAULT_OPERATOR_ROLE, DeviceGroupConstants.Roles.DEFAULT_OPERATOR_ROLE,
DEFAULT_OPERATOR_PERMISSIONS); DeviceGroupConstants.Permissions.DEFAULT_OPERATOR_PERMISSIONS);
groupManagementService.addGroupSharingRole(owner, group.getName(), owner, DEFAULT_STATS_MONITOR_ROLE, groupManagementService.addGroupSharingRole(owner, group.getName(), owner, DeviceGroupConstants.Roles.DEFAULT_STATS_MONITOR_ROLE,
DEFAULT_STATS_MONITOR_PERMISSIONS); DeviceGroupConstants.Permissions.DEFAULT_STATS_MONITOR_PERMISSIONS);
groupManagementService.addGroupSharingRole(owner, group.getName(), owner, DEFAULT_VIEW_POLICIES, groupManagementService.addGroupSharingRole(owner, group.getName(), owner, DeviceGroupConstants.Roles.DEFAULT_VIEW_POLICIES,
DEFAULT_VIEW_POLICIES_PERMISSIONS); DeviceGroupConstants.Permissions.DEFAULT_VIEW_POLICIES_PERMISSIONS);
groupManagementService.addGroupSharingRole(owner, group.getName(), owner, DEFAULT_MANAGE_POLICIES, groupManagementService.addGroupSharingRole(owner, group.getName(), owner, DeviceGroupConstants.Roles.DEFAULT_MANAGE_POLICIES,
DEFAULT_MANAGE_POLICIES_PERMISSIONS); DeviceGroupConstants.Permissions.DEFAULT_MANAGE_POLICIES_PERMISSIONS);
groupManagementService.addGroupSharingRole(owner, group.getName(), owner, DEFAULT_VIEW_EVENTS, groupManagementService.addGroupSharingRole(owner, group.getName(), owner, DeviceGroupConstants.Roles.DEFAULT_VIEW_EVENTS,
DEFAULT_VIEW_EVENTS_PERMISSIONS); DeviceGroupConstants.Permissions.DEFAULT_VIEW_EVENTS_PERMISSIONS);
return Response.status(Response.Status.CREATED).build(); return Response.status(Response.Status.CREATED).build();
} catch (GroupAlreadyEixistException e) { } catch (GroupAlreadyEixistException e) {
return Response.status(Response.Status.CONFLICT).entity(e.getMessage()).build(); return Response.status(Response.Status.CONFLICT).entity(e.getMessage()).build();
@ -275,8 +263,10 @@ public class Group {
if (isShared) { if (isShared) {
return Response.status(Response.Status.OK).build(); return Response.status(Response.Status.OK).build();
} else { } else {
return Response.status(Response.Status.NOT_FOUND).build(); return Response.status(Response.Status.NOT_FOUND).entity("Group not found").build();
} }
} catch (UserDoesNotExistException e) {
return Response.status(Response.Status.NOT_FOUND).entity(e.getMessage()).build();
} catch (GroupManagementException e) { } catch (GroupManagementException e) {
log.error(e.getMessage(), e); log.error(e.getMessage(), e);
return Response.status(Response.Status.INTERNAL_SERVER_ERROR).entity(e.getMessage()).build(); return Response.status(Response.Status.INTERNAL_SERVER_ERROR).entity(e.getMessage()).build();
@ -295,8 +285,10 @@ public class Group {
if (isUnShared) { if (isUnShared) {
return Response.status(Response.Status.OK).build(); return Response.status(Response.Status.OK).build();
} else { } else {
return Response.status(Response.Status.NOT_FOUND).build(); return Response.status(Response.Status.NOT_FOUND).entity("Group not found").build();
} }
} catch (UserDoesNotExistException e) {
return Response.status(Response.Status.NOT_FOUND).entity(e.getMessage()).build();
} catch (GroupManagementException e) { } catch (GroupManagementException e) {
log.error(e.getMessage(), e); log.error(e.getMessage(), e);
return Response.status(Response.Status.INTERNAL_SERVER_ERROR).entity(e.getMessage()).build(); return Response.status(Response.Status.INTERNAL_SERVER_ERROR).entity(e.getMessage()).build();
@ -360,6 +352,34 @@ public class Group {
String[] rolesArray = new String[roles.size()]; String[] rolesArray = new String[roles.size()];
roles.toArray(rolesArray); roles.toArray(rolesArray);
return Response.status(Response.Status.OK).entity(rolesArray).build(); return Response.status(Response.Status.OK).entity(rolesArray).build();
} catch (UserDoesNotExistException e) {
return Response.status(Response.Status.NOT_FOUND).entity(e.getMessage()).build();
} catch (GroupManagementException e) {
log.error(e.getMessage(), e);
return Response.status(Response.Status.INTERNAL_SERVER_ERROR).entity(e.getMessage()).build();
}
}
@PUT
@Path("/owner/{owner}/name/{groupName}/user/{userName}/share/roles")
@Produces("application/json")
public Response setRoles(@PathParam("groupName") String groupName,
@PathParam("owner") String owner, @PathParam("userName") String userName,
List<String> selectedRoles) {
try {
List<String> allRoles = DeviceMgtAPIUtils.getGroupManagementProviderService().getRoles(groupName, owner);
for (String role : allRoles) {
if (selectedRoles.contains(role)) {
DeviceMgtAPIUtils.getGroupManagementProviderService()
.shareGroup(userName, groupName, owner, role);
} else {
DeviceMgtAPIUtils.getGroupManagementProviderService()
.unshareGroup(userName, groupName, owner, role);
}
}
return Response.status(Response.Status.OK).build();
} catch (UserDoesNotExistException e) {
return Response.status(Response.Status.NOT_FOUND).entity(e.getMessage()).build();
} catch (GroupManagementException e) { } catch (GroupManagementException e) {
log.error(e.getMessage(), e); log.error(e.getMessage(), e);
return Response.status(Response.Status.INTERNAL_SERVER_ERROR).entity(e.getMessage()).build(); return Response.status(Response.Status.INTERNAL_SERVER_ERROR).entity(e.getMessage()).build();
@ -466,6 +486,8 @@ public class Group {
String[] permissions = DeviceMgtAPIUtils.getGroupManagementProviderService() String[] permissions = DeviceMgtAPIUtils.getGroupManagementProviderService()
.getPermissions(userName, groupName, owner); .getPermissions(userName, groupName, owner);
return Response.status(Response.Status.OK).entity(permissions).build(); return Response.status(Response.Status.OK).entity(permissions).build();
} catch (UserDoesNotExistException e) {
return Response.status(Response.Status.NOT_FOUND).entity(e.getMessage()).build();
} catch (GroupManagementException e) { } catch (GroupManagementException e) {
log.error(e.getMessage(), e); log.error(e.getMessage(), e);
return Response.status(Response.Status.INTERNAL_SERVER_ERROR).entity(e.getMessage()).build(); return Response.status(Response.Status.INTERNAL_SERVER_ERROR).entity(e.getMessage()).build();

@ -1035,6 +1035,13 @@
<method>GET</method> <method>GET</method>
</Permission> </Permission>
<Permission>
<name>Group Roles</name>
<path>/device-mgt/user/groups/roles</path>
<url>/groups/owner/*/name/*/user/*/share/roles</url>
<method>PUT</method>
</Permission>
<Permission> <Permission>
<name>Group Permissions</name> <name>Group Permissions</name>
<path>/device-mgt/admin/groups/roles/permissions</path> <path>/device-mgt/admin/groups/roles/permissions</path>

@ -28,7 +28,6 @@ import java.util.List;
* accessing the device information and performing MDM operations on devices. * accessing the device information and performing MDM operations on devices.
*/ */
public interface DeviceAccessAuthorizationService { public interface DeviceAccessAuthorizationService {
/** /**
* This method will check whether the currently logged-in user has the access to the device identified by the given * This method will check whether the currently logged-in user has the access to the device identified by the given
* DeviceIdentifier. * DeviceIdentifier.
@ -39,18 +38,71 @@ public interface DeviceAccessAuthorizationService {
*/ */
boolean isUserAuthorized(DeviceIdentifier deviceIdentifier) throws DeviceAccessAuthorizationException; boolean isUserAuthorized(DeviceIdentifier deviceIdentifier) throws DeviceAccessAuthorizationException;
/**
* This method will check whether the currently logged-in user has the access to the device identified by the given
* DeviceIdentifier.
*
* @param deviceIdentifier - DeviceIdentifier of the device to be checked.
* @param groupPermissions - Group Permissions.
* @return Boolean authorization result.
* @throws DeviceAccessAuthorizationException if something goes wrong when checking the authorization.
*/
boolean isUserAuthorized(DeviceIdentifier deviceIdentifier, String[] groupPermissions)
throws DeviceAccessAuthorizationException;
/** /**
* This method will check whether the currently logged-in user has the access to the devices identified by the given * This method will check whether the currently logged-in user has the access to the devices identified by the given
* DeviceIdentifier list. * DeviceIdentifier list.
* *
* @param deviceIdentifiers - List of DeviceIdentifiers to be checked for authorization. * @param deviceIdentifiers - List of DeviceIdentifiers to be checked for authorization.
* @return DeviceAuthorizationResult - Authorization result including the list of authorized devices & * @return DeviceAuthorizationResult - Authorization result including the list of authorized devices & unauthorized
* unauthorized devices. * devices.
* @throws DeviceAccessAuthorizationException if something goes wrong when checking the authorization. * @throws DeviceAccessAuthorizationException if something goes wrong when checking the authorization.
*/ */
DeviceAuthorizationResult isUserAuthorized(List<DeviceIdentifier> deviceIdentifiers) throws DeviceAuthorizationResult isUserAuthorized(List<DeviceIdentifier> deviceIdentifiers) throws
DeviceAccessAuthorizationException; DeviceAccessAuthorizationException;
/**
* This method will check whether the currently logged-in user has the access to the devices identified by the given
* DeviceIdentifier list.
*
* @param deviceIdentifiers - List of DeviceIdentifiers to be checked for authorization.
* @param groupPermissions - Group Permissions
* @return DeviceAuthorizationResult - Authorization result including the list of authorized devices & unauthorized
* devices.
* @throws DeviceAccessAuthorizationException if something goes wrong when checking the authorization.
*/
DeviceAuthorizationResult isUserAuthorized(List<DeviceIdentifier> deviceIdentifiers, String[] groupPermissions)
throws DeviceAccessAuthorizationException;
/**
* This method will check whether the given user has the access to the device identified by the given
* DeviceIdentifier.
*
* @param deviceIdentifier - DeviceIdentifier of the device to be checked.
* @param username - Username of the user to be checked for authorization.
* @param groupPermissions - Group Permissions
* @return Boolean authorization result.
* @throws DeviceAccessAuthorizationException if something goes wrong when checking the authorization.
*/
boolean isUserAuthorized(DeviceIdentifier deviceIdentifier, String username, String[] groupPermissions)
throws DeviceAccessAuthorizationException;
/**
* This method will check whether the given user has the access to the devices identified by the given
* DeviceIdentifier list.
*
* @param deviceIdentifiers - List of DeviceIdentifiers to be checked for authorization.
* @param username - User name
* @param groupPermissions - Group Permissions
* @return DeviceAuthorizationResult - Authorization result including the list of authorized devices & unauthorized
* devices.
* @throws DeviceAccessAuthorizationException if something goes wrong when checking the authorization.
*/
DeviceAuthorizationResult isUserAuthorized(List<DeviceIdentifier> deviceIdentifiers, String username,
String[] groupPermissions) throws
DeviceAccessAuthorizationException;
/** /**
* This method will check whether the given user has the access to the device identified by the given * This method will check whether the given user has the access to the device identified by the given
* DeviceIdentifier. * DeviceIdentifier.
@ -69,11 +121,10 @@ public interface DeviceAccessAuthorizationService {
* *
* @param deviceIdentifiers - List of DeviceIdentifiers to be checked for authorization. * @param deviceIdentifiers - List of DeviceIdentifiers to be checked for authorization.
* @param username - Username of the user to be checked for authorization. * @param username - Username of the user to be checked for authorization.
* @return DeviceAuthorizationResult - Authorization result including the list of authorized devices & * @return DeviceAuthorizationResult - Authorization result including the list of authorized devices & unauthorized
* unauthorized devices. * devices.
* @throws DeviceAccessAuthorizationException if something goes wrong when checking the authorization. * @throws DeviceAccessAuthorizationException if something goes wrong when checking the authorization.
*/ */
DeviceAuthorizationResult isUserAuthorized(List<DeviceIdentifier> deviceIdentifiers, String username) throws DeviceAuthorizationResult isUserAuthorized(List<DeviceIdentifier> deviceIdentifiers, String username) throws
DeviceAccessAuthorizationException; DeviceAccessAuthorizationException;
} }

@ -0,0 +1,82 @@
/*
* 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.
*/
package org.wso2.carbon.device.mgt.common.group.mgt;
/**
* Holds Device Group constants and expose to external access
*/
public class DeviceGroupConstants {
public enum RolePermissions {
DEFAULT_ADMIN_ROLE(Roles.DEFAULT_ADMIN_ROLE),
DEFAULT_OPERATOR_ROLE(Roles.DEFAULT_OPERATOR_ROLE),
DEFAULT_STATS_MONITOR_ROLE(Roles.DEFAULT_STATS_MONITOR_ROLE),
DEFAULT_VIEW_POLICIES(Roles.DEFAULT_VIEW_POLICIES),
DEFAULT_MANAGE_POLICIES(Roles.DEFAULT_MANAGE_POLICIES),
DEFAULT_VIEW_EVENTS(Roles.DEFAULT_VIEW_EVENTS);
private String value;
private String[] permissions;
RolePermissions(String value) {
this.value = value;
}
static {
DEFAULT_ADMIN_ROLE.permissions = Permissions.DEFAULT_ADMIN_PERMISSIONS;
DEFAULT_OPERATOR_ROLE.permissions = Permissions.DEFAULT_OPERATOR_PERMISSIONS;
DEFAULT_STATS_MONITOR_ROLE.permissions = Permissions.DEFAULT_STATS_MONITOR_PERMISSIONS;
DEFAULT_VIEW_POLICIES.permissions = Permissions.DEFAULT_MANAGE_POLICIES_PERMISSIONS;
DEFAULT_MANAGE_POLICIES.permissions = Permissions.DEFAULT_VIEW_POLICIES_PERMISSIONS;
DEFAULT_VIEW_EVENTS.permissions = Permissions.DEFAULT_VIEW_EVENTS_PERMISSIONS;
}
@Override
public String toString(){
return this.value;
}
public String[] getPermissions(){
return permissions;
}
}
public static class Roles {
public static final String DEFAULT_ADMIN_ROLE = "admin";
public static final String DEFAULT_OPERATOR_ROLE = "invoke-device-operations";
public static final String DEFAULT_STATS_MONITOR_ROLE = "view-statistics";
public static final String DEFAULT_VIEW_POLICIES = "view-policies";
public static final String DEFAULT_MANAGE_POLICIES = "mange-policies";
public static final String DEFAULT_VIEW_EVENTS = "view-events";
}
public static class Permissions {
public static final String[] DEFAULT_ADMIN_PERMISSIONS =
{"/permission/device-mgt/admin/groups", "/permission/device-mgt/user/groups"};
public static final String[] DEFAULT_OPERATOR_PERMISSIONS =
{"/permission/device-mgt/user/groups/device_operation"};
public static final String[] DEFAULT_STATS_MONITOR_PERMISSIONS =
{"/permission/device-mgt/user/groups/device_monitor"};
public static final String[] DEFAULT_MANAGE_POLICIES_PERMISSIONS =
{"/permission/device-mgt/user/groups/device_policies/add"};
public static final String[] DEFAULT_VIEW_POLICIES_PERMISSIONS =
{"/permission/device-mgt/user/groups/device_policies/view"};
public static final String[] DEFAULT_VIEW_EVENTS_PERMISSIONS =
{"/permission/device-mgt/user/groups/device_events"};
}
}

@ -20,20 +20,26 @@ package org.wso2.carbon.device.mgt.core.authorization;
import org.apache.commons.logging.Log; import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory; import org.apache.commons.logging.LogFactory;
import org.wso2.carbon.CarbonConstants;
import org.wso2.carbon.context.CarbonContext; import org.wso2.carbon.context.CarbonContext;
import org.wso2.carbon.device.mgt.common.*; import org.wso2.carbon.device.mgt.common.Device;
import org.wso2.carbon.device.mgt.common.DeviceIdentifier;
import org.wso2.carbon.device.mgt.common.DeviceManagementException;
import org.wso2.carbon.device.mgt.common.EnrolmentInfo;
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.authorization.DeviceAuthorizationResult; import org.wso2.carbon.device.mgt.common.authorization.DeviceAuthorizationResult;
import org.wso2.carbon.device.mgt.common.group.mgt.DeviceGroup;
import org.wso2.carbon.device.mgt.common.group.mgt.GroupManagementException;
import org.wso2.carbon.device.mgt.common.permission.mgt.Permission; import org.wso2.carbon.device.mgt.common.permission.mgt.Permission;
import org.wso2.carbon.device.mgt.common.permission.mgt.PermissionManagementException; import org.wso2.carbon.device.mgt.common.permission.mgt.PermissionManagementException;
import org.wso2.carbon.device.mgt.core.internal.DeviceManagementDataHolder; import org.wso2.carbon.device.mgt.core.internal.DeviceManagementDataHolder;
import org.wso2.carbon.device.mgt.core.permission.mgt.PermissionUtils; import org.wso2.carbon.device.mgt.core.permission.mgt.PermissionUtils;
import org.wso2.carbon.user.api.UserRealm; import org.wso2.carbon.user.api.UserRealm;
import org.wso2.carbon.user.api.UserStoreException; import org.wso2.carbon.user.api.UserStoreException;
import org.wso2.carbon.user.api.UserStoreManager;
import java.util.HashMap; import java.util.HashMap;
import java.util.Iterator;
import java.util.List; import java.util.List;
import java.util.Map; import java.util.Map;
@ -66,157 +72,173 @@ public class DeviceAccessAuthorizationServiceImpl implements DeviceAccessAuthori
} }
@Override @Override
public boolean isUserAuthorized(DeviceIdentifier deviceIdentifier) throws DeviceAccessAuthorizationException { public boolean isUserAuthorized(DeviceIdentifier deviceIdentifier, String username, String[] groupPermissions)
boolean status; throws DeviceAccessAuthorizationException {
String username = this.getUserName();
int tenantId = this.getTenantId(); int tenantId = this.getTenantId();
if (username == null || username.isEmpty()) { if (username == null || username.isEmpty()) {
return !DeviceManagementDataHolder.getInstance().requireDeviceAuthorization(deviceIdentifier.getType()); return false;
} }
try { //check for admin and ownership permissions
//Check for admin users. If the user is an admin user we authorize the access to that device. if (isAdminOrDeviceOwner(username, tenantId, deviceIdentifier)) {
status = isAdminUser(username, tenantId); return true;
} catch (UserStoreException e) {
throw new DeviceAccessAuthorizationException("Unable to authorize the access to device : " +
deviceIdentifier.getId() + " for the user : " + username, e);
} }
//Check for device ownership. If the user is the owner of the device we allow the access. //check for group permissions
if (!status) {
try { try {
Device device = DeviceManagementDataHolder.getInstance().getDeviceManagementProvider(). if (groupPermissions == null || groupPermissions.length == 0) {
getDevice(deviceIdentifier); return false;
EnrolmentInfo enrolmentInfo = device.getEnrolmentInfo();
if (enrolmentInfo != null && username.equalsIgnoreCase(enrolmentInfo.getOwner())) {
status = true;
} }
} catch (DeviceManagementException e) { for (String groupPermission : groupPermissions) {
if (!checkGroupsPermission(username, tenantId, groupPermission)) {
//if at least one fails, authorization fails
return false;
}
}
return true;
} catch (GroupManagementException | UserStoreException e) {
throw new DeviceAccessAuthorizationException("Unable to authorize the access to device : " + throw new DeviceAccessAuthorizationException("Unable to authorize the access to device : " +
deviceIdentifier.getId() + " for the user : " + username, e); deviceIdentifier.getId() + " for the user : " +
username, e);
} }
} }
return status;
@Override
public boolean isUserAuthorized(DeviceIdentifier deviceIdentifier, String username)
throws DeviceAccessAuthorizationException {
return isUserAuthorized(deviceIdentifier, username, null);
} }
@Override @Override
public DeviceAuthorizationResult isUserAuthorized(List<DeviceIdentifier> deviceIdentifiers) throws public boolean isUserAuthorized(DeviceIdentifier deviceIdentifier, String[] groupPermissions)
DeviceAccessAuthorizationException { throws DeviceAccessAuthorizationException {
boolean status; return isUserAuthorized(deviceIdentifier, this.getUserName(), groupPermissions);
DeviceAuthorizationResult deviceAuthorizationResult = new DeviceAuthorizationResult(); }
String username = this.getUserName();
@Override
public boolean isUserAuthorized(DeviceIdentifier deviceIdentifier) throws DeviceAccessAuthorizationException {
return isUserAuthorized(deviceIdentifier, this.getUserName(), null);
}
@Override
public DeviceAuthorizationResult isUserAuthorized(List<DeviceIdentifier> deviceIdentifiers, String username,
String[] groupPermissions)
throws DeviceAccessAuthorizationException {
int tenantId = this.getTenantId(); int tenantId = this.getTenantId();
if (username == null || username.isEmpty()) { if (username == null || username.isEmpty()) {
return deviceAuthorizationResult; return null;
} }
DeviceAuthorizationResult deviceAuthorizationResult = new DeviceAuthorizationResult();
for (DeviceIdentifier deviceIdentifier : deviceIdentifiers) {
//check for admin and ownership permissions
if (isAdminOrDeviceOwner(username, tenantId, deviceIdentifier)) {
deviceAuthorizationResult.addAuthorizedDevice(deviceIdentifier);
} else {
try { try {
//Check for admin users. If the user is an admin user we authorize the access to that device. if (groupPermissions == null || groupPermissions.length == 0) {
status = isAdminUser(username, tenantId); return null;
} catch (UserStoreException e) {
throw new DeviceAccessAuthorizationException("Unable to authorize the access to devices for the user : " +
username, e);
} }
//Check for device ownership. If the user is the owner of the device we allow the access. //check for group permissions
if (!status) { boolean isAuthorized = true;
try { for (String groupPermission : groupPermissions) {
//Get the list of devices of the user if (!checkGroupsPermission(username, tenantId, groupPermission)) {
List<Device> devicesOfUser = DeviceManagementDataHolder.getInstance().getDeviceManagementProvider(). //if at least one failed, authorizations fails and break the loop
getDevicesOfUser(username); isAuthorized = false;
//Convert device-list to a Map break;
Map<String, String> ownershipData = this.getOwnershipOfDevices(devicesOfUser); }
for (DeviceIdentifier deviceIdentifier : deviceIdentifiers) { }
if (ownershipData.containsKey(deviceIdentifier.getId())) { if (isAuthorized) {
deviceAuthorizationResult.addAuthorizedDevice(deviceIdentifier); deviceAuthorizationResult.addAuthorizedDevice(deviceIdentifier);
} else { } else {
deviceAuthorizationResult.addUnauthorizedDevice(deviceIdentifier); deviceAuthorizationResult.addUnauthorizedDevice(deviceIdentifier);
} }
} catch (GroupManagementException | UserStoreException e) {
throw new DeviceAccessAuthorizationException("Unable to authorize the access to device : " +
deviceIdentifier.getId() + " for the user : " +
username, e);
} }
} catch (DeviceManagementException e) {
throw new DeviceAccessAuthorizationException("Unable to authorize the access to devices for the user : "
+ username, e);
} }
} else {
deviceAuthorizationResult.setAuthorizedDevices(deviceIdentifiers);
} }
return deviceAuthorizationResult; return deviceAuthorizationResult;
} }
@Override @Override
public boolean isUserAuthorized(DeviceIdentifier deviceIdentifier, String username) public DeviceAuthorizationResult isUserAuthorized(List<DeviceIdentifier> deviceIdentifiers, String username)
throws DeviceAccessAuthorizationException { throws DeviceAccessAuthorizationException {
boolean status; return isUserAuthorized(deviceIdentifiers, username, null);
int tenantId = this.getTenantId();
if (username == null || username.isEmpty()) {
return false;
} }
@Override
public DeviceAuthorizationResult isUserAuthorized(List<DeviceIdentifier> deviceIdentifiers)
throws DeviceAccessAuthorizationException {
return isUserAuthorized(deviceIdentifiers, this.getUserName(), null);
}
@Override
public DeviceAuthorizationResult isUserAuthorized(List<DeviceIdentifier> deviceIdentifiers, String[] groupPermissions)
throws DeviceAccessAuthorizationException {
return isUserAuthorized(deviceIdentifiers, this.getUserName(), groupPermissions);
}
private boolean isAdminOrDeviceOwner(String username, int tenantId, DeviceIdentifier deviceIdentifier)
throws DeviceAccessAuthorizationException {
try { try {
//Check for admin users. If the user is an admin user we authorize the access to that device. //First Check for admin users. If the user is an admin user we authorize the access to that device.
status = isAdminUser(username, tenantId); //Secondly Check for device ownership. If the user is the owner of the device we allow the access.
return (isAdminUser(username, tenantId) || isDeviceOwner(deviceIdentifier, username));
} catch (UserStoreException e) { } catch (UserStoreException e) {
throw new DeviceAccessAuthorizationException("Unable to authorize the access to device : " + throw new DeviceAccessAuthorizationException("Unable to authorize the access to device : " +
deviceIdentifier.getId() + " for the user : " + username, e); deviceIdentifier.getId() + " for the user : " +
username, e);
} }
//Check for device ownership. If the user is the owner of the device we allow the access.
if (!status) {
try {
Device device = DeviceManagementDataHolder.getInstance().getDeviceManagementProvider().
getDevice(deviceIdentifier);
EnrolmentInfo enrolmentInfo = device.getEnrolmentInfo();
if (enrolmentInfo != null && username.equalsIgnoreCase(enrolmentInfo.getOwner())) {
status = true;
} }
} catch (DeviceManagementException e) {
throw new DeviceAccessAuthorizationException("Unable to authorize the access to device : " + private boolean checkGroupsPermission(String username, int tenantId, String groupPermission)
deviceIdentifier.getId() + " for the user : " + username, e); throws GroupManagementException, UserStoreException {
List<DeviceGroup> groups =
DeviceManagementDataHolder.getInstance().getGroupManagementProviderService().getGroups(username,
groupPermission);
UserRealm userRealm = DeviceManagementDataHolder.getInstance().getRealmService().getTenantUserRealm(tenantId);
if (userRealm != null && userRealm.getAuthorizationManager() != null) {
Iterator<DeviceGroup> groupIterator = groups.iterator();
while (groupIterator.hasNext()) {
DeviceGroup deviceGroup = groupIterator.next();
Iterator<String> rolesIterator = deviceGroup.getRoles().iterator();
while (rolesIterator.hasNext()) {
String role = rolesIterator.next();
if (userRealm.getAuthorizationManager().isRoleAuthorized(
"Internal/group-" + deviceGroup.getId() + "-" + role, groupPermission,
CarbonConstants.UI_PERMISSION_ACTION)) {
return true;
} }
} }
return status;
} }
@Override
public DeviceAuthorizationResult isUserAuthorized(List<DeviceIdentifier> deviceIdentifiers, String username)
throws DeviceAccessAuthorizationException {
boolean status;
int tenantId = this.getTenantId();
DeviceAuthorizationResult deviceAuthorizationResult = new DeviceAuthorizationResult();
if (username == null || username.isEmpty()) {
return null;
} }
try { return false;
//Check for admin users. If the user is an admin user we authorize the access to that device.
status = isAdminUser(username, tenantId);
} catch (UserStoreException e) {
throw new DeviceAccessAuthorizationException("Unable to authorize the access to devices for the user : " +
username, e);
} }
private boolean isDeviceOwner(DeviceIdentifier deviceIdentifier, String username)
throws DeviceAccessAuthorizationException {
//Check for device ownership. If the user is the owner of the device we allow the access. //Check for device ownership. If the user is the owner of the device we allow the access.
if (!status) {
try { try {
Device device; Device device = DeviceManagementDataHolder.getInstance().getDeviceManagementProvider().
EnrolmentInfo enrolmentInfo;
for (DeviceIdentifier deviceIdentifier : deviceIdentifiers) {
device = DeviceManagementDataHolder.getInstance().getDeviceManagementProvider().
getDevice(deviceIdentifier); getDevice(deviceIdentifier);
enrolmentInfo = device.getEnrolmentInfo(); EnrolmentInfo enrolmentInfo = device.getEnrolmentInfo();
if (enrolmentInfo != null && username.equalsIgnoreCase(enrolmentInfo.getOwner())) { if (enrolmentInfo != null && username.equalsIgnoreCase(enrolmentInfo.getOwner())) {
deviceAuthorizationResult.addAuthorizedDevice(deviceIdentifier); return true;
} else {
deviceAuthorizationResult.addUnauthorizedDevice(deviceIdentifier);
}
} }
} catch (DeviceManagementException e) { } catch (DeviceManagementException e) {
throw new DeviceAccessAuthorizationException("Unable to authorize the access to devices for the user : " throw new DeviceAccessAuthorizationException("Unable to authorize the access to device : " +
+ username, e); deviceIdentifier.getId() + " for the user : " +
} username, e);
} else {
deviceAuthorizationResult.setAuthorizedDevices(deviceIdentifiers);
} }
return deviceAuthorizationResult; return false;
} }
private boolean isAdminUser(String username, int tenantId) throws UserStoreException { private boolean isAdminUser(String username, int tenantId) throws UserStoreException {
UserRealm userRealm = DeviceManagementDataHolder.getInstance().getRealmService().getTenantUserRealm(tenantId); UserRealm userRealm = DeviceManagementDataHolder.getInstance().getRealmService().getTenantUserRealm(tenantId);
if (userRealm != null && userRealm.getAuthorizationManager() != null) { if (userRealm != null && userRealm.getAuthorizationManager() != null) {
return userRealm.getAuthorizationManager() return userRealm.getAuthorizationManager()
.isUserAuthorized(removeTenantDomain(username), PermissionUtils.getAbsolutePermissionPath(EMM_ADMIN_PERMISSION), .isUserAuthorized(removeTenantDomain(username),
PermissionUtils.getAbsolutePermissionPath(EMM_ADMIN_PERMISSION),
PermissionMethod.UI_EXECUTE); PermissionMethod.UI_EXECUTE);
} }
return false; return false;

@ -25,6 +25,7 @@ import org.wso2.carbon.device.mgt.common.operation.mgt.OperationManager;
import org.wso2.carbon.device.mgt.core.app.mgt.config.AppManagementConfig; import org.wso2.carbon.device.mgt.core.app.mgt.config.AppManagementConfig;
import org.wso2.carbon.device.mgt.core.config.license.LicenseConfig; import org.wso2.carbon.device.mgt.core.config.license.LicenseConfig;
import org.wso2.carbon.device.mgt.core.service.DeviceManagementProviderService; import org.wso2.carbon.device.mgt.core.service.DeviceManagementProviderService;
import org.wso2.carbon.device.mgt.core.service.GroupManagementProviderService;
import org.wso2.carbon.ntask.core.service.TaskService; import org.wso2.carbon.ntask.core.service.TaskService;
import org.wso2.carbon.registry.core.service.RegistryService; import org.wso2.carbon.registry.core.service.RegistryService;
import org.wso2.carbon.user.core.service.RealmService; import org.wso2.carbon.user.core.service.RealmService;
@ -47,6 +48,7 @@ public class DeviceManagementDataHolder {
private ConfigurationContextService configurationContextService; private ConfigurationContextService configurationContextService;
private HashMap<String,Boolean> requireDeviceAuthorization = new HashMap<>(); private HashMap<String,Boolean> requireDeviceAuthorization = new HashMap<>();
private DeviceAccessAuthorizationService deviceAccessAuthorizationService; private DeviceAccessAuthorizationService deviceAccessAuthorizationService;
private GroupManagementProviderService groupManagementProviderService;
private TaskService taskService; private TaskService taskService;
//private EmailSenderService emailSenderService; //private EmailSenderService emailSenderService;
@ -91,6 +93,15 @@ public class DeviceManagementDataHolder {
this.deviceManagerProvider = deviceManagerProvider; this.deviceManagerProvider = deviceManagerProvider;
} }
public GroupManagementProviderService getGroupManagementProviderService() {
return groupManagementProviderService;
}
public void setGroupManagementProviderService(
GroupManagementProviderService groupManagementProviderService) {
this.groupManagementProviderService = groupManagementProviderService;
}
public RegistryService getRegistryService() { public RegistryService getRegistryService() {
if (registryService == null) { if (registryService == null) {
throw new IllegalStateException("Registry service is not initialized properly"); throw new IllegalStateException("Registry service is not initialized properly");

@ -195,6 +195,7 @@ public class DeviceManagementServiceComponent {
/* Registering Group Management Service */ /* Registering Group Management Service */
GroupManagementProviderService groupManagementProvider = new GroupManagementProviderServiceImpl(); GroupManagementProviderService groupManagementProvider = new GroupManagementProviderServiceImpl();
DeviceManagementDataHolder.getInstance().setGroupManagementProviderService(groupManagementProvider);
bundleContext.registerService(GroupManagementProviderService.class.getName(), groupManagementProvider, null); bundleContext.registerService(GroupManagementProviderService.class.getName(), groupManagementProvider, null);
/* Registering Tenant Configuration Management Service */ /* Registering Tenant Configuration Management Service */

@ -25,7 +25,7 @@ import org.wso2.carbon.device.mgt.common.group.mgt.DeviceGroup;
import org.wso2.carbon.device.mgt.common.group.mgt.GroupAlreadyEixistException; import org.wso2.carbon.device.mgt.common.group.mgt.GroupAlreadyEixistException;
import org.wso2.carbon.device.mgt.common.group.mgt.GroupManagementException; import org.wso2.carbon.device.mgt.common.group.mgt.GroupManagementException;
import org.wso2.carbon.device.mgt.common.group.mgt.GroupUser; import org.wso2.carbon.device.mgt.common.group.mgt.GroupUser;
import org.wso2.carbon.device.mgt.core.group.mgt.DeviceGroupBuilder; import org.wso2.carbon.user.core.multiplecredentials.UserDoesNotExistException;
import java.util.List; import java.util.List;
@ -77,6 +77,7 @@ public interface GroupManagementProviderService {
/** /**
* Get the device group provided the device group id. * Get the device group provided the device group id.
*
* @param groupId * @param groupId
* @return * @return
* @throws GroupManagementException * @throws GroupManagementException
@ -148,10 +149,10 @@ public interface GroupManagementProviderService {
* @param owner of the group * @param owner of the group
* @param sharingRole to be shared * @param sharingRole to be shared
* @return is group shared * @return is group shared
* @throws GroupManagementException * @throws GroupManagementException UserDoesNotExistException
*/ */
boolean shareGroup(String username, String groupName, String owner, String sharingRole) boolean shareGroup(String username, String groupName, String owner, String sharingRole)
throws GroupManagementException; throws GroupManagementException, UserDoesNotExistException;
/** /**
* Un share existing group sharing with user specified by role * Un share existing group sharing with user specified by role
@ -161,10 +162,10 @@ public interface GroupManagementProviderService {
* @param owner of the group * @param owner of the group
* @param sharingRole to be un shared * @param sharingRole to be un shared
* @return is group un shared * @return is group un shared
* @throws GroupManagementException * @throws GroupManagementException UserDoesNotExistException
*/ */
boolean unshareGroup(String userName, String groupName, String owner, String sharingRole) boolean unshareGroup(String userName, String groupName, String owner, String sharingRole)
throws GroupManagementException; throws GroupManagementException, UserDoesNotExistException;
/** /**
* Add new sharing role for device group * Add new sharing role for device group
@ -208,9 +209,10 @@ public interface GroupManagementProviderService {
* @param groupName of the group * @param groupName of the group
* @param owner of the group * @param owner of the group
* @return list of roles * @return list of roles
* @throws GroupManagementException * @throws GroupManagementException UserDoesNotExistException
*/ */
List<String> getRoles(String userName, String groupName, String owner) throws GroupManagementException; List<String> getRoles(String userName, String groupName, String owner)
throws GroupManagementException, UserDoesNotExistException;
/** /**
* Get device group users * Get device group users
@ -284,9 +286,10 @@ public interface GroupManagementProviderService {
* @param groupName of the group. * @param groupName of the group.
* @param owner of the group. * @param owner of the group.
* @return array of permissions. * @return array of permissions.
* @throws GroupManagementException * @throws GroupManagementException UserDoesNotExistException
*/ */
String[] getPermissions(String username, String groupName, String owner) throws GroupManagementException; String[] getPermissions(String username, String groupName, String owner)
throws GroupManagementException, UserDoesNotExistException;
/** /**
* Get device groups of user with permission. * Get device groups of user with permission.
@ -300,6 +303,7 @@ public interface GroupManagementProviderService {
/** /**
* Get the group of device. * Get the group of device.
*
* @param deviceIdentifier * @param deviceIdentifier
* @return * @return
* @throws GroupManagementException * @throws GroupManagementException

@ -41,6 +41,7 @@ import org.wso2.carbon.user.api.Permission;
import org.wso2.carbon.user.api.UserRealm; import org.wso2.carbon.user.api.UserRealm;
import org.wso2.carbon.user.api.UserStoreException; import org.wso2.carbon.user.api.UserStoreException;
import org.wso2.carbon.user.api.UserStoreManager; import org.wso2.carbon.user.api.UserStoreManager;
import org.wso2.carbon.user.core.multiplecredentials.UserDoesNotExistException;
import org.wso2.carbon.user.core.util.UserCoreUtil; import org.wso2.carbon.user.core.util.UserCoreUtil;
import java.sql.SQLException; import java.sql.SQLException;
@ -379,7 +380,7 @@ public class GroupManagementProviderServiceImpl implements GroupManagementProvid
*/ */
@Override @Override
public boolean shareGroup(String username, String groupName, String owner, String sharingRole) public boolean shareGroup(String username, String groupName, String owner, String sharingRole)
throws GroupManagementException { throws GroupManagementException, UserDoesNotExistException {
int groupId = getGroupId(groupName, owner); int groupId = getGroupId(groupName, owner);
return modifyGroupShare(username, groupId, sharingRole, true); return modifyGroupShare(username, groupId, sharingRole, true);
} }
@ -389,14 +390,14 @@ public class GroupManagementProviderServiceImpl implements GroupManagementProvid
*/ */
@Override @Override
public boolean unshareGroup(String username, String groupName, String owner, String sharingRole) public boolean unshareGroup(String username, String groupName, String owner, String sharingRole)
throws GroupManagementException { throws GroupManagementException, UserDoesNotExistException {
int groupId = getGroupId(groupName, owner); int groupId = getGroupId(groupName, owner);
return modifyGroupShare(username, groupId, sharingRole, false); return modifyGroupShare(username, groupId, sharingRole, false);
} }
private boolean modifyGroupShare(String username, int groupId, String sharingRole, private boolean modifyGroupShare(String username, int groupId, String sharingRole,
boolean isAddNew) boolean isAddNew)
throws GroupManagementException { throws GroupManagementException, UserDoesNotExistException {
if (groupId == -1) { if (groupId == -1) {
return false; return false;
} }
@ -407,14 +408,21 @@ public class GroupManagementProviderServiceImpl implements GroupManagementProvid
userStoreManager = userStoreManager =
DeviceManagementDataHolder.getInstance().getRealmService().getTenantUserRealm( DeviceManagementDataHolder.getInstance().getRealmService().getTenantUserRealm(
tenantId).getUserStoreManager(); tenantId).getUserStoreManager();
if (!userStoreManager.isExistingUser(username)) {
throw new UserDoesNotExistException("User not exists with name " + username);
}
roles[0] = "Internal/group-" + groupId + "-" + sharingRole; roles[0] = "Internal/group-" + groupId + "-" + sharingRole;
if (isAddNew) { List<String> currentRoles = getRoles(username, groupId);
if (isAddNew && !currentRoles.contains(sharingRole)) {
userStoreManager.updateRoleListOfUser(username, null, roles); userStoreManager.updateRoleListOfUser(username, null, roles);
} else { } else if (!isAddNew && currentRoles.contains(sharingRole)) {
userStoreManager.updateRoleListOfUser(username, roles, null); userStoreManager.updateRoleListOfUser(username, roles, null);
} }
return true; return true;
} catch (UserStoreException e) { } catch (UserStoreException e) {
if (e instanceof UserDoesNotExistException) {
throw (UserDoesNotExistException) e;
}
throw new GroupManagementException("User store error in adding user " + username + " to group name:" + throw new GroupManagementException("User store error in adding user " + username + " to group name:" +
groupId, e); groupId, e);
} }
@ -532,18 +540,23 @@ public class GroupManagementProviderServiceImpl implements GroupManagementProvid
* {@inheritDoc} * {@inheritDoc}
*/ */
@Override @Override
public List<String> getRoles(String username, String groupName, String owner) throws GroupManagementException { public List<String> getRoles(String username, String groupName, String owner)
throws GroupManagementException, UserDoesNotExistException {
int groupId = getGroupId(groupName, owner); int groupId = getGroupId(groupName, owner);
return getRoles(username, groupId); return getRoles(username, groupId);
} }
private List<String> getRoles(String username, int groupId) throws GroupManagementException { private List<String> getRoles(String username, int groupId)
throws GroupManagementException, UserDoesNotExistException {
UserStoreManager userStoreManager; UserStoreManager userStoreManager;
List<String> groupRoleList = new ArrayList<>(); List<String> groupRoleList = new ArrayList<>();
try { try {
int tenantId = CarbonContext.getThreadLocalCarbonContext().getTenantId(); int tenantId = CarbonContext.getThreadLocalCarbonContext().getTenantId();
userStoreManager = DeviceManagementDataHolder.getInstance().getRealmService().getTenantUserRealm(tenantId) userStoreManager = DeviceManagementDataHolder.getInstance().getRealmService().getTenantUserRealm(tenantId)
.getUserStoreManager(); .getUserStoreManager();
if (!userStoreManager.isExistingUser(username)) {
throw new UserDoesNotExistException("User not exists with name " + username);
}
String[] roleList = userStoreManager.getRoleListOfUser(username); String[] roleList = userStoreManager.getRoleListOfUser(username);
for (String role : roleList) { for (String role : roleList) {
if (role != null && role.contains("Internal/group-" + groupId)) { if (role != null && role.contains("Internal/group-" + groupId)) {
@ -553,6 +566,9 @@ public class GroupManagementProviderServiceImpl implements GroupManagementProvid
} }
return groupRoleList; return groupRoleList;
} catch (UserStoreException e) { } catch (UserStoreException e) {
if (e instanceof UserDoesNotExistException) {
throw (UserDoesNotExistException) e;
}
throw new GroupManagementException("Error occurred while getting user store manager.", e); throw new GroupManagementException("Error occurred while getting user store manager.", e);
} }
} }
@ -723,7 +739,8 @@ public class GroupManagementProviderServiceImpl implements GroupManagementProvid
* {@inheritDoc} * {@inheritDoc}
*/ */
@Override @Override
public String[] getPermissions(String username, String groupName, String owner) throws GroupManagementException { public String[] getPermissions(String username, String groupName, String owner)
throws GroupManagementException, UserDoesNotExistException {
UserRealm userRealm; UserRealm userRealm;
int groupId = getGroupId(groupName, owner); int groupId = getGroupId(groupName, owner);
List<String> roles = getRoles(username, groupId); List<String> roles = getRoles(username, groupId);

@ -81,8 +81,12 @@
<div class="content"> <div class="content">
<div class="row"> <div class="row">
<div class="col-lg-5 col-md-6 col-centered"> <div class="col-lg-5 col-md-6 col-centered">
<h3>Select user to manage group sharing</h3> <h3>Enter user name to manage group sharing</h3>
<div id="user-names">Loading...</div> <div id="user-names">
<br />
<input type="text" id="share-user-selector" style="color:#3f3f3f;padding:5px;width:250px;">
</input>
</div>
<div class="buttons"> <div class="buttons">
<a href="#" id="share-group-next-link" class="btn-operations"> <a href="#" id="share-group-next-link" class="btn-operations">
&nbsp;&nbsp;&nbsp;&nbsp;Next&nbsp;&nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp;&nbsp;Next&nbsp;&nbsp;&nbsp;&nbsp;
@ -233,6 +237,22 @@
</div> </div>
</div> </div>
<div id="group-404-content" class="hide">
<div class="content">
<div class="row">
<div class="col-lg-5 col-md-6 col-centered">
<h3 id="group-404-message">Not found.</h3>
<div class="buttons">
<a href="#" id="group-404-link" class="btn-operations">
&nbsp;&nbsp;&nbsp;&nbsp;Ok&nbsp;&nbsp;&nbsp;&nbsp;
</a>
</div>
</div>
</div>
</div>
</div>
<div id="group-409-content" class="hide"> <div id="group-409-content" class="hide">
<div class="content"> <div class="content">
<div class="row"> <div class="row">

@ -100,10 +100,10 @@ function loadGroups() {
var currentUser = groupListing.data("currentUser"); var currentUser = groupListing.data("currentUser");
var serviceURL; var serviceURL;
if ($.hasPermission("LIST_ALL_GROUPS")) { if ($.hasPermission("LIST_ALL_GROUPS")) {
serviceURL = "/devicemgt_admin/groups?start=0&rowCount=1000"; serviceURL = "/devicemgt_admin/groups";
} else if ($.hasPermission("LIST_GROUPS")) { } else if ($.hasPermission("LIST_GROUPS")) {
//Get authenticated users groups //Get authenticated users groups
serviceURL = "/devicemgt_admin/groups/user/" + currentUser + "?start=0&rowCount=1000"; serviceURL = "/devicemgt_admin/groups/user/" + currentUser;
} else { } else {
$("#loading-content").remove(); $("#loading-content").remove();
$('#device-table').addClass('hidden'); $('#device-table').addClass('hidden');
@ -133,9 +133,7 @@ function loadGroups() {
{ targets: 0, data: 'id', className: 'remove-padding icon-only content-fill' , render: function ( data, type, row, meta ) { { targets: 0, data: 'id', className: 'remove-padding icon-only content-fill' , render: function ( data, type, row, meta ) {
return '<div class="thumbnail icon"><img class="square-element text fw " src="public/cdmf.page.groups/images/group-icon.png"/></div>'; return '<div class="thumbnail icon"><img class="square-element text fw " src="public/cdmf.page.groups/images/group-icon.png"/></div>';
}}, }},
{ targets: 1, data: 'name', className: 'fade-edge' , render: function ( name, type, row, meta ) { {targets: 1, data: 'name', className: 'fade-edge'},
return '<h4 data-groupid="' + row.id + '">' + name + '</h4>';
}},
{ targets: 2, data: 'owner', className: 'fade-edge remove-padding-top'}, { targets: 2, data: 'owner', className: 'fade-edge remove-padding-top'},
{ targets: 3, data: 'id', className: 'text-right content-fill text-left-on-grid-view no-wrap' , { targets: 3, data: 'id', className: 'text-right content-fill text-left-on-grid-view no-wrap' ,
render: function ( id, type, row, meta ) { render: function ( id, type, row, meta ) {
@ -293,58 +291,23 @@ function attachEvents() {
* on Group Management page in WSO2 Device Management Server Console. * on Group Management page in WSO2 Device Management Server Console.
*/ */
$("a.share-group-link").click(function () { $("a.share-group-link").click(function () {
var username = $("#group-listing").data("current-user");
var groupName = $(this).data("group-name"); var groupName = $(this).data("group-name");
var groupOwner = $(this).data("group-owner"); var groupOwner = $(this).data("group-owner");
$(modalPopupContent).html($('#share-group-w1-modal-content').html()); $(modalPopupContent).html($('#share-group-w1-modal-content').html());
$('#user-names').html('<div style="height:100px" data-state="loading" data-loading-text="Loading..." data-loading-style="icon-only" data-loading-inverse="true"></div>');
showPopup();
$("a#share-group-next-link").hide();
var userRequest = $.ajax(
{
url: "api/user/all",
method: "GET",
contentType: "application/json",
accept: "application/json"
}
);
userRequest.done(function (data, txtStatus, jqxhr) {
var users = JSON.parse(data);
var status = jqxhr.status;
if (status == 200) {
var str = '<br /><select id="share-user-selector" style="color:#3f3f3f;padding:5px;width:250px;">';
var hasUsers = false;
users = users.content;
for (var user in users) {
if (users[user].username != username) {
str += '<option value="' + users[user].username + '">' + users[user].username + '</option>';
hasUsers = true;
}
}
str += '</select>';
if (!hasUsers) {
str = "There is no any other users registered";
$('#user-names').html(str);
return;
}
$('#user-names').html(str);
$("a#share-group-next-link").show(); $("a#share-group-next-link").show();
showPopup();
$("a#share-group-next-link").click(function () { $("a#share-group-next-link").click(function () {
var selectedUser = $('#share-user-selector').val(); var selectedUser = $('#share-user-selector').val();
getAllRoles(groupName, groupOwner, selectedUser); if (selectedUser == $("#group-listing").data("current-user")) {
}); $("#user-names").html("Please specify a user other than current user.");
$("a#share-group-next-link").hide();
} else { } else {
displayErrors(status); getAllRoles(groupName, groupOwner, selectedUser);
} }
}); });
userRequest.fail(function (jqXHR) {
displayErrors(jqXHR);
});
$("a#share-group-w1-cancel-link").click(function () { $("a#share-group-w1-cancel-link").click(function () {
hidePopup(); hidePopup();
}); });
}); });
/** /**
@ -360,22 +323,22 @@ function attachEvents() {
showPopup(); showPopup();
$("a#remove-group-yes-link").click(function () { $("a#remove-group-yes-link").click(function () {
var successCallback = function (data) { var successCallback = function (data, textStatus, xhr) {
data = JSON.parse(data); data = JSON.parse(data);
if (data.status == 200) { if (xhr.status == 200) {
$(modalPopupContent).html($('#remove-group-200-content').html()); $(modalPopupContent).html($('#remove-group-200-content').html());
setTimeout(function () { setTimeout(function () {
hidePopup(); hidePopup();
location.reload(false); location.reload(false);
}, 2000); }, 2000);
} else { } else {
displayErrors(status); displayErrors(xhr);
} }
}; };
invokerUtil.delete("/devicemgt_admin/groups/owner/" + groupOwner + "/name/" + groupName, invokerUtil.delete("/devicemgt_admin/groups/owner/" + groupOwner + "/name/" + groupName,
successCallback, function (message) { successCallback, function (message) {
displayErrors(message.content); displayErrors(message);
}); });
}); });
@ -405,21 +368,21 @@ function attachEvents() {
var newGroupDescription = $('#edit-group-description').val(); var newGroupDescription = $('#edit-group-description').val();
var group = {"name": newGroupName, "description": newGroupDescription, "owner": groupOwner}; var group = {"name": newGroupName, "description": newGroupDescription, "owner": groupOwner};
var successCallback = function (data) { var successCallback = function (data, textStatus, xhr) {
data = JSON.parse(data); data = JSON.parse(data);
if (data.status == 200) { if (xhr.status == 200) {
setTimeout(function () { setTimeout(function () {
hidePopup(); hidePopup();
location.reload(false); location.reload(false);
}, 2000); }, 2000);
} else { } else {
displayErrors(status); displayErrors(xhr);
} }
}; };
invokerUtil.put("/devicemgt_admin/groups/owner/" + groupOwner + "/name/" + groupName, group, invokerUtil.put("/devicemgt_admin/groups/owner/" + groupOwner + "/name/" + groupName, group,
successCallback, function (message) { successCallback, function (message) {
displayErrors(message.content); displayErrors(message);
}); });
}); });
@ -433,22 +396,22 @@ function getAllRoles(groupName, groupOwner, selectedUser) {
$(modalPopupContent).html($('#share-group-w2-modal-content').html()); $(modalPopupContent).html($('#share-group-w2-modal-content').html());
$('#user-roles').html('<div style="height:100px" data-state="loading" data-loading-text="Loading..." data-loading-style="icon-only" data-loading-inverse="true"></div>'); $('#user-roles').html('<div style="height:100px" data-state="loading" data-loading-text="Loading..." data-loading-style="icon-only" data-loading-inverse="true"></div>');
$("a#share-group-yes-link").hide(); $("a#share-group-yes-link").hide();
var successCallback = function (data) { var successCallback = function (data, textStatus, xhr) {
data = JSON.parse(data); data = JSON.parse(data);
if (data.status == 200) { if (xhr.status == 200) {
if (data.data.length > 0) { if (data.length > 0) {
generateRoleMap(groupName, groupOwner, selectedUser, data.data); generateRoleMap(groupName, groupOwner, selectedUser, data);
} else { } else {
$('#user-roles').html("There is no any roles for this group."); $('#user-roles').html("There is no any roles for this group.");
} }
} else { } else {
displayErrors(status); displayErrors(xhr);
} }
}; };
invokerUtil.get("/devicemgt_admin/groups/owner/" + groupOwner + "/name/" + groupName + "/share/roles", invokerUtil.get("/devicemgt_admin/groups/owner/" + groupOwner + "/name/" + groupName + "/share/roles",
successCallback, function (message) { successCallback, function (message) {
displayErrors(message.content); displayErrors(message);
}); });
$("a#share-group-w2-cancel-link").click(function () { $("a#share-group-w2-cancel-link").click(function () {
@ -457,52 +420,44 @@ function getAllRoles(groupName, groupOwner, selectedUser) {
} }
function generateRoleMap(groupName, groupOwner, selectedUser, allRoles) { function generateRoleMap(groupName, groupOwner, selectedUser, allRoles) {
var successCallback = function (data) { var successCallback = function (data, textStatus, xhr) {
data = JSON.parse(data); data = JSON.parse(data);
if (data.status == 200) { if (xhr.status == 200) {
var userRoles = data.data; var userRoles = data;
var roleMap = [];
var str = ''; var str = '';
var isChecked = '';
for (var role in allRoles) { for (var i = 0; i < allRoles.length; i++) {
var objRole = {"role": allRoles[role], "assigned": false}; var isChecked = '';
for (var usrRole in userRoles) { for (var j = 0; j < userRoles.length; j++) {
if (allRoles[role] == userRoles[usrRole]) { if (allRoles[i] == userRoles[j]) {
objRole.assigned = true;
isChecked = 'checked'; isChecked = 'checked';
break; break;
} }
} }
str += '<label class="checkbox-text"><input type="checkbox" id="user-role-' + roleMap[role].role + '" value="' + roleMap[role].role str += '<label class="checkbox-text"><input type="checkbox" id="user-role-' + allRoles[i] + '" value="' + allRoles[i]
+ '" ' + isChecked + '/>' + roleMap[role].role + '</label>&nbsp;&nbsp;&nbsp;&nbsp;'; + '" ' + isChecked + '/>' + allRoles[i] + '</label>&nbsp;&nbsp;&nbsp;&nbsp;';
roleMap.push(objRole);
} }
$('#user-roles').html(str); $('#user-roles').html(str);
$("a#share-group-yes-link").show(); $("a#share-group-yes-link").show();
var isOngoing; $("a#share-group-yes-link").show();
$("a#share-group-yes-link").click(function () { $("a#share-group-yes-link").click(function () {
if (isOngoing) { var roles = [];
return false; for (var i = 0; i < allRoles.length; i++) {
} if ($('#user-role-' + allRoles[i]).is(':checked')) {
$("a#share-group-yes-link").html("Wait..."); roles.push(allRoles[i]);
isOngoing = true;
for (var role in roleMap) {
if ($('#user-role-' + roleMap[role].role).is(':checked') != roleMap[role].assigned) {
roleMap[role].assigned = $('#user-role-' + roleMap[role].role).is(':checked');
updateGroupShare(groupName, groupOwner, selectedUser, roleMap[role]);
} }
} }
updateGroupShare(groupName, groupOwner, selectedUser, roles);
}); });
} else { } else {
displayErrors(status); displayErrors(xhr);
} }
}; };
invokerUtil.get("/devicemgt_admin/groups/owner/" + groupOwner + "/name/" + groupName + "/share/roles?userName=" + selectedUser, invokerUtil.get("/devicemgt_admin/groups/owner/" + groupOwner + "/name/" + groupName + "/share/roles?userName=" + selectedUser,
successCallback, function (message) { successCallback, function (message) {
displayErrors(message.content); displayErrors(message);
}); });
$("a#share-group-w2-cancel-link").click(function () { $("a#share-group-w2-cancel-link").click(function () {
@ -510,24 +465,18 @@ function generateRoleMap(groupName, groupOwner, selectedUser, allRoles) {
}); });
} }
function updateGroupShare(groupName, groupOwner, selectedUser, role) { function updateGroupShare(groupName, groupOwner, selectedUser, roles) {
var successCallback = function (data) { var successCallback = function (data) {
data = JSON.parse(data);
var status = data.status;
if (status == 200) {
$(modalPopupContent).html($('#share-group-200-content').html()); $(modalPopupContent).html($('#share-group-200-content').html());
setTimeout(function () { setTimeout(function () {
hidePopup(); hidePopup();
location.reload(false); location.reload(false);
}, 2000); }, 2000);
} else {
displayErrors(status);
}
}; };
invokerUtil.put("/devicemgt_admin/groups/owner/" + groupOwner + "/name/" + groupName + "/share/roles?userName=" + selectedUser, invokerUtil.put("/devicemgt_admin/groups/owner/" + groupOwner + "/name/" + groupName + "/user/" + selectedUser + "/share/roles",
role, successCallback, function (message) { roles, successCallback, function (message) {
displayErrors(message.content); displayErrors(message);
}); });
} }
@ -543,6 +492,12 @@ function displayErrors(jqXHR) {
$("a#group-403-link").click(function () { $("a#group-403-link").click(function () {
hidePopup(); hidePopup();
}); });
} else if (jqXHR.status == 404) {
$(modalPopupContent).html($('#group-404-content').html());
$("#group-404-message").html(jqXHR.responseText);
$("a#group-404-link").click(function () {
hidePopup();
});
} else if (jqXHR.status == 409) { } else if (jqXHR.status == 409) {
$(modalPopupContent).html($('#group-409-content').html()); $(modalPopupContent).html($('#group-409-content').html());
$("a#group-409-link").click(function () { $("a#group-409-link").click(function () {

@ -50,7 +50,6 @@ var invokerUtil = function () {
accept: acceptType, accept: acceptType,
success: successCallback success: successCallback
}; };
console.log(data);
var paramValue = {}; var paramValue = {};
paramValue.actionMethod = methoad; paramValue.actionMethod = methoad;
paramValue.actionUrl = url; paramValue.actionUrl = url;

@ -8,7 +8,7 @@
"path": "/api/device-api.jag" "path": "/api/device-api.jag"
}, },
{ {
"url": "/api/group/*", "url": "/api/groups/*",
"path": "/api/group-api.jag" "path": "/api/group-api.jag"
}, },
{ {

Loading…
Cancel
Save