Merge pull request #395 from Megala21/master

Fixing EMM-1752 and EMM-1755
revert-70aa11f8
Kamidu Sachith Punchihewa 8 years ago committed by GitHub
commit 7666bbfd05

@ -175,7 +175,6 @@
<dependency> <dependency>
<groupId>org.wso2.carbon</groupId> <groupId>org.wso2.carbon</groupId>
<artifactId>org.wso2.carbon.user.core</artifactId> <artifactId>org.wso2.carbon.user.core</artifactId>
<version>4.4.3</version>
</dependency> </dependency>
<dependency> <dependency>
<groupId>org.wso2.carbon.registry</groupId> <groupId>org.wso2.carbon.registry</groupId>

@ -172,6 +172,11 @@ public interface RoleManagementService {
required = true, required = true,
defaultValue = "Engineer") defaultValue = "Engineer")
@PathParam("roleName") String roleName, @PathParam("roleName") String roleName,
@ApiParam(
name = "user-store",
value = "The name of the user store from which you wish to get the permission of role.",
required = false)
@QueryParam("user-store") String userStoreName,
@ApiParam( @ApiParam(
name = "If-Modified-Since", name = "If-Modified-Since",
value = "Checks if the requested variant was modified, since the specified date-time." + value = "Checks if the requested variant was modified, since the specified date-time." +
@ -237,6 +242,11 @@ public interface RoleManagementService {
required = true, required = true,
defaultValue = "admin") defaultValue = "admin")
@PathParam("roleName") String roleName, @PathParam("roleName") String roleName,
@ApiParam(
name = "user-store",
value = "The name of the user store which the particular of role resides in",
required = false)
@QueryParam("user-store") String userStoreName,
@ApiParam( @ApiParam(
name = "If-Modified-Since", name = "If-Modified-Since",
value = "Checks if the requested variant was modified, since the specified date-time." + value = "Checks if the requested variant was modified, since the specified date-time." +
@ -355,7 +365,12 @@ public interface RoleManagementService {
value = "The properties required to update a role.\n" + value = "The properties required to update a role.\n" +
"NOTE: Don't change the role and the permissions of the admin user. " + "NOTE: Don't change the role and the permissions of the admin user. " +
"If you want to try out this API by updating all the properties, create a new role and update the properties accordingly.", "If you want to try out this API by updating all the properties, create a new role and update the properties accordingly.",
required = true) RoleInfo role); required = true) RoleInfo role,
@ApiParam(
name = "user-store",
value = "The name of the user store which the particular role resides in.",
required = false)
@QueryParam("user-store") String userStoreName);
@DELETE @DELETE
@Path("/{roleName}") @Path("/{roleName}")
@ -389,7 +404,12 @@ public interface RoleManagementService {
value = "The name of the role that needs to de deleted.\n" + value = "The name of the role that needs to de deleted.\n" +
"NOTE: Don't delete the admin role", "NOTE: Don't delete the admin role",
required = true) required = true)
@PathParam("roleName") String roleName); @PathParam("roleName") String roleName,
@ApiParam(
name = "user-store",
value = "The name of the user store which the particular role resides in.",
required = false)
@QueryParam("user-store") String userStoreName);
@PUT @PUT
@Path("/{roleName}/users") @Path("/{roleName}/users")
@ -449,6 +469,11 @@ public interface RoleManagementService {
required = true, required = true,
defaultValue = "admin") defaultValue = "admin")
@PathParam("roleName") String roleName, @PathParam("roleName") String roleName,
@ApiParam(
name = "user-store",
value = "The name of the user store which the particular role resides in.",
required = false)
@QueryParam("user-store") String userStoreName,
@ApiParam( @ApiParam(
name = "users", name = "users",
value = "Define the users that belong to the role.\n" + value = "Define the users that belong to the role.\n" +

@ -457,6 +457,11 @@ public interface UserManagementService {
value = "Provide a character or a few character in the user name", value = "Provide a character or a few character in the user name",
required = true) required = true)
@QueryParam("filter") String filter, @QueryParam("filter") String filter,
@ApiParam(
name = "domain",
value = "The user store domain which the user names should be fetched from",
required = false)
@QueryParam("domain") String domain,
@ApiParam( @ApiParam(
name = "If-Modified-Since", name = "If-Modified-Since",
value = "Checks if the requested variant was modified, since the specified date-time\n." + value = "Checks if the requested variant was modified, since the specified date-time\n." +

@ -22,17 +22,13 @@ 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.CarbonConstants;
import org.wso2.carbon.base.MultitenantConstants; import org.wso2.carbon.base.MultitenantConstants;
import org.wso2.carbon.device.mgt.common.scope.mgt.ScopeManagementException;
import org.wso2.carbon.device.mgt.common.scope.mgt.ScopeManagementService;
import org.wso2.carbon.device.mgt.jaxrs.beans.ErrorResponse; import org.wso2.carbon.device.mgt.jaxrs.beans.ErrorResponse;
import org.wso2.carbon.device.mgt.jaxrs.beans.RoleInfo; import org.wso2.carbon.device.mgt.jaxrs.beans.RoleInfo;
import org.wso2.carbon.device.mgt.jaxrs.beans.RoleList; import org.wso2.carbon.device.mgt.jaxrs.beans.RoleList;
import org.wso2.carbon.device.mgt.jaxrs.beans.Scope;
import org.wso2.carbon.device.mgt.jaxrs.service.api.RoleManagementService; import org.wso2.carbon.device.mgt.jaxrs.service.api.RoleManagementService;
import org.wso2.carbon.device.mgt.jaxrs.service.impl.util.FilteringUtil; 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.DeviceMgtUtil;
import org.wso2.carbon.device.mgt.jaxrs.util.SetReferenceTransformer; import org.wso2.carbon.device.mgt.jaxrs.util.SetReferenceTransformer;
import org.wso2.carbon.user.api.*; import org.wso2.carbon.user.api.*;
import org.wso2.carbon.user.core.common.AbstractUserStoreManager; import org.wso2.carbon.user.core.common.AbstractUserStoreManager;
@ -43,12 +39,16 @@ import org.wso2.carbon.user.mgt.common.UserAdminException;
import javax.ws.rs.*; import javax.ws.rs.*;
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.net.URI; import java.net.URI;
import java.net.URISyntaxException; import java.net.URISyntaxException;
import java.net.URLEncoder;
import java.util.ArrayList; import java.util.ArrayList;
import java.util.Arrays; import java.util.Arrays;
import java.util.List; import java.util.List;
import static org.wso2.carbon.device.mgt.jaxrs.util.Constants.PRIMARY_USER_STORE;
@Path("/roles") @Path("/roles")
@Produces(MediaType.APPLICATION_JSON) @Produces(MediaType.APPLICATION_JSON)
@Consumes(MediaType.APPLICATION_JSON) @Consumes(MediaType.APPLICATION_JSON)
@ -56,7 +56,6 @@ public class RoleManagementServiceImpl implements RoleManagementService {
private static final String API_BASE_PATH = "/roles"; private static final String API_BASE_PATH = "/roles";
private static final Log log = LogFactory.getLog(RoleManagementServiceImpl.class); private static final Log log = LogFactory.getLog(RoleManagementServiceImpl.class);
private static final String PRIMARY_USER_STORE = "PRIMARY";
@GET @GET
@Override @Override
@ -94,9 +93,11 @@ public class RoleManagementServiceImpl implements RoleManagementService {
@GET @GET
@Path("/{roleName}/permissions") @Path("/{roleName}/permissions")
@Override @Override
public Response getPermissionsOfRole( public Response getPermissionsOfRole(@PathParam("roleName") String roleName,
@PathParam("roleName") String roleName, @QueryParam("user-store") String userStoreName, @HeaderParam("If-Modified-Since") String ifModifiedSince) {
@HeaderParam("If-Modified-Since") String ifModifiedSince) { if (userStoreName != null && !userStoreName.isEmpty()) {
roleName = userStoreName + "/" + roleName;
}
RequestValidationUtil.validateRoleName(roleName); RequestValidationUtil.validateRoleName(roleName);
try { try {
final UserRealm userRealm = DeviceMgtAPIUtils.getUserRealm(); final UserRealm userRealm = DeviceMgtAPIUtils.getUserRealm();
@ -164,11 +165,14 @@ public class RoleManagementServiceImpl implements RoleManagementService {
@GET @GET
@Path("/{roleName}") @Path("/{roleName}")
@Override @Override
public Response getRole(@PathParam("roleName") String roleName, public Response getRole(@PathParam("roleName") String roleName, @QueryParam("user-store") String userStoreName,
@HeaderParam("If-Modified-Since") String ifModifiedSince) { @HeaderParam("If-Modified-Since") String ifModifiedSince) {
if (log.isDebugEnabled()) { if (log.isDebugEnabled()) {
log.debug("Getting the list of user roles"); log.debug("Getting the list of user roles");
} }
if (userStoreName != null && !userStoreName.isEmpty()) {
roleName = userStoreName + "/" + roleName;
}
RequestValidationUtil.validateRoleName(roleName); RequestValidationUtil.validateRoleName(roleName);
RoleInfo roleInfo = new RoleInfo(); RoleInfo roleInfo = new RoleInfo();
try { try {
@ -229,9 +233,9 @@ public class RoleManagementServiceImpl implements RoleManagementService {
userStoreManager.addRole(roleInfo.getRoleName(), roleInfo.getUsers(), permissions); userStoreManager.addRole(roleInfo.getRoleName(), roleInfo.getUsers(), permissions);
//TODO fix what's returned in the entity //TODO fix what's returned in the entity
return Response.created(new URI(API_BASE_PATH + "/" + roleInfo.getRoleName())).entity( return Response.created(new URI(API_BASE_PATH + "/" + URLEncoder.encode(roleInfo.getRoleName(), "UTF-8"))).
"Role '" + roleInfo.getRoleName() + "' has " + entity("Role '" + roleInfo.getRoleName() + "' has " + "successfully been"
"successfully been added").build(); + " added").build();
} catch (UserStoreException e) { } catch (UserStoreException e) {
String msg = "Error occurred while adding role '" + roleInfo.getRoleName() + "'"; String msg = "Error occurred while adding role '" + roleInfo.getRoleName() + "'";
log.error(msg, e); log.error(msg, e);
@ -243,13 +247,22 @@ public class RoleManagementServiceImpl implements RoleManagementService {
log.error(msg, e); log.error(msg, e);
return Response.serverError().entity( return Response.serverError().entity(
new ErrorResponse.ErrorResponseBuilder().setMessage(msg).build()).build(); 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 @PUT
@Path("/{roleName}") @Path("/{roleName}")
@Override @Override
public Response updateRole(@PathParam("roleName") String roleName, RoleInfo roleInfo) { public Response updateRole(@PathParam("roleName") String roleName, RoleInfo roleInfo,
@QueryParam("user-store") String userStoreName) {
if (userStoreName != null && !userStoreName.isEmpty()) {
roleName = userStoreName + "/" + roleName;
}
RequestValidationUtil.validateRoleName(roleName); RequestValidationUtil.validateRoleName(roleName);
RequestValidationUtil.validateRoleDetails(roleInfo); RequestValidationUtil.validateRoleDetails(roleInfo);
try { try {
@ -306,7 +319,10 @@ public class RoleManagementServiceImpl implements RoleManagementService {
@DELETE @DELETE
@Path("/{roleName}") @Path("/{roleName}")
@Override @Override
public Response deleteRole(@PathParam("roleName") String roleName) { public Response deleteRole(@PathParam("roleName") String roleName, @QueryParam("user-store") String userStoreName) {
if (userStoreName != null && !userStoreName.isEmpty()) {
roleName = userStoreName + "/" + roleName;
}
RequestValidationUtil.validateRoleName(roleName); RequestValidationUtil.validateRoleName(roleName);
try { try {
final UserRealm userRealm = DeviceMgtAPIUtils.getUserRealm(); final UserRealm userRealm = DeviceMgtAPIUtils.getUserRealm();
@ -337,7 +353,11 @@ public class RoleManagementServiceImpl implements RoleManagementService {
@PUT @PUT
@Path("/{roleName}/users") @Path("/{roleName}/users")
@Override @Override
public Response updateUsersOfRole(@PathParam("roleName") String roleName, List<String> users) { public Response updateUsersOfRole(@PathParam("roleName") String roleName,
@QueryParam("user-store") String userStoreName, List<String> users) {
if (userStoreName != null && !userStoreName.isEmpty()) {
roleName = userStoreName + "/" + roleName;
}
RequestValidationUtil.validateRoleName(roleName); RequestValidationUtil.validateRoleName(roleName);
RequestValidationUtil.validateUsers(users); RequestValidationUtil.validateUsers(users);
try { try {
@ -372,7 +392,11 @@ public class RoleManagementServiceImpl implements RoleManagementService {
if (log.isDebugEnabled()) { if (log.isDebugEnabled()) {
log.debug("Getting the list of user roles"); log.debug("Getting the list of user roles");
} }
if (userStore.equals("all")) {
roles = userStoreManager.getRoleNames("*", -1, false, true, true);
} else {
roles = userStoreManager.getRoleNames(userStore + "/*", -1, false, true, true); roles = userStoreManager.getRoleNames(userStore + "/*", -1, false, true, true);
}
// removing all internal roles, roles created for Service-providers and application related roles. // removing all internal roles, roles created for Service-providers and application related roles.
List<String> filteredRoles = new ArrayList<>(); List<String> filteredRoles = new ArrayList<>();
for (String role : roles) { for (String role : roles) {

@ -21,6 +21,7 @@ package org.wso2.carbon.device.mgt.jaxrs.service.impl;
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;
import org.eclipse.wst.common.uriresolver.internal.util.URIEncoder;
import org.wso2.carbon.device.mgt.common.DeviceManagementException; import org.wso2.carbon.device.mgt.common.DeviceManagementException;
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.EmailMetaInfo; import org.wso2.carbon.device.mgt.core.service.EmailMetaInfo;
@ -36,6 +37,7 @@ import org.wso2.carbon.user.api.UserStoreManager;
import javax.ws.rs.*; import javax.ws.rs.*;
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.net.URI; import java.net.URI;
import java.net.URISyntaxException; import java.net.URISyntaxException;
import java.security.SecureRandom; import java.security.SecureRandom;
@ -85,7 +87,8 @@ public class UserManagementServiceImpl implements UserManagementService {
if (log.isDebugEnabled()) { if (log.isDebugEnabled()) {
log.debug("User by username: " + userInfo.getUsername() + " was found."); log.debug("User by username: " + userInfo.getUsername() + " was found.");
} }
return Response.created(new URI(API_BASE_PATH + "/" + userInfo.getUsername())).entity( return Response.created(new URI(API_BASE_PATH + "/" + URIEncoder.encode(userInfo.getUsername(), "UTF-8")))
.entity(
createdUserInfo).build(); createdUserInfo).build();
} catch (UserStoreException e) { } catch (UserStoreException e) {
String msg = "Error occurred while trying to add user '" + userInfo.getUsername() + "' to the " + String msg = "Error occurred while trying to add user '" + userInfo.getUsername() + "' to the " +
@ -99,6 +102,12 @@ public class UserManagementServiceImpl implements UserManagementService {
log.error(msg, e); log.error(msg, e);
return Response.serverError().entity( return Response.serverError().entity(
new ErrorResponse.ErrorResponseBuilder().setMessage(msg).build()).build(); new ErrorResponse.ErrorResponseBuilder().setMessage(msg).build()).build();
} catch (UnsupportedEncodingException e) {
String msg = "Error occurred while encoding username in the URI for the newly created user " +
userInfo.getUsername();
log.error(msg, e);
return Response.serverError().entity(
new ErrorResponse.ErrorResponseBuilder().setMessage(msg).build()).build();
} }
} }
@ -353,18 +362,24 @@ public class UserManagementServiceImpl implements UserManagementService {
@GET @GET
@Path("/search/usernames") @Path("/search/usernames")
@Override @Override
public Response getUserNames(@QueryParam("filter") String filter, @HeaderParam("If-Modified-Since") String timestamp, public Response getUserNames(@QueryParam("filter") String filter, @QueryParam("domain") String domain,
@HeaderParam("If-Modified-Since") String timestamp,
@QueryParam("offset") int offset, @QueryParam("limit") int limit) { @QueryParam("offset") int offset, @QueryParam("limit") int limit) {
if (log.isDebugEnabled()) { if (log.isDebugEnabled()) {
log.debug("Getting the list of users with all user-related information using the filter : " + filter); log.debug("Getting the list of users with all user-related information using the filter : " + filter);
} }
String userStoreDomain = Constants.PRIMARY_USER_STORE;
if (domain != null && !domain.isEmpty()) {
userStoreDomain = domain;
}
List<UserInfo> userList; List<UserInfo> userList;
try { try {
UserStoreManager userStoreManager = DeviceMgtAPIUtils.getUserStoreManager(); UserStoreManager userStoreManager = DeviceMgtAPIUtils.getUserStoreManager();
String[] users = userStoreManager.listUsers(filter + "*", -1); String[] users = userStoreManager.listUsers(userStoreDomain + "/*", -1);
userList = new ArrayList<>(users.length); userList = new ArrayList<>();
UserInfo user; UserInfo user;
for (String username : users) { for (String username : users) {
if (username.contains(filter)) {
user = new UserInfo(); user = new UserInfo();
user.setUsername(username); user.setUsername(username);
user.setEmailAddress(getClaimValue(username, Constants.USER_CLAIM_EMAIL_ADDRESS)); user.setEmailAddress(getClaimValue(username, Constants.USER_CLAIM_EMAIL_ADDRESS));
@ -372,9 +387,7 @@ public class UserManagementServiceImpl implements UserManagementService {
user.setLastname(getClaimValue(username, Constants.USER_CLAIM_LAST_NAME)); user.setLastname(getClaimValue(username, Constants.USER_CLAIM_LAST_NAME));
userList.add(user); userList.add(user);
} }
// if (userList.size() <= 0) { }
// return Response.status(Response.Status.NOT_FOUND).entity("No user is available to be retrieved").build();
// }
return Response.status(Response.Status.OK).entity(userList).build(); return Response.status(Response.Status.OK).entity(userList).build();
} catch (UserStoreException e) { } catch (UserStoreException e) {
String msg = "Error occurred while retrieving the list of users using the filter : " + filter; String msg = "Error occurred while retrieving the list of users using the filter : " + filter;

@ -26,6 +26,7 @@ public class Constants {
public static final String USER_CLAIM_EMAIL_ADDRESS = "http://wso2.org/claims/emailaddress"; public static final String USER_CLAIM_EMAIL_ADDRESS = "http://wso2.org/claims/emailaddress";
public static final String USER_CLAIM_FIRST_NAME = "http://wso2.org/claims/givenname"; public static final String USER_CLAIM_FIRST_NAME = "http://wso2.org/claims/givenname";
public static final String USER_CLAIM_LAST_NAME = "http://wso2.org/claims/lastname"; public static final String USER_CLAIM_LAST_NAME = "http://wso2.org/claims/lastname";
public static final String PRIMARY_USER_STORE = "PRIMARY";
public final class ErrorMessages { public final class ErrorMessages {
private ErrorMessages () { throw new AssertionError(); } private ErrorMessages () { throw new AssertionError(); }

@ -187,7 +187,7 @@ var userModule = function () {
var url = devicemgtProps["httpsURL"] + devicemgtProps["backendRestEndpoints"]["deviceMgt"] + "/users/" + var url = devicemgtProps["httpsURL"] + devicemgtProps["backendRestEndpoints"]["deviceMgt"] + "/users/" +
encodeURIComponent(username); encodeURIComponent(username);
if (domain) { if (domain) {
url += '?domain=' + domain; url += '?domain=' + encodeURIComponent(domain);
} }
var response = privateMethods.callBackend(url, constants["HTTP_GET"]); var response = privateMethods.callBackend(url, constants["HTTP_GET"]);
response["content"] = parse(response.content); response["content"] = parse(response.content);
@ -217,7 +217,7 @@ var userModule = function () {
var url = devicemgtProps["httpsURL"] + devicemgtProps["backendRestEndpoints"]["deviceMgt"] + "/users/" + var url = devicemgtProps["httpsURL"] + devicemgtProps["backendRestEndpoints"]["deviceMgt"] + "/users/" +
encodeURIComponent(username) + "/roles"; encodeURIComponent(username) + "/roles";
if (domain) { if (domain) {
url += '?domain=' + domain; url += '?domain=' + encodeURIComponent(domain);
} }
var response = privateMethods.callBackend(url, constants["HTTP_GET"]); var response = privateMethods.callBackend(url, constants["HTTP_GET"]);
if (response.status == "success") { if (response.status == "success") {
@ -268,7 +268,7 @@ var userModule = function () {
try { try {
utility.startTenantFlow(carbonUser); utility.startTenantFlow(carbonUser);
var url = devicemgtProps["httpsURL"] + devicemgtProps["backendRestEndpoints"]["deviceMgt"] + var url = devicemgtProps["httpsURL"] + devicemgtProps["backendRestEndpoints"]["deviceMgt"] +
"/roles?offset=0&limit=100"; "/roles?offset=0&limit=100&user-store=all";
var response = privateMethods.callBackend(url, constants["HTTP_GET"]); var response = privateMethods.callBackend(url, constants["HTTP_GET"]);
if (response.status == "success") { if (response.status == "success") {
response.content = parse(response.content).roles; response.content = parse(response.content).roles;
@ -294,7 +294,7 @@ var userModule = function () {
try { try {
utility.startTenantFlow(carbonUser); utility.startTenantFlow(carbonUser);
var url = devicemgtProps["httpsURL"] + devicemgtProps["backendRestEndpoints"]["deviceMgt"] + var url = devicemgtProps["httpsURL"] + devicemgtProps["backendRestEndpoints"]["deviceMgt"] +
"/roles?offset=0&limit=1"; "/roles?offset=0&limit=1&user-store=all";
return serviceInvokers.XMLHttp.get( return serviceInvokers.XMLHttp.get(
url, function (responsePayload) { url, function (responsePayload) {
return parse(responsePayload["responseText"])["count"]; return parse(responsePayload["responseText"])["count"];
@ -328,7 +328,7 @@ var userModule = function () {
try { try {
utility.startTenantFlow(carbonUser); utility.startTenantFlow(carbonUser);
var url = devicemgtProps["httpsURL"] + devicemgtProps["backendRestEndpoints"]["deviceMgt"] + var url = devicemgtProps["httpsURL"] + devicemgtProps["backendRestEndpoints"]["deviceMgt"] +
"/roles?user-store=" + userStore + "&limit=100"; "/roles?user-store=" + encodeURIComponent(userStore) + "&limit=100";
var response = privateMethods.callBackend(url, constants["HTTP_GET"]); var response = privateMethods.callBackend(url, constants["HTTP_GET"]);
if (response.status == "success") { if (response.status == "success") {
response.content = parse(response.content).roles; response.content = parse(response.content).roles;
@ -374,14 +374,22 @@ var userModule = function () {
publicMethods.getRole = function (roleName) { publicMethods.getRole = function (roleName) {
var carbonUser = session.get(constants["USER_SESSION_KEY"]); var carbonUser = session.get(constants["USER_SESSION_KEY"]);
var utility = require("/app/modules/utility.js")["utility"]; var utility = require("/app/modules/utility.js")["utility"];
var userStore;
if (!carbonUser) { if (!carbonUser) {
log.error("User object was not found in the session"); log.error("User object was not found in the session");
throw constants["ERRORS"]["USER_NOT_FOUND"]; throw constants["ERRORS"]["USER_NOT_FOUND"];
} }
try { try {
utility.startTenantFlow(carbonUser); utility.startTenantFlow(carbonUser);
if (roleName.indexOf('/') > 0) {
userStore = roleName.substr(0, roleName.indexOf('/'));
roleName = roleName.substr(roleName.indexOf('/') + 1);
}
var url = devicemgtProps["httpsURL"] + devicemgtProps["backendRestEndpoints"]["deviceMgt"] + var url = devicemgtProps["httpsURL"] + devicemgtProps["backendRestEndpoints"]["deviceMgt"] +
"/roles/" + encodeURIComponent(roleName); "/roles/" + encodeURIComponent(roleName);
if (userStore) {
url += "?user-store=" + encodeURIComponent(userStore);
}
var response = privateMethods.callBackend(url, constants["HTTP_GET"]); var response = privateMethods.callBackend(url, constants["HTTP_GET"]);
if (response.status == "success") { if (response.status == "success") {
response.content = parse(response.content); response.content = parse(response.content);

@ -94,7 +94,8 @@
data-error-msg="{{roleNameRegExViolationErrorMsg}}" class="form-control" /> data-error-msg="{{roleNameRegExViolationErrorMsg}}" class="form-control" />
<span class="roleNameError hidden glyphicon glyphicon-remove form-control-feedback"></span> <span class="roleNameError hidden glyphicon glyphicon-remove form-control-feedback"></span>
<label class="error roleNameEmpty hidden" for="summary"> <label class="error roleNameEmpty hidden" for="summary">
Role name is required, should be in minimum 3 characters long and not include any whitespaces. Role name is required, should be in minimum 3 characters long and not include any
whitespaces or "@" character or "/" character.
</label> </label>
</div> </div>
{{#if canViewUsers}} {{#if canViewUsers}}

@ -32,6 +32,7 @@ var validateInline = {};
var clearInline = {}; var clearInline = {};
var apiBasePath = "/api/device-mgt/v1.0"; var apiBasePath = "/api/device-mgt/v1.0";
var domain = $("#domain").val();
var enableInlineError = function (inputField, errorMsg, errorSign) { var enableInlineError = function (inputField, errorMsg, errorSign) {
var fieldIdentifier = "#" + inputField; var fieldIdentifier = "#" + inputField;
@ -82,7 +83,8 @@ clearInline["role-name"] = function () {
*/ */
validateInline["role-name"] = function () { validateInline["role-name"] = function () {
var roleNameInput = $("input#roleName"); var roleNameInput = $("input#roleName");
if (inputIsValid( roleNameInput.data("regex"), roleNameInput.val())) { var roleName = roleNameInput.val();
if (inputIsValid( roleNameInput.data("regex"), roleName) && roleName.indexOf("@") < 0 && roleName.indexOf("/") < 0) {
disableInlineError("roleNameField", "roleNameEmpty", "roleNameError"); disableInlineError("roleNameField", "roleNameEmpty", "roleNameError");
} else { } else {
enableInlineError("roleNameField", "roleNameEmpty", "roleNameError"); enableInlineError("roleNameField", "roleNameEmpty", "roleNameError");
@ -127,7 +129,8 @@ $(document).ready(function () {
data: function (params) { data: function (params) {
var postData = {}; var postData = {};
postData.requestMethod = "GET"; postData.requestMethod = "GET";
postData.requestURL = "/api/device-mgt/v1.0/users/search/usernames?filter=" + params.term; postData.requestURL = "/api/device-mgt/v1.0/users/search/usernames?filter=" + params.term +
"&domain=" + encodeURIComponent(domain);
postData.requestPayload = null; postData.requestPayload = null;
return JSON.stringify(postData); return JSON.stringify(postData);
}, },
@ -170,7 +173,8 @@ $(document).ready(function () {
if (!roleName) { if (!roleName) {
$(errorMsg).text("Role name is a required field. It cannot be empty."); $(errorMsg).text("Role name is a required field. It cannot be empty.");
$(errorMsgWrapper).removeClass("hidden"); $(errorMsgWrapper).removeClass("hidden");
} else if (!inputIsValid(roleNameInput.data("regex"), roleName)) { } else if (!inputIsValid(roleNameInput.data("regex"), roleName) || roleName.indexOf("@") >= 0 ||
roleName.indexOf("/") >= 0) {
$(errorMsg).text(roleNameInput.data("error-msg")); $(errorMsg).text(roleNameInput.data("error-msg"));
$(errorMsgWrapper).removeClass("hidden"); $(errorMsgWrapper).removeClass("hidden");
} else if (!domain) { } else if (!domain) {
@ -201,7 +205,8 @@ $(document).ready(function () {
$("input#roleName").val(""); $("input#roleName").val("");
$("#domain").val("PRIMARY"); $("#domain").val("PRIMARY");
$("#users").val(""); $("#users").val("");
window.location.href = appContext + "/role/edit-permission/" + roleName; window.location.href = appContext + "/role/edit-permission/?rolename=" +
encodeURIComponent(addRoleFormData.roleName);
} }
}, },
function (jqXHR) { function (jqXHR) {
@ -222,4 +227,12 @@ $(document).ready(function () {
$(roleNameInputElement).blur(function() { $(roleNameInputElement).blur(function() {
validateInline["role-name"](); validateInline["role-name"]();
}); });
/* When the user store domain value is changed, the users who are assigned to that role should be removed, as
user and role can be mapped only if both are in same user store
*/
$("#domain").change(function () {
$("#users").select2("val", "");
domain = $("#domain").val();
});
}); });

@ -1,5 +1,5 @@
{ {
"version": "1.0.0", "version": "1.0.0",
"uri": "/role/edit-permission/{+any}", "uri": "/role/edit-permission/",
"layout": "cdmf.layout.default" "layout": "cdmf.layout.default"
} }

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

@ -17,7 +17,7 @@
*/ */
var loadRoleBasedActionURL = function (action, rolename) { var loadRoleBasedActionURL = function (action, rolename) {
var href = $("#ast-container").data("app-context") + "role/" + action + "/" + rolename; href = $("#ast-container").data("app-context") + "role/" + action + "/?rolename=" + encodeURIComponent(rolename);
$(location).attr('href', href); $(location).attr('href', href);
}; };
@ -188,7 +188,7 @@ function loadRoles() {
"sorting": false "sorting": false
}; };
$('#role-grid').datatables_extended_serverside_paging(settings, '/api/device-mgt/v1.0/roles', dataFilter, columns, fnCreatedRow, null, options); $('#role-grid').datatables_extended_serverside_paging(settings, '/api/device-mgt/v1.0/roles?user-store=all', dataFilter, columns, fnCreatedRow, null, options);
loadingContent.hide(); loadingContent.hide();
} }
@ -201,8 +201,15 @@ function loadRoles() {
*/ */
$("#role-grid").on("click", ".remove-role-link", function () { $("#role-grid").on("click", ".remove-role-link", function () {
var role = $(this).data("role"); var role = $(this).data("role");
var removeRoleAPI = apiBasePath + "/roles/" + role; var userStore;
if (role.indexOf('/') > 0) {
userStore = role.substr(0, role.indexOf('/'));
role = role.substr(role.indexOf('/') + 1);
}
var removeRoleAPI = apiBasePath + "/roles/" + encodeURIComponent(role);
if (userStore) {
removeRoleAPI += "?user-store=" + encodeURIComponent(userStore);
}
$(modalPopupContent).html($('#remove-role-modal-content').html()); $(modalPopupContent).html($('#remove-role-modal-content').html());
showPopup(); showPopup();
@ -210,7 +217,10 @@ $("#role-grid").on("click", ".remove-role-link", function () {
invokerUtil.delete( invokerUtil.delete(
removeRoleAPI, removeRoleAPI,
function () { function () {
$("#role-" + role).remove(); if (userStore) {
role = userStore + '/' + role;
}
$('[id="role-' + role + '"]').remove();
$(modalPopupContent).html($('#remove-role-success-content').html()); $(modalPopupContent).html($('#remove-role-success-content').html());
$("a#remove-role-success-link").click(function () { $("a#remove-role-success-link").click(function () {
hidePopup(); hidePopup();

@ -180,8 +180,7 @@ $("#userStore").change(
str += $(this).text() + ""; str += $(this).text() + "";
}); });
if ($("#roles").length > 0) { if ($("#roles").length > 0) {
var getRolesAPI = deviceMgtAPIsBasePath + "/roles?user-store=" + str + "&limit=100"; var getRolesAPI = deviceMgtAPIsBasePath + "/roles?user-store=" + encodeURIComponent(str) + "&limit=100";
invokerUtil.get( invokerUtil.get(
getRolesAPI, getRolesAPI,
function (data) { function (data) {
@ -189,10 +188,10 @@ $("#userStore").change(
if (data.errorMessage) { if (data.errorMessage) {
$(errorMsg).text("Selected user store prompted an error : " + data.errorMessage); $(errorMsg).text("Selected user store prompted an error : " + data.errorMessage);
$(errorMsgWrapper).removeClass("hidden"); $(errorMsgWrapper).removeClass("hidden");
} else if (data["statusCode"] == 200) { } else {
$("#roles").empty(); $("#roles").empty();
for (var i = 0; i < data.responseContent.length; i++) { for (var i = 0; i < data.roles.length; i++) {
var newOption = $('<option value="' + data.responseContent[i] + '">' + data.responseContent[i] + '</option>'); var newOption = $('<option value="' + data.roles[i] + '">' + data.roles[i] + '</option>');
$('#roles').append(newOption); $('#roles').append(newOption);
} }
} }

@ -236,7 +236,8 @@ $(document).ready(function () {
} }
addUserFormData.roles = roles; addUserFormData.roles = roles;
username = username.substr(username.indexOf('/') + 1); username = username.substr(username.indexOf('/') + 1);
var addUserAPI = deviceMgtBasePath + "/users/" + username + "?domain=" + domain; var addUserAPI = deviceMgtBasePath + "/users/" + encodeURIComponent(username) + "?domain=" +
encodeURIComponent(domain);
invokerUtil.put( invokerUtil.put(
addUserAPI, addUserAPI,

@ -158,7 +158,7 @@ function resetPassword(username) {
} }
var resetPasswordServiceURL = apiBasePath + "/admin/users/" + username + "/credentials"; var resetPasswordServiceURL = apiBasePath + "/admin/users/" + username + "/credentials";
if (domain) { if (domain) {
resetPasswordServiceURL += '?domain=' + domain; resetPasswordServiceURL += '?domain=' + encodeURIComponent(domain);
} }
invokerUtil.post( invokerUtil.post(
resetPasswordServiceURL, resetPasswordServiceURL,
@ -198,11 +198,10 @@ function removeUser(username) {
domain = username.substr(0, username.indexOf('/')); domain = username.substr(0, username.indexOf('/'));
username = username.substr(username.indexOf('/') + 1); username = username.substr(username.indexOf('/') + 1);
} }
var removeUserAPI = apiBasePath + "/users/" + username; var removeUserAPI = apiBasePath + "/users/" + encodeURIComponent(username);
if (domain) { if (domain) {
removeUserAPI += '?domain=' + domain; removeUserAPI += '?domain=' + encodeURIComponent(domain);
} }
modalDialog.header("Remove User"); modalDialog.header("Remove User");
modalDialog.content("Do you really want to remove this user ?"); modalDialog.content("Do you really want to remove this user ?");
modalDialog.footer('<div class="buttons"> <a href="#" id="remove-user-yes-link" class="btn-operations">Remove</a> ' + modalDialog.footer('<div class="buttons"> <a href="#" id="remove-user-yes-link" class="btn-operations">Remove</a> ' +
@ -219,10 +218,9 @@ function removeUser(username) {
function (data, textStatus, jqXHR) { function (data, textStatus, jqXHR) {
if (jqXHR.status == 200) { if (jqXHR.status == 200) {
if (domain) { if (domain) {
$("#user-" + domain + "\\/" + username).remove(); username = domain + '/' + username;
} else {
$("#user-" + username).remove();
} }
$('[id="user-' + username + '"]').remove();
// update modal-content with success message // update modal-content with success message
modalDialog.header("User Removed."); modalDialog.header("User Removed.");
modalDialog.content("Done. User was successfully removed."); modalDialog.content("Done. User was successfully removed.");
@ -338,7 +336,8 @@ function loadUsers() {
class: "text-right content-fill text-left-on-grid-view no-wrap", class: "text-right content-fill text-left-on-grid-view no-wrap",
data: null, data: null,
render: function (data, type, row, meta) { render: function (data, type, row, meta) {
var editbtn = '<a data-toggle="tooltip" data-placement="bottom" title="Edit User"href="' + context + '/user/edit?username=' + data.filter + '" data-username="' + data.filter + '" ' + var editbtn = '<a data-toggle="tooltip" data-placement="bottom" title="Edit User"href="' + context +
'/user/edit?username=' + encodeURIComponent(data.filter) + '" data-username="' + data.filter + '" ' +
'data-click-event="edit-form" ' + 'data-click-event="edit-form" ' +
'class="btn padding-reduce-on-grid-view edit-user-link"> ' + 'class="btn padding-reduce-on-grid-view edit-user-link"> ' +
'<span class="fw-stack"> ' + '<span class="fw-stack"> ' +

@ -24,14 +24,6 @@
*/ */
function onRequest(context) { function onRequest(context) {
var userModule = require("/app/modules/business-controllers/user.js")["userModule"]; var userModule = require("/app/modules/business-controllers/user.js")["userModule"];
var uri = request.getRequestURI(); context["roleName"] = request.getParameter("rolename");
var uriMatcher = new URIMatcher(String(uri));
var isMatched = uriMatcher.match("/{context}/role/edit-permission/{rolename}");
if (isMatched) {
var matchedElements = uriMatcher.elements();
var roleName = matchedElements.rolename;
context["roleName"] = roleName;
}
return context; return context;
} }

@ -103,7 +103,15 @@ $(document).ready(function () {
var listPartialSrc = $("#list-partial").attr("src"); var listPartialSrc = $("#list-partial").attr("src");
var treeTemplateSrc = $("#tree-template").attr("src"); var treeTemplateSrc = $("#tree-template").attr("src");
var roleName = $("#permissionList").data("currentrole"); var roleName = $("#permissionList").data("currentrole");
var userStore;
if (roleName.indexOf('/') > 0) {
userStore = roleName.substr(0, roleName.indexOf('/'));
roleName = roleName.substr(roleName.indexOf('/') + 1);
}
var serviceUrl = apiBasePath + "/roles/" +encodeURIComponent(roleName)+"/permissions"; var serviceUrl = apiBasePath + "/roles/" +encodeURIComponent(roleName)+"/permissions";
if (userStore) {
serviceUrl += "?user-store=" + encodeURIComponent(userStore);
}
$.registerPartial("list", listPartialSrc, function(){ $.registerPartial("list", listPartialSrc, function(){
$.template("treeTemplate", treeTemplateSrc, function (template) { $.template("treeTemplate", treeTemplateSrc, function (template) {
invokerUtil.get(serviceUrl, invokerUtil.get(serviceUrl,
@ -146,13 +154,23 @@ $(document).ready(function () {
*/ */
$("button#update-permissions-btn").click(function() { $("button#update-permissions-btn").click(function() {
var roleName = $("#permissionList").data("currentrole"); var roleName = $("#permissionList").data("currentrole");
var updateRolePermissionAPI = apiBasePath + "/roles/" + roleName; var userStore;
if (roleName.indexOf('/') > 0) {
userStore = roleName.substr(0, roleName.indexOf('/'));
roleName = roleName.substr(roleName.indexOf('/') + 1);
}
var updateRolePermissionAPI = apiBasePath + "/roles/" + encodeURIComponent(roleName);
var updateRolePermissionData = {}; var updateRolePermissionData = {};
var perms = []; var perms = [];
$("#permissionList li input:checked").each(function(){ $("#permissionList li input:checked").each(function(){
perms.push($(this).data("resourcepath")); perms.push($(this).data("resourcepath"));
}); });
if (userStore) {
updateRolePermissionAPI += "?user-store=" + encodeURIComponent(userStore);
updateRolePermissionData.roleName = userStore + "/" + roleName;
} else {
updateRolePermissionData.roleName = roleName; updateRolePermissionData.roleName = roleName;
}
updateRolePermissionData.permissions = perms; updateRolePermissionData.permissions = perms;
invokerUtil.put( invokerUtil.put(
updateRolePermissionAPI, updateRolePermissionAPI,

@ -25,28 +25,29 @@
function onRequest(context) { function onRequest(context) {
var userModule = require("/app/modules/business-controllers/user.js")["userModule"]; var userModule = require("/app/modules/business-controllers/user.js")["userModule"];
var deviceMgtProps = require("/app/modules/conf-reader/main.js")["conf"]; var deviceMgtProps = require("/app/modules/conf-reader/main.js")["conf"];
var uri = request.getRequestURI(); var uri = request.getRequestURI();
var uriMatcher = new URIMatcher(String(uri)); var roleName = request.getParameter("rolename");
var isMatched = uriMatcher.match("/{context}/role/edit/{roleName}"); var response;
if (isMatched) {
var matchedElements = uriMatcher.elements();
var roleName = matchedElements["roleName"];
var response = userModule.getRole(roleName);
if (response["status"] == "success") {
context["role"] = response["content"];
}
var userStore; var userStore;
if (roleName) {
if (roleName.indexOf("/") > -1) { if (roleName.indexOf("/") > -1) {
userStore = roleName.substring(0, roleName.indexOf("/")); userStore = roleName.substr(0, roleName.indexOf("/"));
} else { } else {
userStore = "PRIMARY"; userStore = "PRIMARY";
} }
response = userModule.getRole(roleName);
if (response["status"] == "success") {
context["role"] = response["content"];
}
context["userStore"] = userStore; context["userStore"] = userStore;
context["roleNameJSRegEx"] = deviceMgtProps["roleValidationConfig"]["roleNameJSRegEx"]; context["roleNameJSRegEx"] = deviceMgtProps["roleValidationConfig"]["roleNameJSRegEx"];
context["roleNameHelpText"] = deviceMgtProps["roleValidationConfig"]["roleNameHelpMsg"]; context["roleNameHelpText"] = deviceMgtProps["roleValidationConfig"]["roleNameHelpMsg"];
context["roleNameRegExViolationErrorMsg"] = deviceMgtProps["roleValidationConfig"]["roleNameRegExViolationErrorMsg"]; context["roleNameRegExViolationErrorMsg"] = deviceMgtProps["roleValidationConfig"]["roleNameRegExViolationErrorMsg"];
roleName = context["role"]["roleName"];
if (roleName.indexOf("/") > -1) {
context["role"]["roleName"] = roleName.substr(roleName.indexOf("/") + 1);
}
return context; return context;
} else { } else {
//TODO: handle error scenario //TODO: handle error scenario

@ -1,3 +1,21 @@
/*
* 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.
*/
/** /**
* Checks if provided input is valid against RegEx input. * Checks if provided input is valid against RegEx input.
* *
@ -12,6 +30,7 @@ function inputIsValid(regExp, inputString) {
var validateInline = {}; var validateInline = {};
var clearInline = {}; var clearInline = {};
var domain = $("#domain").val();
var apiBasePath = "/api/device-mgt/v1.0"; var apiBasePath = "/api/device-mgt/v1.0";
@ -112,7 +131,8 @@ $(document).ready(function () {
data: function (params) { data: function (params) {
var postData = {}; var postData = {};
postData.actionMethod = "GET"; postData.actionMethod = "GET";
postData.actionUrl = apiBasePath + "/users/search/usernames?filter=" + params.term; postData.actionUrl = apiBasePath + "/users/search/usernames?filter=" + params.term + "&domain=" +
encodeURIComponent(domain);
postData.actionPayload = null; postData.actionPayload = null;
return JSON.stringify(postData); return JSON.stringify(postData);
}, },
@ -163,11 +183,11 @@ $(document).ready(function () {
} else { } else {
var addRoleFormData = {}; var addRoleFormData = {};
addRoleFormData.roleName = roleName; addRoleFormData.roleName = roleName;
var addRoleAPI = apiBasePath + "/roles/" + encodeURIComponent(currentRoleName);
if (domain != "PRIMARY"){ if (domain != "PRIMARY"){
addRoleFormData.roleName = domain + "/" + roleName; addRoleFormData.roleName = domain + "/" + roleName;
addRoleAPI = addRoleAPI + "?user-store=" + encodeURIComponent(domain);
} }
var addRoleAPI = apiBasePath + "/roles/" + currentRoleName;
invokerUtil.put( invokerUtil.put(
addRoleAPI, addRoleAPI,
addRoleFormData, addRoleFormData,
@ -196,4 +216,12 @@ $(document).ready(function () {
$("#rolename").blur(function() { $("#rolename").blur(function() {
validateInline["role-name"](); validateInline["role-name"]();
}); });
/* When the user store domain value is changed, the users who are assigned to that role should be removed, as
user and role can be mapped only if both are in same user store
*/
$("#domain").change(function () {
$("#users").select2("val", "");
domain = $("#domain").val();
});
}); });
Loading…
Cancel
Save