Java Code Examples for org.wso2.carbon.user.core.UserStoreException

The following examples show how to use org.wso2.carbon.user.core.UserStoreException. These examples are extracted from open source projects. You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example 1
Source Project: carbon-identity   Source File: UserStoreManagerService.java    License: Apache License 2.0 6 votes vote down vote up
public int getTenantIdofUser(String username) throws UserStoreException {

        if (Util.isSuperTenant()) {
            return getUserStoreManager().getTenantId(username);
        } else {
            StringBuilder stringBuilder
                    = new StringBuilder(AUTH_FAIL);
            stringBuilder.append(CarbonContext.getThreadLocalCarbonContext().getTenantDomain()).append(" tenant id - ")
                    .append(CarbonContext.getThreadLocalCarbonContext().getTenantId()).append(" user - ")
                    .append(CarbonContext.getThreadLocalCarbonContext().getUsername());
            log.warn(stringBuilder.toString());

            throw new UserStoreException("Access Denied");
        }

    }
 
Example 2
/**
 * Overridden to trigger Notification Sending module to send messages to registered modules
 * on doPostSetUserClaimValues
 *
 * @param username         username of user whose claim values are updated
 * @param claims           set of claims
 * @param profileName      profile name
 * @param userStoreManager instance of user store manager called
 * @return always returns true since no major effect on further operations
 * @throws org.wso2.carbon.user.core.UserStoreException
 */
@Override
public boolean doPostSetUserClaimValues(String username,
                                        Map<String, String> claims, String profileName,
                                        UserStoreManager userStoreManager)
        throws UserStoreException {
    if (!isEnable()) {
        return true;
    }

    if (log.isDebugEnabled()) {
        log.debug("Sending user claim values update notification for user " + username);
    }
    sendNotification(EVENT_TYPE_PROFILE_UPDATE, username);
    // Returns true since no major effect on upcoming listeners
    return true;
}
 
Example 3
@Override
public boolean doPreDeleteUser(String userName, UserStoreManager userStoreManager) throws UserStoreException {
    if (!isEnable()) {
        return true;
    }

    String domainName = UserCoreUtil.getDomainName(userStoreManager.getRealmConfiguration());
    if (StringUtils.isBlank(domainName)) {
        domainName = UserAccountAssociationConstants.PRIMARY_USER_DOMAIN;
    }

    try {
        if (log.isDebugEnabled()) {
            log.debug("User account associations for user " + userName + " with tenant id " +
                      userStoreManager.getTenantId() + " is getting deleted.");
        }

        UserAccountAssociationDAO.getInstance().deleteUserAssociation(domainName, userStoreManager.getTenantId()
                , userName);
        return true;

    } catch (UserAccountAssociationException e) {
        throw new UserStoreException(String.format(UserAccountAssociationConstants.ErrorMessages
                                             .ERROR_WHILE_DELETING_USER_ASSOC.getDescription(), userName), e);
    }
}
 
Example 4
@Override
public boolean doPostGetRoleListOfUser(String userName, String filter, String[] roleList,
                                       UserStoreManager userStoreManager) throws UserStoreException {

    if (!isEnable()) {
        return true;
    }

    String userID = ((AbstractUserStoreManager) userStoreManager).getUserIDFromUserName(userName);
    if (userID == null) {
        return handleUserIDResolveFailure(userName, userStoreManager);
    }

    for (UserOperationEventListener listener : getUserStoreManagerListeners()) {
        if (isNotAResolverListener(listener)) {
            if (!((UniqueIDUserOperationEventListener) listener)
                    .doPostGetRoleListOfUserWithID(userID, filter, roleList, userStoreManager)) {
                return false;
            }
        }
    }

    return true;
}
 
Example 5
@Override
public boolean doPostGetRoleListOfUsers(String[] userNames, Map<String, List<String>> rolesOfUsersMap,
                                        UserStoreManager userStoreManager) throws UserStoreException {

    if (!isEnable()) {
        return true;
    }

    List<String> userIDsList = ((AbstractUserStoreManager) userStoreManager)
            .getUserIDsFromUserNames(Arrays.asList(userNames));

    for (UserOperationEventListener listener : getUserStoreManagerListeners()) {
        if (isNotAResolverListener(listener)) {
            if (!((UniqueIDUserOperationEventListener) listener)
                    .doPostGetRoleListOfUsersWithID(userIDsList, rolesOfUsersMap, userStoreManager)) {
                return false;
            }
        }
    }

    return true;
}
 
Example 6
Source Project: carbon-identity   Source File: UserStoreActionListener.java    License: Apache License 2.0 6 votes vote down vote up
@Override
public boolean doPreUpdateRoleName(String roleName, String newRoleName, UserStoreManager userStoreManager) throws
        UserStoreException {
    if (!isEnable() || isCalledViaIdentityMgtListners()) {
        return true;
    }
    try {
        UpdateRoleNameWFRequestHandler updateRoleNameWFRequestHandler = new UpdateRoleNameWFRequestHandler();
        String domain = userStoreManager.getRealmConfiguration().getUserStoreProperty(UserCoreConstants.RealmConfig
                                                                                              .PROPERTY_DOMAIN_NAME);

        int tenantId = userStoreManager.getTenantId() ;
        String currentUser = PrivilegedCarbonContext.getThreadLocalCarbonContext().getUsername();
        PrivilegedCarbonContext.startTenantFlow();
        PrivilegedCarbonContext.getThreadLocalCarbonContext().setTenantId(tenantId, true);
        PrivilegedCarbonContext.getThreadLocalCarbonContext().setUsername(currentUser);

        return updateRoleNameWFRequestHandler.startUpdateRoleNameFlow(domain, roleName, newRoleName);
    } catch (WorkflowException e) {
        // Sending e.getMessage() since it is required to give error message to end user.
        throw new UserStoreException(e.getMessage(), e);
    } finally {
        PrivilegedCarbonContext.endTenantFlow();
    }
}
 
Example 7
@Override
public boolean doPostDeleteUserClaimValuesWithID(String userID, UserStoreManager userStoreManager)
        throws UserStoreException {

    if (!isEnable()) {
        return true;
    }

    String userName = getUserNameFromUserID(userID, (AbstractUserStoreManager) userStoreManager);
    if (userName == null) {
        return handleUserNameResolveFailure(userID, userStoreManager);
    }

    for (UserOperationEventListener listener : getUserStoreManagerListeners()) {
        if (isNotAResolverListener(listener)) {
            if (!listener.doPostDeleteUserClaimValues(userName, userStoreManager)) {
                return false;
            }
        }
    }

    return true;
}
 
Example 8
@Override
public boolean doPostSetUserClaimValuesWithID(String userID, Map<String, String> claims, String profileName,
                                              UserStoreManager userStoreManager) throws UserStoreException {

    if (!isEnable()) {
        return true;
    }

    String userName = getUserNameFromUserID(userID, (AbstractUserStoreManager) userStoreManager);
    if (userName == null) {
        return handleUserNameResolveFailure(userID, userStoreManager);
    }

    for (UserOperationEventListener listener : getUserStoreManagerListeners()) {
        if (isNotAResolverListener(listener)) {
            if (!listener.doPostSetUserClaimValues(userName, claims, profileName, userStoreManager)) {
                return false;
            }
        }
    }

    return true;
}
 
Example 9
@Override
public boolean doPostGetUserListWithID(Condition condition, String domain, String profileName, int limit,
                                       int offset, String sortBy, String sortOrder, List<User> users,
                                       UserStoreManager userStoreManager)
        throws UserStoreException {

    if (!isEnable()) {
        return true;
    }

    List<String> userNamesList = users.stream().map(User::getUsername).collect(Collectors.toList());
    String[] userNames = userNamesList.toArray(new String[0]);

    for (UserOperationEventListener listener : getUserStoreManagerListeners()) {
        if (isNotAResolverListener(listener)) {
            return listener
                    .doPostGetUserList(condition, domain, profileName, limit, offset, sortBy, sortOrder, userNames,
                            userStoreManager);
        }
    }

    return true;
}
 
Example 10
Source Project: carbon-identity   Source File: DirectoryServerManager.java    License: Apache License 2.0 6 votes vote down vote up
/**
 * Gets the regular expression which defines the format of the service principle, password.
 *
 * @return Regular expression.
 * @throws DirectoryServerManagerException If unable to get RealmConfiguration.
 */
public String getPasswordConformanceRegularExpression() throws DirectoryServerManagerException {

    try {
        RealmConfiguration userStoreConfigurations = this.getUserRealm().getRealmConfiguration();
        if (userStoreConfigurations != null) {
            String passwordRegEx = userStoreConfigurations.getUserStoreProperty(
                    LDAPServerManagerConstants.SERVICE_PASSWORD_REGEX_PROPERTY);
            if (passwordRegEx == null) {
                return LDAPServerManagerConstants.DEFAULT_PASSWORD_REGULAR_EXPRESSION;
            } else {
                log.info("Service password format is " + passwordRegEx);
                return passwordRegEx;
            }
        }
    } catch (UserStoreException e) {
        log.error("Unable to retrieve service password format.", e);
        throw new DirectoryServerManagerException("Unable to retrieve service password format.", e);
    }

    return LDAPServerManagerConstants.DEFAULT_PASSWORD_REGULAR_EXPRESSION;
}
 
Example 11
Source Project: carbon-identity   Source File: UserProfileAdmin.java    License: Apache License 2.0 6 votes vote down vote up
private String[] getAvailableProfileConfiguration(
        ProfileConfigurationManager profileAdmin) throws UserStoreException {
    ProfileConfiguration[] configurations;
    String[] profileNames = new String[0];
    try {
        configurations = (ProfileConfiguration[]) profileAdmin.getAllProfiles();
    } catch (org.wso2.carbon.user.api.UserStoreException e) {
        throw new UserStoreException(e);
    }

    if (configurations != null) {
        profileNames = new String[configurations.length];
        for (int i = 0; i < configurations.length; i++) {
            profileNames[i] = configurations[i].getProfileName();
        }
    }

    return profileNames;
}
 
Example 12
private void updateUserWithNewRoleSet(String username, UserStoreManager userStoreManager, String[] newRoles,
                                      Collection<String> addingRoles, Collection<String> deletingRoles)
        throws UserStoreException {
    if (log.isDebugEnabled()) {
        log.debug("Deleting roles : "
                  + Arrays.toString(deletingRoles.toArray(new String[deletingRoles.size()]))
                  + " and Adding roles : "
                  + Arrays.toString(addingRoles.toArray(new String[addingRoles.size()])));
    }
    userStoreManager.updateRoleListOfUser(username, deletingRoles.toArray(new String[deletingRoles
                                                  .size()]),
                                          addingRoles.toArray(new String[addingRoles.size()]));
    if (log.isDebugEnabled()) {
        log.debug("Federated user: " + username
                  + " is updated by authentication framework with roles : "
                  + Arrays.toString(newRoles));
    }
}
 
Example 13
Source Project: carbon-identity-framework   Source File: UserRealmProxy.java    License: Apache License 2.0 6 votes vote down vote up
private void buildUIPermissionNodeAllSelected(Collection parent, UIPermissionNode parentNode,
                                              Registry registry, Registry tenantRegistry) throws RegistryException,
        UserStoreException {

    String[] children = parent.getChildren();
    UIPermissionNode[] childNodes = new UIPermissionNode[children.length];
    for (int i = 0; i < children.length; i++) {
        String child = children[i];
        Resource resource = null;

        if (registry.resourceExists(child)) {
            resource = registry.get(child);
        } else if (tenantRegistry != null) {
            resource = tenantRegistry.get(child);
        } else {
            throw new RegistryException("Permission resource not found in the registry.");
        }

        childNodes[i] = getUIPermissionNode(resource, true);
        if (resource instanceof Collection) {
            buildUIPermissionNodeAllSelected((Collection) resource, childNodes[i], registry,
                    tenantRegistry);
        }
    }
    parentNode.setNodeList(childNodes);
}
 
Example 14
@Override
public boolean doPostAddRoleWithID(String roleName, String[] userIDList, Permission[] permissions,
                                   UserStoreManager userStoreManager) throws UserStoreException {

    if (!isEnable()) {
        return true;
    }

    String[] userNames = getUserNamesFromUserIDs(userIDList, (AbstractUserStoreManager) userStoreManager);

    for (UserOperationEventListener listener : getUserStoreManagerListeners()) {
        if (isNotAResolverListener(listener)) {
            if (!listener.doPostAddRole(roleName, userNames, permissions, userStoreManager)) {
                return false;
            }
        }
    }

    return true;
}
 
Example 15
/**
 * This method is overridden to clear caches on doPostDeleteRole operation
 *
 * @param roleName         Deleted role name
 * @param userStoreManager UserStoreManagerClass
 * @return Always Returns true, since no major effect on further procedures
 * @throws org.wso2.carbon.user.core.UserStoreException
 */
@Override
public boolean doPostDeleteRole(String roleName, UserStoreManager userStoreManager) throws
                                                                                    UserStoreException {
    if (!isEnable()) {
        return true;
    }

    if (log.isDebugEnabled()) {
        log.debug("Clearing entitlement cache on post delete role operation for role " +
                  roleName);
    }
    clearCarbonAttributeCache();
    // Always returns true since cache clearing failure does not make an effect on subsequent
    // User Operation Listeners
    return true;
}
 
Example 16
@Test
public void testFailuresToUpdateRoleOfUserWhenRemoteServiceCallFailed() throws UserStoreException, RemoteException,
        UserAdminUserAdminException {
    Mockito.when(userAdminStub.getRolesOfUser(username, "*", -1)).thenReturn(flaggedNames);
    Mockito.when(userStoreManager.isExistingRole(role)).thenReturn(true);

    //Test failure to update the user role when
    Mockito.doThrow(new RemoteException("Exception occurred while updating the roles of user")).when(userAdminStub)
            .updateRolesOfUser(Mockito.anyString(), new
                    String[]{Mockito.anyString()});
    try {
        UserSignUpWorkflowExecutor.updateRolesOfUser(serverURL, adminUsername, adminPassword, username, role);
        Assert.fail("Expected exception has been not thrown while updating the roles of user failed");
    } catch (Exception e) {
        Assert.assertEquals(e.getMessage(), "Exception occurred while updating the roles of user");
    }
}
 
Example 17
@Override
public boolean doPostGetUserListWithID(String claimUri, String claimValue, List<User> returnUsersList,
                                       UserStoreManager userStoreManager) throws UserStoreException {

    if (!isEnable()) {
        return true;
    }

    List<String> returnUserNamesList = returnUsersList.stream().map(User::getUsername).collect(Collectors.toList());

    for (UserOperationEventListener listener : getUserStoreManagerListeners()) {
        if (isNotAResolverListener(listener)) {
            if (!listener.doPostGetUserList(claimUri, claimValue, returnUserNamesList, userStoreManager)) {
                return false;
            }
        }
    }

    return true;
}
 
Example 18
@Override
public boolean doPreGetUserListWithID(String claimUri, String claimValue, int limit, int offset,
                                      List<User> returnUsersList, UserStoreManager userStoreManager)
        throws UserStoreException {

    if (!isEnable()) {
        return true;
    }

    List<String> returnUserNamesList = returnUsersList.stream().map(User::getUsername).collect(Collectors.toList());

    for (UserOperationEventListener listener : getUserStoreManagerListeners()) {
        if (isNotAResolverListener(listener)) {
            return listener
                    .doPreGetUserList(claimUri, claimValue, limit, offset, returnUserNamesList, userStoreManager);
        }
    }

    return true;
}
 
Example 19
Source Project: carbon-identity-framework   Source File: CaptchaUtil.java    License: Apache License 2.0 6 votes vote down vote up
public static void setAnonAuthorization(String path, UserRealm userRealm)
        throws RegistryException {

    if (userRealm == null) {
        return;
    }

    try {
        AuthorizationManager accessControlAdmin = userRealm.getAuthorizationManager();
        String everyoneRole = CarbonConstants.REGISTRY_ANONNYMOUS_ROLE_NAME;

        accessControlAdmin.authorizeRole(everyoneRole, path, ActionConstants.GET);
        accessControlAdmin.denyRole(everyoneRole, path, ActionConstants.PUT);
        accessControlAdmin.denyRole(everyoneRole, path, ActionConstants.DELETE);
        accessControlAdmin.denyRole(everyoneRole, path, AccessControlConstants.AUTHORIZE);

    } catch (UserStoreException e) {
        String msg = "Could not set authorizations for the " + path + ".";
        log.error(msg, e);
        throw new RegistryException(msg);
    }
}
 
Example 20
private String[] getUserIdsFromUserNames(String[] userNames, AbstractUserStoreManager userStoreManager)
        throws UserStoreException {

    if (ArrayUtils.isEmpty(userNames)) {
        return new String[0];
    }

    List<String> userIDsList = userStoreManager.getUserIDsFromUserNames(Arrays.asList(userNames));

    return userIDsList.toArray(new String[0]);
}
 
Example 21
Source Project: carbon-apimgt   Source File: AbstractAPIManagerTestCase.java    License: Apache License 2.0 5 votes vote down vote up
@Test
public void testGetPolicies() throws APIManagementException, org.wso2.carbon.user.api.UserStoreException,
        RegistryException {
    APIPolicy[] policies1 = { new APIPolicy("policy1") };
    ApplicationPolicy[] policies2 = { new ApplicationPolicy("policy2"), new ApplicationPolicy("policy3") };
    SubscriptionPolicy[] policies3 = { new SubscriptionPolicy("policy4"), new SubscriptionPolicy("policy5"),
            new SubscriptionPolicy("policy6") };
    GlobalPolicy[] policies4 = { new GlobalPolicy("policy7"), new GlobalPolicy("policy8"),
            new GlobalPolicy("policy9"), new GlobalPolicy("policy0") };
    PowerMockito.mockStatic(APIUtil.class);
    BDDMockito.when(APIUtil.getTenantId(Mockito.anyString())).thenReturn(-1234);
    PowerMockito.when(APIUtil.replaceSystemProperty(Mockito.anyString())).thenAnswer((Answer<String>) invocation -> {
        Object[] args = invocation.getArguments();
        return (String) args[0];
    });
    AbstractAPIManager abstractAPIManager = new AbstractAPIManagerWrapper(apiMgtDAO);
    Mockito.when(apiMgtDAO.getAPIPolicies(Mockito.anyInt())).thenReturn(policies1);
    Mockito.when(apiMgtDAO.getApplicationPolicies(Mockito.anyInt())).thenReturn(policies2);
    Mockito.when(apiMgtDAO.getSubscriptionPolicies(Mockito.anyInt())).thenReturn(policies3);
    Mockito.when(apiMgtDAO.getGlobalPolicies(Mockito.anyInt())).thenReturn(policies4);

    ServiceReferenceHolder sh = mockRegistryAndUserRealm(-1234);
    APIManagerConfigurationService amConfigService = Mockito.mock(APIManagerConfigurationService.class);
    APIManagerConfiguration amConfig = Mockito.mock(APIManagerConfiguration.class);
    ThrottleProperties throttleProperties = Mockito.mock(ThrottleProperties.class, Mockito.RETURNS_MOCKS);

    PowerMockito.when(sh.getAPIManagerConfigurationService()).thenReturn(amConfigService);
    PowerMockito.when(amConfigService.getAPIManagerConfiguration()).thenReturn(amConfig);
    PowerMockito.when(amConfig.getThrottleProperties()).thenReturn(throttleProperties);

    Assert.assertEquals(abstractAPIManager.getPolicies(API_PROVIDER, PolicyConstants.POLICY_LEVEL_API).length, 1);
    Assert.assertEquals(abstractAPIManager.getPolicies(API_PROVIDER, PolicyConstants.POLICY_LEVEL_APP).length, 2);

    PowerMockito.when(throttleProperties.isEnableUnlimitedTier()).thenReturn(false);

    Assert.assertEquals(3, abstractAPIManager.getPolicies(API_PROVIDER, PolicyConstants.POLICY_LEVEL_SUB).length);
    Assert.assertEquals(4, abstractAPIManager.getPolicies(API_PROVIDER,
            PolicyConstants.POLICY_LEVEL_GLOBAL).length);
    Assert.assertEquals(0, abstractAPIManager.getPolicies(API_PROVIDER, "Test").length);
}
 
Example 22
Source Project: carbon-identity   Source File: SCIMUserOperationListener.java    License: Apache License 2.0 5 votes vote down vote up
@Override
public boolean doPostAddUser(String userName, Object credential, String[] roleList,
                             Map<String, String> claims, String profile,
                             UserStoreManager userStoreManager)
        throws UserStoreException {
    return true;
}
 
Example 23
Source Project: carbon-identity   Source File: WSRealmTenantManager.java    License: Apache License 2.0 5 votes vote down vote up
public void updateTenant(Tenant tenant) throws UserStoreException {
    try {
        getStub().updateTenant(this.tenantToADBTenant(tenant));
    } catch (Exception e) {
        handleException("", e);
    }
}
 
Example 24
public boolean doPreGetUserClaimValue(String userName, String claim, String profileName,
                                      UserStoreManager storeManager) throws UserStoreException {

    if (!isEnable()) {
        // a simple user claim. add it to the user store
        return true;
    }
    if (StringUtils.isNotBlank(claim) && claim.contains(UserCoreConstants.ClaimTypeURIs.IDENTITY_CLAIM_URI)) {
        throw new UserStoreException(INVALID_OPERATION + " This operation is not supported for Identity claims");
    }

    return true;
}
 
Example 25
public boolean doPostDeleteRole(String roleName, UserStoreManager userStoreManager) throws UserStoreException {

        if(!isEnable()) {
            return true;
        }

        audit.info(String.format(AUDIT_MESSAGE, getUser(), "Delete Role", roleName, "",
                SUCCESS));
        return true;
    }
 
Example 26
@Override
public boolean doPreSetUserClaimValues(String userName, Map<String, String> claims, String profileName, UserStoreManager userStoreManager) throws UserStoreException {

    if (isEnable()) {
        if (isLogUpdatedClaimsOnlyPropertyEnabled()) {
            logUpdatedClaims(userName, claims, "doPreSetUserClaimValues", userStoreManager);
        } else {
            logClaims(userName, "doPreSetUserClaimValues", userStoreManager);
        }
    }
    return true;
}
 
Example 27
Source Project: carbon-identity   Source File: UserProfileAdmin.java    License: Apache License 2.0 5 votes vote down vote up
public boolean isAddProfileEnabled() throws UserProfileException {
    UserRealm realm = getUserRealm();
    UserStoreManager userStoreManager = null;
    try {
        userStoreManager = realm.getUserStoreManager();
    } catch (UserStoreException e) {
        String errorMessage = "Error in obtaining UserStoreManager.";
        log.error(errorMessage, e);
        throw new UserProfileException(errorMessage, e);
    }
    return userStoreManager.isMultipleProfilesAllowed();
}
 
Example 28
Source Project: carbon-identity   Source File: UserProfileUtil.java    License: Apache License 2.0 5 votes vote down vote up
public static boolean isUserAuthorizedToConfigureProfile(UserRealm realm, String currentUserName, String targetUser)
        throws UserStoreException {
    boolean isAuthrized = false;
    if (currentUserName == null) {
        //do nothing
    } else if (currentUserName.equals(targetUser)) {
        isAuthrized = true;
    } else {
        AuthorizationManager authorizer = realm.getAuthorizationManager();
        isAuthrized = authorizer.isUserAuthorized(currentUserName,
                CarbonConstants.UI_ADMIN_PERMISSION_COLLECTION + "/configure/security/usermgt/profiles",
                "ui.execute");
    }
    return isAuthrized;
}
 
Example 29
Source Project: carbon-apimgt   Source File: SelfSignupUtilTestCase.java    License: Apache License 2.0 5 votes vote down vote up
@Test(expected = APIManagementException.class)
public void testIsUserNameWithAllowedDomainNameException() throws Exception {
    UserRealm userRealm = Mockito.mock(UserRealm.class);
    RealmConfiguration realmConfiguration = new RealmConfiguration();
    realmConfiguration.addRestrictedDomainForSelfSignUp("bar.com");
    Mockito.when(userRealm.getRealmConfiguration()).thenThrow(new UserStoreException());
    SelfSignUpUtil.isUserNameWithAllowedDomainName("bar.com/john", userRealm);
}
 
Example 30
Source Project: carbon-identity   Source File: UserRealmProxy.java    License: Apache License 2.0 5 votes vote down vote up
public void setRoleUIPermission(String roleName, String[] rawResources)
        throws UserAdminException {
    try {
        if (((AbstractUserStoreManager) realm.getUserStoreManager()).isOthersSharedRole(roleName)) {
            throw new UserAdminException("Logged in user is not authorized to assign " +
                    "permissions to a role belong to another tenant");
        }
        if (realm.getRealmConfiguration().getAdminRoleName().equalsIgnoreCase(roleName)) {
            String msg = "UI permissions of Admin is not allowed to change";
            log.error(msg);
            throw new UserAdminException(msg);
        }

        String loggedInUserName = addPrimaryDomainIfNotExists(getLoggedInUser());
        String adminUser = addPrimaryDomainIfNotExists(realm.getRealmConfiguration().getAdminUserName());
        if (rawResources != null &&
                !adminUser.equalsIgnoreCase(loggedInUserName)) {
            Arrays.sort(rawResources);
            if (Arrays.binarySearch(rawResources, PERMISSION_ADMIN) > -1 ||
                    Arrays.binarySearch(rawResources, "/permission/protected") > -1 ||
                    Arrays.binarySearch(rawResources, PERMISSION) > -1) {
                log.warn("An attempt to Assign admin permission for role by user : " +
                        loggedInUserName);
                throw new UserStoreException("Can not assign Admin for permission role");
            }
        }

        String[] optimizedList = UserCoreUtil.optimizePermissions(rawResources);
        AuthorizationManager authMan = realm.getAuthorizationManager();
        authMan.clearRoleActionOnAllResources(roleName, UserMgtConstants.EXECUTE_ACTION);
        for (String path : optimizedList) {
            authMan.authorizeRole(roleName, path, UserMgtConstants.EXECUTE_ACTION);
        }
    } catch (UserStoreException e) {
        log.error(e.getMessage(), e);
        throw new UserAdminException(e.getMessage(), e);
    }
}