org.wso2.carbon.user.core.UserRealm Java Examples

The following examples show how to use org.wso2.carbon.user.core.UserRealm. 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 File: CommonUtil.java    From attic-stratos with 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 #2
Source File: UserRegistrationService.java    From carbon-identity-framework with Apache License 2.0 6 votes vote down vote up
public void addUser(UserDTO user) throws Exception {
    UserFieldDTO[] userFieldDTOs = null;
    Map<String, String> userClaims = null;

    userFieldDTOs = user.getUserFields();
    userClaims = new HashMap<String, String>();

    if (userFieldDTOs != null) {
        for (UserFieldDTO userFieldDTO : userFieldDTOs) {
            userClaims.put(userFieldDTO.getClaimUri(), userFieldDTO.getFieldValue());
        }
    }

    UserRealm realm = null;
    String tenantAwareUserName = MultitenantUtils.getTenantAwareUsername(user.getUserName());
    String tenantName = MultitenantUtils.getTenantDomain(user.getUserName());
    realm = IdentityTenantUtil.getRealm(tenantName, null);
    addUser(tenantAwareUserName, user.getPassword(), userClaims, null, realm);
}
 
Example #3
Source File: SelfSignUpUtil.java    From carbon-apimgt with Apache License 2.0 6 votes vote down vote up
/**
 * Check whether user can signup to the tenant domain
 * 
 * @param userName - The user name
 * @param realm - The realm
 * @return - A boolean value
 * @throws APIManagementException
 */
public static boolean isUserNameWithAllowedDomainName(String userName, UserRealm realm)
		throws APIManagementException {
	int index;
	index = userName.indexOf('/');

	// Check whether we have a secondary UserStoreManager setup.
	if (index > 0) {
		// Using the short-circuit. User name comes with the domain name.
		try {
			return !realm.getRealmConfiguration()
					.isRestrictedDomainForSlefSignUp(userName.substring(0, index));
		} catch (UserStoreException e) {
			throw new APIManagementException(e.getMessage(), e);				
		}
	}

	return true;
}
 
Example #4
Source File: UserAdmin.java    From carbon-identity with Apache License 2.0 6 votes vote down vote up
/**
 * @param roleName
 * @param realm
 * @return
 * @throws UserAdminException
 */
private boolean isAllowedRoleName(String roleName, UserRealm realm) throws UserAdminException {

    int index;
    index = roleName.indexOf("/");

    if (index > 0) {
        roleName = roleName.substring(index + 1);
    }

    try {
        return !realm.getRealmConfiguration().isReservedRoleName(roleName);
    } catch (UserStoreException e) {
        throw new UserAdminException(e.getMessage(), e);
    }
}
 
Example #5
Source File: UserProfileAdmin.java    From carbon-identity with Apache License 2.0 6 votes vote down vote up
/**
 * @return
 * @throws UserStoreException
 */
private Claim[] getAllSupportedClaims(UserRealm realm, String dialectUri)
        throws org.wso2.carbon.user.api.UserStoreException {
    ClaimMapping[] claims = null;
    List<Claim> reqClaims = null;

    claims = realm.getClaimManager().getAllSupportClaimMappingsByDefault();
    reqClaims = new ArrayList<Claim>();
    for (int i = 0; i < claims.length; i++) {
        if (dialectUri.equals(claims[i].getClaim().getDialectURI()) && (claims[i] != null && claims[i].getClaim().getDisplayTag() != null
                && !claims[i].getClaim().getClaimUri().equals(IdentityConstants.CLAIM_PPID))) {

            reqClaims.add((Claim) claims[i].getClaim());
        }
    }

    return reqClaims.toArray(new Claim[reqClaims.size()]);
}
 
Example #6
Source File: UserAdmin.java    From carbon-identity with Apache License 2.0 6 votes vote down vote up
/**
 * Get list of roles which have given permission
 *
 * @param filter     filter to check
 * @param permission permission to check
 * @param limit
 * @return
 * @throws UserAdminException
 */
public FlaggedName[] getAllPermittedRoleNames(String filter, String permission, int limit) throws
        UserAdminException {

    FlaggedName[] roles = getUserAdminProxy().getAllRolesNames(filter, limit);
    List<FlaggedName> permittedRoles = new ArrayList<>();
    try {
        org.wso2.carbon.user.api.UserRealm realm = UserMgtDSComponent.getRealmService().getTenantUserRealm
                (PrivilegedCarbonContext.getThreadLocalCarbonContext().getTenantId());
        AuthorizationManager authorizationManager = realm.getAuthorizationManager();
        for (int i = 0; i < roles.length - 1; i++) {
            if (authorizationManager.isRoleAuthorized(roles[i].getItemName(), permission, UserMgtConstants
                    .EXECUTE_ACTION)) {
                permittedRoles.add(roles[i]);
            }
        }
        permittedRoles.add(roles[roles.length - 1]);
    } catch (org.wso2.carbon.user.api.UserStoreException e) {
        throw new UserAdminException("Error while filtering authorized roles.", e);
    }
    FlaggedName[] permittedRolesArray = new FlaggedName[permittedRoles.size()];
    return permittedRoles.toArray(permittedRolesArray);
}
 
Example #7
Source File: UserProfileAdmin.java    From carbon-identity with Apache License 2.0 6 votes vote down vote up
public boolean isAddProfileEnabledForDomain(String domain) throws UserProfileException {

        org.wso2.carbon.user.core.UserStoreManager userStoreManager = null;
        org.wso2.carbon.user.core.UserRealm realm = getUserRealm();
        boolean isAddProfileEnabled = false;

        try {
            if (StringUtils.isBlank(domain) || StringUtils.equals(domain, UserCoreConstants.PRIMARY_DEFAULT_DOMAIN_NAME)) {
                userStoreManager = realm.getUserStoreManager();
            } else {
                userStoreManager = realm.getUserStoreManager().getSecondaryUserStoreManager(domain);
            }

        } catch (UserStoreException e) {
            String errorMessage = "Error in obtaining SecondaryUserStoreManager.";
            log.error(errorMessage, e);
            throw new UserProfileException(errorMessage, e);
        }

        if (userStoreManager != null) {
            isAddProfileEnabled = userStoreManager.isMultipleProfilesAllowed();
        }

        return isAddProfileEnabled;
    }
 
Example #8
Source File: DefaultClaimHandler.java    From carbon-identity with Apache License 2.0 6 votes vote down vote up
private UserStoreManager getUserStoreManager(String tenantDomain, UserRealm realm, String userDomain) throws
        FrameworkException {
    UserStoreManager userStore = null;
    try {
        userStore = realm.getUserStoreManager();
        if (StringUtils.isNotBlank(userDomain)) {
            userStore = realm.getUserStoreManager().getSecondaryUserStoreManager(userDomain);
        }

        if (userStore == null) {
            // To avoid NPEs
            throw new FrameworkException("Invalid user store domain name : " + userDomain + " in tenant : "
                    + tenantDomain);
        }
    } catch (UserStoreException e) {
        throw new FrameworkException("Error occurred while retrieving the UserStoreManager " +
                                     "from Realm for " + tenantDomain + " to handle local claims", e);
    }
    return userStore;
}
 
Example #9
Source File: UserSignUpWorkflowExecutorTest.java    From carbon-apimgt with Apache License 2.0 6 votes vote down vote up
@Before
public void init() throws Exception {
    ServiceReferenceHolder serviceReferenceHolder = TestUtils.getServiceReferenceHolder();
    RealmService realmService = Mockito.mock(RealmService.class);
    UserRealm userRealm = Mockito.mock(UserRealm.class);
    userStoreManager = Mockito.mock(UserStoreManager.class);
    PowerMockito.mockStatic(CarbonUtils.class);
    userAdminStub = Mockito.mock(UserAdminStub.class);
    userRegistrationAdminServiceStub = Mockito.mock(UserRegistrationAdminServiceStub.class);
    serviceClient =  Mockito.mock(ServiceClient.class);;
    PowerMockito.whenNew(UserAdminStub.class).withAnyArguments().thenReturn(userAdminStub);
    PowerMockito.whenNew(UserRegistrationAdminServiceStub.class).withAnyArguments().thenReturn
            (userRegistrationAdminServiceStub);
    PowerMockito.when(userRegistrationAdminServiceStub._getServiceClient()).thenReturn(serviceClient);
    Mockito.when(serviceClient.getOptions()).thenReturn(new Options());
    Mockito.when(serviceReferenceHolder.getRealmService()).thenReturn(realmService);
    Mockito.when(realmService.getBootstrapRealm()).thenReturn(userRealm);
    Mockito.when(userRealm.getUserStoreManager()).thenReturn(userStoreManager);
    PowerMockito.doNothing().when(CarbonUtils.class, "setBasicAccessSecurityHeaders", Mockito.anyString(),
            Mockito.anyString(), Mockito.anyBoolean(), (ServiceClient) Mockito.anyObject());
    FlaggedName flaggedName = new FlaggedName();
    flaggedName.setSelected(true);
    flaggedName.setItemName(role);
    flaggedNames = new FlaggedName[]{flaggedName};
}
 
Example #10
Source File: DatabaseBasedUserStoreDAOImpl.java    From carbon-identity-framework with Apache License 2.0 5 votes vote down vote up
private void addRealmToSecondaryUserStoreManager(UserStorePersistanceDTO userStorePersistanceDTO) throws
        UserStoreException, XMLStreamException {

    UserRealm userRealm = (UserRealm) CarbonContext.getThreadLocalCarbonContext().getUserRealm();
    AbstractUserStoreManager primaryUSM = (AbstractUserStoreManager) userRealm.getUserStoreManager();
    InputStream targetStream = new ByteArrayInputStream(userStorePersistanceDTO.getUserStoreProperties()
                                                                               .getBytes());
    RealmConfiguration realmConfiguration = getRealmConfiguration(userStorePersistanceDTO.getUserStoreDTO().
            getDomainId(), targetStream);
    primaryUSM.addSecondaryUserStoreManager(realmConfiguration, userRealm);
}
 
Example #11
Source File: ProfileConfigurationManagerService.java    From carbon-identity with Apache License 2.0 5 votes vote down vote up
private ProfileConfigurationManager getProfileConfigurationManager() throws UserStoreException {
    try {
        UserRealm realm = super.getUserRealm();
        if (realm == null) {
            throw new UserStoreException(NULL_REALM_MESSAGE);
        }
        return realm.getProfileConfigurationManager();
    } catch (Exception e) {
        throw new UserStoreException(e);
    }
}
 
Example #12
Source File: UserRegistrationService.java    From carbon-identity with Apache License 2.0 5 votes vote down vote up
/**
 * This service method will return back all available password validation regular expressions
 * against the corresponding domain names.
 *
 * @return
 * @throws IdentityException
 */
public PasswordRegExDTO[] getPasswordRegularExpressions() throws IdentityException {
    UserRealm realm = null;
    realm = IdentityTenantUtil.getRealm(null, null);
    List<PasswordRegExDTO> passwordRegExList = new ArrayList<PasswordRegExDTO>();
    PasswordRegExDTO passwordRegEx;

    try {
        UserStoreManager manager = realm.getUserStoreManager();
        String domainName;
        String regEx;

        while (manager != null) {
            domainName = manager.getRealmConfiguration().getUserStoreProperty(
                    UserCoreConstants.RealmConfig.PROPERTY_DOMAIN_NAME);
            regEx = manager.getRealmConfiguration().getUserStoreProperty(
                    UserCoreConstants.RealmConfig.PROPERTY_JS_REG_EX);
            if (regEx != null && regEx.length() > 0) {
                passwordRegEx = new PasswordRegExDTO();
                passwordRegEx.setDomainName(domainName);
                passwordRegEx.setRegEx(regEx);
                passwordRegExList.add(passwordRegEx);
            }
            manager = manager.getSecondaryUserStoreManager();
        }
    } catch (UserStoreException e) {
        log.error(e);
        throw IdentityException.error(
                "Error occured while loading password validation regular expressions.");
    }
    return passwordRegExList.toArray(new PasswordRegExDTO[passwordRegExList.size()]);
}
 
Example #13
Source File: IdentityProfileManager.java    From carbon-identity-framework with Apache License 2.0 5 votes vote down vote up
/**
 * Set user realm for IdentityProfileManager.
 *
 * @param realm user realm to be set
 */
public void setRealm(UserRealm realm) {
    this.realm = realm;
    if (log.isDebugEnabled()) {
        if (realm != null) {
            log.debug("IdentityProfileManager UserRealm set successfully: "
                    + realm.getClass().getName());
        }
    }
}
 
Example #14
Source File: UserSignUpWorkflowExecutor.java    From carbon-apimgt with Apache License 2.0 5 votes vote down vote up
/**
 * Method updates Roles users with subscriber role
 * @param serverURL
 * @param adminUsername
 * @param adminPassword
 * @param userName
 * @param role
 * @throws Exception
 */
protected static void updateRolesOfUser(String serverURL, String adminUsername,
                                        String adminPassword, String userName, String role)
                                                                                           throws Exception {
	if (log.isDebugEnabled()) {
		log.debug("Adding Subscriber role to " + userName);
	}

	String url = serverURL + "UserAdmin";
	RealmService realmService = ServiceReferenceHolder.getInstance().getRealmService();
	UserRealm realm = realmService.getBootstrapRealm();
	UserStoreManager manager = realm.getUserStoreManager();
	if (!manager.isExistingRole(role)){
		log.error("Could not find role " + role + " in the user store");
		throw new Exception("Could not find role " + role + " in the user store");
	}

	UserAdminStub userAdminStub = new UserAdminStub(url);
	CarbonUtils.setBasicAccessSecurityHeaders(adminUsername, adminPassword, userAdminStub._getServiceClient());
	FlaggedName[] flaggedNames = userAdminStub.getRolesOfUser(userName, "*", -1);
	List<String> roles = new ArrayList<String>();
	if (flaggedNames != null) {
		for (FlaggedName flaggedName : flaggedNames) {
			if (flaggedName.getSelected()) {
				roles.add(flaggedName.getItemName());
			}
		}
	}
	roles.add(role);
	userAdminStub.updateRolesOfUser(userName, roles.toArray(new String[roles.size()]));
}
 
Example #15
Source File: DefaultProvisioningHandler.java    From carbon-identity-framework with Apache License 2.0 5 votes vote down vote up
/**
 * Retrieve the list of roles to be deleted.
 *
 * @param realm            user realm
 * @param currentRolesList current role list of the user
 * @param rolesToAdd       roles that are about to be added
 * @return roles to be deleted
 * @throws UserStoreException When failed to get realm configuration
 */
protected List<String> retrieveRolesToBeDeleted(UserRealm realm, List<String> currentRolesList,
                                                List<String> rolesToAdd) throws UserStoreException {

    List<String> deletingRoles = new ArrayList<String>();
    deletingRoles.addAll(currentRolesList);

    // deletingRoles = currentRolesList - rolesToAdd
    deletingRoles.removeAll(rolesToAdd);

    // Exclude Internal/everyonerole from deleting role since its cannot be deleted
    deletingRoles.remove(realm.getRealmConfiguration().getEveryOneRoleName());

    return deletingRoles;
}
 
Example #16
Source File: OpenIDProviderService.java    From carbon-identity with Apache License 2.0 5 votes vote down vote up
/**
 * Get Profile details of an user
 *
 * @param openId
 * @return
 * @throws IdentityProviderException
 */
public OpenIDUserProfileDTO[] getUserProfiles(String openId, OpenIDParameterDTO[] requredClaims)
        throws IdentityProviderException {
    String userName = null;
    UserRealm realm = null;
    UserStoreManager reader = null;
    String tenatUser = null;
    String domainName = null;

    try {
        userName = OpenIDUtil.getUserName(openId);
        tenatUser = MultitenantUtils.getTenantAwareUsername(userName);
        domainName = MultitenantUtils.getDomainNameFromOpenId(openId);
        realm = IdentityTenantUtil.getRealm(domainName, userName);
        reader = realm.getUserStoreManager();
        String[] profileNames = reader.getProfileNames(tenatUser);
        OpenIDUserProfileDTO[] profileDtoSet = new OpenIDUserProfileDTO[profileNames.length];

        List<String> claimList = null;
        ParameterList paramList = getParameterList(requredClaims);
        AuthRequest authReq =
                AuthRequest.createAuthRequest(paramList, OpenIDProvider.getInstance()
                                                                       .getManager()
                                                                       .getRealmVerifier());

        claimList = getRequestedAttributes(authReq);

        for (int i = 0; i < profileNames.length; i++) {
            OpenIDUserProfileDTO profileDTO = new OpenIDUserProfileDTO();
            OpenIDClaimDTO[] claimSet =
                    getOpenIDClaimValues(openId, profileNames[i], claimList);
            profileDTO.setProfileName(profileNames[i]);
            profileDTO.setClaimSet(claimSet);
            profileDtoSet[i] = profileDTO;
        }
        return profileDtoSet;
    } catch (MalformedURLException | UserStoreException | MessageException | IdentityException e) {
        throw new IdentityProviderException("Error while retrieving user profiles", e);
    }
}
 
Example #17
Source File: UserRegistrationService.java    From carbon-identity with Apache License 2.0 5 votes vote down vote up
public boolean isAddUserEnabled() throws Exception {

        UserRealm userRealm = IdentityTenantUtil.getRealm(null, null);
        if (userRealm != null) {
            UserStoreManager userStoreManager = userRealm.getUserStoreManager();
            if (userStoreManager != null) {
                return !userStoreManager.isReadOnly();
            }
        }
        return false;
    }
 
Example #18
Source File: SystemRolesRetainedProvisionHandler.java    From carbon-identity-framework with Apache License 2.0 5 votes vote down vote up
@Override
protected List<String> retrieveRolesToBeDeleted(UserRealm realm, List<String> currentRolesList,
                                                List<String> rolesToAdd) throws UserStoreException {

    List<String> deletingRoles = super.retrieveRolesToBeDeleted(realm, currentRolesList, rolesToAdd);

    // Remove all internal roles from deleting list
    deletingRoles.removeAll(extractInternalRoles(currentRolesList));

    return deletingRoles;
}
 
Example #19
Source File: UserRegistrationService.java    From carbon-identity-framework with Apache License 2.0 5 votes vote down vote up
public UserFieldDTO[] readUserFieldsForUserRegistration(String dialect)
        throws IdentityException {

    IdentityClaimManager claimManager = null;
    Claim[] claims = null;
    List<UserFieldDTO> claimList = null;
    UserRealm realm = null;

    claimManager = IdentityClaimManager.getInstance();
    realm = IdentityTenantUtil.getRealm(null, null);
    claims = claimManager.getAllSupportedClaims(dialect, realm);

    if (claims == null || claims.length == 0) {
        return new UserFieldDTO[0];
    }

    claimList = new ArrayList<UserFieldDTO>();

    for (Claim claim : claims) {
        if (claim.getDisplayTag() != null
                && !IdentityConstants.PPID_DISPLAY_VALUE.equals(claim.getDisplayTag())) {
            if (UserCoreConstants.ClaimTypeURIs.ACCOUNT_STATUS.equals(claim.getClaimUri())) {
                continue;
            }
            if (!claim.isReadOnly()) {
                claimList.add(getUserFieldDTO(claim.getClaimUri(), claim.getDisplayTag(), claim.isRequired(),
                        claim.getDisplayOrder(), claim.getRegEx(), claim.isSupportedByDefault()));
            }
        }
    }
    return claimList.toArray(new UserFieldDTO[claimList.size()]);
}
 
Example #20
Source File: UserProfileAdmin.java    From carbon-identity-framework with Apache License 2.0 5 votes vote down vote up
private Claim[] getClaimsToEnterData(UserRealm realm)
        throws UserStoreException {
    try {
        return getAllSupportedClaims(realm, UserCoreConstants.DEFAULT_CARBON_DIALECT);
    } catch (org.wso2.carbon.user.api.UserStoreException e) {
        throw new UserStoreException(e);
    }
}
 
Example #21
Source File: DirectoryServerManager.java    From carbon-identity with Apache License 2.0 5 votes vote down vote up
private LDAPServerStoreManager getServerStoreManager() throws DirectoryServerManagerException {
    UserRealm realm = this.getUserRealm();
    RealmConfiguration configuration;
    try {
        configuration = realm.getRealmConfiguration();
    } catch (UserStoreException e) {
        throw new DirectoryServerManagerException("Unable to retrieve realm configuration.", e);
    }

    return new LDAPServerStoreManager(configuration);
}
 
Example #22
Source File: UserProfileAdmin.java    From carbon-identity with Apache License 2.0 5 votes vote down vote up
public boolean isReadOnlyUserStore() throws UserProfileException {
    try {
        UserRealm realm = getUserRealm();
        if ("true".equals(realm.getRealmConfiguration().getUserStoreProperty(
                UserCoreConstants.RealmConfig.PROPERTY_READ_ONLY))) {
            return true;
        }
        return false;
    } catch (UserStoreException e) {
        log.error(e.getMessage(), e);
        throw new UserProfileException(e.getMessage(), e);
    }
}
 
Example #23
Source File: SelfSignupUtilTestCase.java    From carbon-apimgt with 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 #24
Source File: UserAdmin.java    From carbon-identity-framework with Apache License 2.0 5 votes vote down vote up
/**
 * Get list of users which have given permission
 *
 * @param filter     filter to check
 * @param permission permission to check
 * @param limit
 * @return
 * @throws UserAdminException
 */
public FlaggedName[] listAllUsersWithPermission(String filter, String permission, int limit) throws
        UserAdminException {

    List<FlaggedName> permittedUsers = new ArrayList<>();
    try {
        org.wso2.carbon.user.api.UserRealm realm = UserMgtDSComponent.getRealmService().getTenantUserRealm
                (PrivilegedCarbonContext.getThreadLocalCarbonContext().getTenantId());
        AuthorizationManager authorizationManager = realm.getAuthorizationManager();


        FlaggedName[] users = getUserAdminProxy().listAllUsers(filter, limit);

        for (int i = 0; i < users.length - 1; i++) {
            if (authorizationManager.isUserAuthorized(users[i].getItemName(),
                    permission, UserMgtConstants.EXECUTE_ACTION)) {
                permittedUsers.add(users[i]);
            }
        }
        permittedUsers.add(users[users.length - 1]);
    } catch (org.wso2.carbon.user.api.UserStoreException e) {
        throw new UserAdminException("Error while filtering authorized users.", e);
    }
    FlaggedName[] permittedUsersArray = new FlaggedName[permittedUsers.size()];
    return permittedUsers.toArray(permittedUsersArray);

}
 
Example #25
Source File: WSRealmBuilder.java    From carbon-identity with Apache License 2.0 5 votes vote down vote up
/**
 * Method to create WSRealm for non-Carbon environment
 * Recommended method
 */
public static UserRealm createWSRealm(String serverUrl, String cookie, ConfigurationContext configContext)
        throws UserStoreException {

    WSRealm realm = new WSRealm();
    realm.init(serverUrl, cookie, configContext);
    return realm;
}
 
Example #26
Source File: IdentityUserProfileServiceComponent.java    From carbon-identity-framework with Apache License 2.0 5 votes vote down vote up
@Reference(
         name = "user.realm.default", 
         service = org.wso2.carbon.user.core.UserRealm.class, 
         cardinality = ReferenceCardinality.MANDATORY, 
         policy = ReferencePolicy.DYNAMIC, 
         unbind = "unsetUserRealmDefault")
protected void setUserRealmDefault(UserRealm userRealmDefault) {
    if (log.isDebugEnabled()) {
        log.debug("Setting DefaultRealm in User Profile Management");
    }
    ServiceHodler.setInternalUserStore(userRealmDefault);
}
 
Example #27
Source File: UserProfileUtil.java    From carbon-identity-framework with 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 + "/manage/identity/usermgt/profiles",
                "ui.execute");
    }
    return isAuthrized;
}
 
Example #28
Source File: UserProfileAdmin.java    From carbon-identity-framework with Apache License 2.0 5 votes vote down vote up
public boolean isReadOnlyUserStore() throws UserProfileException {
    try {
        UserRealm realm = getUserRealm();
        if ("true".equals(realm.getRealmConfiguration().getUserStoreProperty(
                UserCoreConstants.RealmConfig.PROPERTY_READ_ONLY))) {
            return true;
        }
        return false;
    } catch (UserStoreException e) {
        log.error(e.getMessage(), e);
        throw new UserProfileException(e.getMessage(), e);
    }
}
 
Example #29
Source File: SecurityPersistenceUtils.java    From carbon-identity with Apache License 2.0 5 votes vote down vote up
/**
 * @param serviceGroupId      serviceGroupId
 * @param serviceId           serviceId
 * @param realm               realm
 * @param tenantAwareUserName tenantAwareUserName
 * @param permissionType      Probably UserCoreConstants.INVOKE_SERVICE_PERMISSION is all you need for this
 * @param serviceGroupFilePM  serviceGroupFilePM
 * @return false if any of the roles of user does not have permission to access it or no roles assigned for the service.
 * @throws UserStoreException
 * @deprecated do not use this method
 */
public static boolean isUserAuthorized(
        String serviceGroupId, String serviceId, UserRealm realm, String tenantAwareUserName, String permissionType,
        ServiceGroupFilePersistenceManager serviceGroupFilePM) throws UserStoreException {
    try {
        String[] rolesList = realm.getUserStoreManager().getRoleListOfUser(tenantAwareUserName);

        String serviceXPath = Resources.ServiceProperties.ROOT_XPATH + PersistenceUtils.
                getXPathAttrPredicate(Resources.NAME, serviceId);
        String rolesPath = serviceXPath +
                "/" + Resources.SecurityManagement.ROLE_XML_TAG +
                PersistenceUtils.getXPathAttrPredicate(
                        Resources.Associations.TYPE, permissionType) +
                "/@" + Resources.SecurityManagement.ROLENAME_XML_ATTR;

        List tmpAllowedRolesAttr = serviceGroupFilePM.getAll(serviceGroupId, rolesPath);
        List<String> allowedRoles = new ArrayList<>(tmpAllowedRolesAttr.size());
        for (Object attr : tmpAllowedRolesAttr) {
            allowedRoles.add(((OMAttribute) attr).getAttributeValue());
        }

        for (String role : rolesList) {
            if (allowedRoles.contains(role)) {
                return true;
            }
        }
        return false;
    } catch (PersistenceDataNotFoundException e) {
        log.error("Error occurred while reading allowed roles element. Returning false.", e);
        return false;
    }
}
 
Example #30
Source File: StratosManagerServiceComponent.java    From attic-stratos with Apache License 2.0 5 votes vote down vote up
/**
 * Create internal user role if not exists.
 *
 * @param componentContext
 * @throws UserStoreException
 * @throws UserManagerException
 */
private void createInternalUserRole(ComponentContext componentContext)
        throws UserStoreException, UserManagerException {
    RealmService realmService = ServiceReferenceHolder.getRealmService();
    UserRealm realm = realmService.getBootstrapRealm();
    UserStoreManager userStoreManager = realm.getUserStoreManager();
    UserRoleCreator.createInternalUserRole(userStoreManager);

    TenantUserRoleManager tenantUserRoleManager = new TenantUserRoleManager();
    componentContext.getBundleContext()
            .registerService(org.wso2.carbon.stratos.common.listeners.TenantMgtListener.class.getName(),
                    tenantUserRoleManager, null);
}