Adding new api to create combined roles

revert-70aa11f8
Rasika Perera 8 years ago
parent 3fe18ba4bb
commit aaade2363c

@ -356,6 +356,70 @@ public interface RoleManagementService {
value = "The properties required to add a new role.",
required = true) RoleInfo role);
@POST
@Path("/create-combined-role/{roleName}")
@ApiOperation(
consumes = MediaType.APPLICATION_JSON,
produces = MediaType.APPLICATION_JSON,
httpMethod = "POST",
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.",
tags = "Role Management",
authorizations = {
@Authorization(
value="permission",
scopes = { @AuthorizationScope(scope = "/device-mgt/roles/manage",
description = "Manage Roles") }
)
}
)
@ApiResponses(value = {
@ApiResponse(
code = 201,
message = "Created. \n Successfully created the role.",
responseHeaders = {
@ResponseHeader(
name = "Content-Location",
description = "The URL to the newly added role."),
@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 = 303,
message = "See Other. \n The source can be retrieved from the URL specified in the location header.",
responseHeaders = {
@ResponseHeader(
name = "Content-Location",
description = "The Source URL of the document.")}),
@ApiResponse(
code = 400,
message = "Bad Request. \n Invalid request or validation error.",
response = ErrorResponse.class),
@ApiResponse(
code = 415,
message = "Unsupported media type. \n The format of the requested entity was not supported.",
response = ErrorResponse.class),
@ApiResponse(
code = 500,
message = "Internal Server Error. \n Server error occurred while adding a new role.",
response = ErrorResponse.class)
})
Response addCombinedRole(
@ApiParam(
name = "roles",
value = "List of roles names required to add a new combined role.",
required = true) List<String> roles,
@PathParam("roleName") String roleName,
@QueryParam("user-store") String userStoreName);
@PUT
@Path("/{roleName}")
@ApiOperation(

@ -30,13 +30,26 @@ 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.util.DeviceMgtAPIUtils;
import org.wso2.carbon.device.mgt.jaxrs.util.SetReferenceTransformer;
import org.wso2.carbon.user.api.*;
import org.wso2.carbon.user.api.AuthorizationManager;
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.mgt.UserRealmProxy;
import org.wso2.carbon.user.mgt.common.UIPermissionNode;
import org.wso2.carbon.user.mgt.common.UserAdminException;
import javax.ws.rs.*;
import javax.ws.rs.Consumes;
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.Response;
import java.io.UnsupportedEncodingException;
@ -45,7 +58,9 @@ import java.net.URISyntaxException;
import java.net.URLEncoder;
import java.util.ArrayList;
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;
@ -94,7 +109,8 @@ public class RoleManagementServiceImpl implements RoleManagementService {
@Path("/{roleName}/permissions")
@Override
public Response getPermissionsOfRole(@PathParam("roleName") String roleName,
@QueryParam("user-store") String userStoreName, @HeaderParam("If-Modified-Since") String ifModifiedSince) {
@QueryParam("user-store") String userStoreName,
@HeaderParam("If-Modified-Since") String ifModifiedSince) {
if (userStoreName != null && !userStoreName.isEmpty()) {
roleName = userStoreName + "/" + roleName;
}
@ -255,6 +271,71 @@ public class RoleManagementServiceImpl implements RoleManagementService {
}
}
@POST
@Path("/create-combined-role/{roleName}")
@Override
public Response addCombinedRole(List<String> roles, @PathParam("roleName") String roleName,
@QueryParam("user-store") String userStoreName) {
if (userStoreName != null && !userStoreName.isEmpty()) {
roleName = userStoreName + "/" + roleName;
}
if (roles.size() < 2) {
return Response.status(400).entity(
new ErrorResponse.ErrorResponseBuilder().setMessage("Combining Roles requires at least two roles.")
.build()
).build();
}
for (String role : roles) {
RequestValidationUtil.validateRoleName(role);
}
try {
UserStoreManager userStoreManager = DeviceMgtAPIUtils.getUserStoreManager();
if (log.isDebugEnabled()) {
log.debug("Persisting the role in the underlying user store");
}
HashSet<Permission> permsSet = new HashSet<>();
try {
for (String role : roles) {
mergePermissions(new UIPermissionNode[]{getRolePermissions(role)}, permsSet);
}
} catch (IllegalArgumentException e) {
return Response.status(404).entity(
new ErrorResponse.ErrorResponseBuilder().setMessage(e.getMessage()).build()
).build();
}
Permission[] permissions = permsSet.toArray(new Permission[permsSet.size()]);
userStoreManager.addRole(roleName, new String[0], permissions);
//TODO fix what's returned in the entity
return Response.created(new URI(API_BASE_PATH + "/" + URLEncoder.encode(roleName, "UTF-8"))).
entity("Role '" + roleName + "' has " + "successfully been"
+ " added").build();
} catch (UserAdminException e) {
String msg = "Error occurred while retrieving the permissions of role '" + roleName + "'";
log.error(msg, e);
return Response.serverError().entity(
new ErrorResponse.ErrorResponseBuilder().setMessage(msg).build()).build();
} catch (UserStoreException e) {
String msg = "Error occurred while adding role '" + roleName + "'";
log.error(msg, e);
return Response.serverError().entity(
new ErrorResponse.ErrorResponseBuilder().setMessage(msg).build()).build();
} catch (URISyntaxException e) {
String msg = "Error occurred while composing the URI at which the information of the newly created role " +
"can be retrieved";
log.error(msg, e);
return Response.serverError().entity(
new ErrorResponse.ErrorResponseBuilder().setMessage(msg).build()).build();
} catch (UnsupportedEncodingException e) {
String msg = "Error occurred while encoding role name";
log.error(msg, e);
return Response.serverError().entity(
new ErrorResponse.ErrorResponseBuilder().setMessage(msg).build()).build();
}
}
@PUT
@Path("/{roleName}")
@Override
@ -376,7 +457,8 @@ public class RoleManagementServiceImpl implements RoleManagementService {
userStoreManager.updateUserListOfRole(roleName, usersToDelete, usersToAdd);
return Response.status(Response.Status.OK).entity("Role '" + roleName + "' has " +
"successfully been updated with the user list").build();
"successfully been updated with the user list")
.build();
} catch (UserStoreException e) {
String msg = "Error occurred while updating the users of the role '" + roleName + "'";
log.error(msg, e);
@ -400,7 +482,8 @@ public class RoleManagementServiceImpl implements RoleManagementService {
// removing all internal roles, roles created for Service-providers and application related roles.
List<String> filteredRoles = new ArrayList<>();
for (String role : roles) {
if (!(role.startsWith("Internal/") || role.startsWith("Authentication/") || role.startsWith("Application/"))) {
if (!(role.startsWith("Internal/") || role.startsWith("Authentication/") || role.startsWith(
"Application/"))) {
if (!filterRolesByName) {
filteredRoles.add(role);
} else {
@ -413,4 +496,31 @@ public class RoleManagementServiceImpl implements RoleManagementService {
return filteredRoles;
}
private Set<Permission> mergePermissions(UIPermissionNode[] permissionNodes, Set<Permission> permissions)
throws UserStoreException, UserAdminException {
for (UIPermissionNode permissionNode : permissionNodes) {
if (permissionNode.getNodeList().length > 0) {
mergePermissions(permissionNode.getNodeList(), permissions);
}
if (permissionNode.isSelected()) {
permissions.add(new Permission(permissionNode.getResourcePath(), CarbonConstants.UI_PERMISSION_ACTION));
}
}
return permissions;
}
private UIPermissionNode getRolePermissions(String roleName) throws UserStoreException, UserAdminException {
final UserRealm userRealm = DeviceMgtAPIUtils.getUserRealm();
if (!userRealm.getUserStoreManager().isExistingRole(roleName)) {
throw new IllegalArgumentException("No role exists with the name '" + roleName + "'");
}
final UIPermissionNode rolePermissions = this.getUIPermissionNode(roleName, userRealm);
if (rolePermissions == null) {
if (log.isDebugEnabled()) {
log.debug("No permissions found for the role '" + roleName + "'");
}
}
return rolePermissions;
}
}

Loading…
Cancel
Save