Java Code Examples for org.wso2.carbon.user.core.service.RealmService#getTenantUserRealm()

The following examples show how to use org.wso2.carbon.user.core.service.RealmService#getTenantUserRealm() . 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: JsClaims.java    From carbon-identity-framework with Apache License 2.0 6 votes vote down vote up
/**
 * Get the local user claim value specified by the Claim URI.
 *
 * @param claimUri Local claim URI
 * @return Claim value of the given claim URI for the local user if available. Null Otherwise.
 */
private String getLocalUserClaim(String claimUri) {

    int usersTenantId = IdentityTenantUtil.getTenantId(authenticatedUser.getTenantDomain());
    String usernameWithDomain = UserCoreUtil.addDomainToName(authenticatedUser.getUserName(), authenticatedUser
        .getUserStoreDomain());
    RealmService realmService = FrameworkServiceDataHolder.getInstance().getRealmService();
    try {
        UserRealm userRealm = realmService.getTenantUserRealm(usersTenantId);
        Map<String, String> claimValues = userRealm.getUserStoreManager().getUserClaimValues(usernameWithDomain, new
            String[]{claimUri}, null);
        return claimValues.get(claimUri);
    } catch (UserStoreException e) {
        LOG.error(String.format("Error when getting claim : %s of user: %s", claimUri, authenticatedUser), e);
    }
    return null;
}
 
Example 2
Source File: CarbonUserRealmHostObject.java    From carbon-commons with Apache License 2.0 6 votes vote down vote up
public static boolean jsFunction_isUserAuthorized(Context cx,
		Scriptable thisObj, Object[] args, Function funObj) throws Exception {
	boolean isAuthorized = false;
	int argLength = args.length;
	if (argLength != 3) {
		throw new ScriptException("Invalid arguments.");
	}
	String user = (String) args[0];
	String userName = MultitenantUtils.getTenantAwareUsername(user);
	String domainName = MultitenantUtils.getTenantDomain(user);
	RealmService service = ServiceHodler.getRealmService();
	int tenantId = service.getTenantManager().getTenantId(domainName);
	UserRealm realm = service.getTenantUserRealm(tenantId);
	isAuthorized = realm.getAuthorizationManager().isUserAuthorized(userName, (String) args[1], (String) args[2]);
	return isAuthorized;
}
 
Example 3
Source File: JsClaims.java    From carbon-identity-framework with Apache License 2.0 6 votes vote down vote up
/**
 * Sets a local claim directly at the userstore for the given user by given claim uri
 *
 * @param claimUri   Local claim URI
 * @param claimValue Claim value
 */
private void setLocalUserClaim(String claimUri, Object claimValue) {

    int usersTenantId = IdentityTenantUtil.getTenantId(authenticatedUser.getTenantDomain());
    RealmService realmService = FrameworkServiceDataHolder.getInstance().getRealmService();
    String usernameWithDomain = UserCoreUtil.addDomainToName(authenticatedUser.getUserName(), authenticatedUser
        .getUserStoreDomain());
    try {
        UserRealm userRealm = realmService.getTenantUserRealm(usersTenantId);
        Map<String, String> claimUriMap = new HashMap<>();
        claimUriMap.put(claimUri, String.valueOf(claimValue));
        userRealm.getUserStoreManager().setUserClaimValues(usernameWithDomain, claimUriMap, null);
    } catch (UserStoreException e) {
        LOG.error(String.format("Error when setting claim : %s of user: %s to value: %s", claimUri,
                authenticatedUser, String.valueOf(claimValue)), e);
    }
}
 
Example 4
Source File: JsAuthenticatedUser.java    From carbon-identity-framework with Apache License 2.0 6 votes vote down vote up
private String[] getLocalRoles() {

        if (idp == null || FrameworkConstants.LOCAL.equals(idp)) {
            RealmService realmService = FrameworkServiceDataHolder.getInstance().getRealmService();
            int usersTenantId = IdentityTenantUtil.getTenantId(getWrapped().getTenantDomain());

            try {
                String usernameWithDomain = UserCoreUtil.addDomainToName(getWrapped().getUserName(), getWrapped()
                    .getUserStoreDomain());
                UserRealm userRealm = realmService.getTenantUserRealm(usersTenantId);
                return userRealm.getUserStoreManager().getRoleListOfUser(usernameWithDomain);
            } catch (UserStoreException e) {
                LOG.error("Error when getting role list of user: " + getWrapped(), e);
            }
        }
        return ArrayUtils.EMPTY_STRING_ARRAY;
    }
 
Example 5
Source File: DeleteRoleWFRequestHandler.java    From carbon-identity with Apache License 2.0 5 votes vote down vote up
@Override
public void onWorkflowCompletion(String status, Map<String, Object> requestParams,
                                 Map<String, Object> responseAdditionalParams, int tenantId)
        throws WorkflowException {
    String roleName = (String) requestParams.get(ROLENAME);
    if (roleName == null) {
        throw new WorkflowException("Callback request for delete role received without the mandatory " +
                "parameter 'username'");
    }

    String userStoreDomain = (String) requestParams.get(USER_STORE_DOMAIN);
    if (StringUtils.isNotBlank(userStoreDomain)) {
        roleName = userStoreDomain + "/" + roleName;
    }

    if (WorkflowRequestStatus.APPROVED.toString().equals(status) ||
            WorkflowRequestStatus.SKIPPED.toString().equals(status)) {
        try {
            RealmService realmService = IdentityWorkflowDataHolder.getInstance().getRealmService();
            UserRealm userRealm = realmService.getTenantUserRealm(tenantId);
            userRealm.getUserStoreManager().deleteRole(roleName);
        } catch (UserStoreException e) {
            // Sending e.getMessage() since it is required to give error message to end user.
            throw new WorkflowException(e.getMessage(), e);
        }
    } else {
        if (retryNeedAtCallback()) {
            //unset threadlocal variable
            unsetWorkFlowCompleted();
        }
        if (log.isDebugEnabled()) {
            log.debug("Deleting role is aborted for role '" + roleName + "', Reason: Workflow response was " +
                    status);
        }
    }
}
 
Example 6
Source File: DeleteUserWFRequestHandler.java    From carbon-identity with Apache License 2.0 5 votes vote down vote up
@Override
public void onWorkflowCompletion(String status, Map<String, Object> requestParams,
                                 Map<String, Object> responseAdditionalParams, int tenantId)
        throws WorkflowException {
    String userName;
    Object requestUsername = requestParams.get(USERNAME);
    if (requestUsername == null || !(requestUsername instanceof String)) {
        throw new WorkflowException("Callback request for delete user received without the mandatory " +
                "parameter 'username'");
    }
    String userStoreDomain = (String) requestParams.get(USER_STORE_DOMAIN);
    if (StringUtils.isNotBlank(userStoreDomain)) {
        userName = userStoreDomain + "/" + requestUsername;
    } else {
        userName = (String) requestUsername;
    }

    if (WorkflowRequestStatus.APPROVED.toString().equals(status) ||
            WorkflowRequestStatus.SKIPPED.toString().equals(status)) {
        try {
            RealmService realmService = IdentityWorkflowDataHolder.getInstance().getRealmService();
            UserRealm userRealm = realmService.getTenantUserRealm(tenantId);
            userRealm.getUserStoreManager().deleteUser(userName);
        } catch (UserStoreException e) {
            // Sending e.getMessage() since it is required to give error message to end user.
            throw new WorkflowException(e.getMessage(), e);
        }
    } else {
        if (retryNeedAtCallback()) {
            //unset threadlocal variable
            unsetWorkFlowCompleted();
        }
        if (log.isDebugEnabled()) {
            log.debug("Deleting user is aborted for user '" + userName + "', Reason: Workflow response was " +
                    status);
        }
    }
}
 
Example 7
Source File: ChangeCredentialWFRequestHandler.java    From carbon-identity with Apache License 2.0 4 votes vote down vote up
@Override
public void onWorkflowCompletion(String status, Map<String, Object> requestParams,
                                 Map<String, Object> responseAdditionalParams, int tenantId)
        throws WorkflowException {
    String userName;
    Object requestUsername = requestParams.get(USERNAME);
    if (requestUsername == null || !(requestUsername instanceof String)) {
        throw new WorkflowException("Callback request for update credential without the mandatory " +
                "parameter 'username'");
    }
    String userStoreDomain = (String) requestParams.get(USER_STORE_DOMAIN);
    if (StringUtils.isNotBlank(userStoreDomain)) {
        userName = userStoreDomain + "/" + requestUsername;
    } else {
        userName = (String) requestUsername;
    }

    Object oldCredential = requestParams.get(OLD_CREDENTIAL);
    Object newCredential = requestParams.get(NEW_CREDENTIAL);
    if (WorkflowRequestStatus.APPROVED.toString().equals(status) ||
            WorkflowRequestStatus.SKIPPED.toString().equals(status)) {
        try {
            RealmService realmService = IdentityWorkflowDataHolder.getInstance().getRealmService();
            UserRealm userRealm = realmService.getTenantUserRealm(tenantId);
            userRealm.getUserStoreManager().updateCredential(userName, newCredential, oldCredential);
        } catch (UserStoreException e) {
            // Sending e.getMessage() since it is required to give error message to end user.
            throw new WorkflowException(e.getMessage(), e);
        }
    } else {
        if (retryNeedAtCallback()) {
            //unset threadlocal variable
            unsetWorkFlowCompleted();
        }
        if (log.isDebugEnabled()) {
            log.debug(
                    "Updating credentials for user '" + userName + "', Reason: Workflow response" + " was " +
                            status);
        }
    }

}
 
Example 8
Source File: UserSignUpWorkflowExecutor.java    From carbon-apimgt with Apache License 2.0 4 votes vote down vote up
/**
 * Method updates Roles users with list of roles
 * @param serverURL
 * @param adminUsername
 * @param adminPassword
 * @param userName
 * @param tenantID
 * @param role
 * @throws Exception
 */
protected static void updateRolesOfUser(String serverURL, String adminUsername,
                                        String adminPassword, String userName,
                                        List<String> roleList, String tenantDomain)
                                        		throws Exception {

	if (log.isDebugEnabled()) {
		log.debug("Adding roles to " + userName + "in " + tenantDomain + " Domain");
	}
	String url = serverURL + "UserAdmin";
	RealmService realmService = ServiceReferenceHolder.getInstance().getRealmService();
	int tenantId = ServiceReferenceHolder.getInstance().getRealmService().getTenantManager()
			.getTenantId(tenantDomain);
	UserRealm realm = (UserRealm) realmService.getTenantUserRealm(tenantId);
	UserStoreManager manager = realm.getUserStoreManager();
	
	if(manager.isExistingUser(userName)) {
		// check whether given roles exist
		for (String role : roleList) {
			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.addAll(roleList);
		userAdminStub.updateRolesOfUser(userName, roles.toArray(new String[roles.size()]));
	} else {
		log.error("User does not exist. Unable to approve user " + userName);
	} 
	
}
 
Example 9
Source File: PermissionBasedScopeIssuer.java    From carbon-apimgt with Apache License 2.0 4 votes vote down vote up
/**
 * This method is used to get the authorized scopes out of requested scopes. It checks requested scopes with app
 * scopes whether user has permissions to take actions for the requested scopes.
 *
 * @param authenticatedUser Authenticated user.
 * @param reqScopeList      Requested scope list.
 * @param appScopes         App scopes.
 * @return Returns a list of scopes.
 */
private List<String> getAuthorizedScopes(AuthenticatedUser authenticatedUser, List<String> reqScopeList,
                                         Map<String, String> appScopes, List<String> whiteListedScopes) {

    boolean status;
    List<String> authorizedScopes = new ArrayList<>();
    int tenantId;
    String username = authenticatedUser.getUserName();
    String tenantDomain = authenticatedUser.getTenantDomain();
    RealmService realmService = getRealmService();
    List<String> defaultScope = new ArrayList<>();
    defaultScope.add(DEFAULT_SCOPE_NAME);

    try {
        tenantId = realmService.getTenantManager().getTenantId(tenantDomain);

        // If tenant Id is not set in the tokenReqContext, deriving it from username.
        if (tenantId == 0 || tenantId == -1) {
            tenantId = getTenantIdOfUser(username);
        }

        UserRealm userRealm = realmService.getTenantUserRealm(tenantId);

        //Iterate the requested scopes list.
        for (String scope : reqScopeList) {
            status = false;

            //Get the set of roles associated with the requested scope.
            String appPermissions = appScopes.get(scope);

            //If the scope has been defined in the context of the App and if permissions have been defined for
            // the scope
            if (appPermissions != null && appPermissions.length() != 0) {
                List<String> permissions = new ArrayList<>(Arrays.asList(appPermissions
                        .replaceAll(" ", "").split(",")));

                //Check if user has at least one of the permission associated with the scope
                if (!permissions.isEmpty()) {
                    for (String permission : permissions) {
                        if (userRealm != null && userRealm.getAuthorizationManager() != null) {
                            String userStore = authenticatedUser.getUserStoreDomain();
                            username = MultitenantUtils.getTenantAwareUsername(username);
                            if (userStore != null) {
                                status = userRealm.getAuthorizationManager()
                                        .isUserAuthorized(userStore + "/" + username, permission, UI_EXECUTE);
                            } else {
                                status = userRealm.getAuthorizationManager()
                                        .isUserAuthorized(username, permission, UI_EXECUTE);
                            }
                            if (status) {
                                break;
                            }
                        }
                    }
                    if (status) {
                        authorizedScopes.add(scope);
                    }
                }
            }

            //The scope string starts with 'device_'.
            else if (appScopes.containsKey(scope) || isWhiteListedScope(whiteListedScopes, scope)) {
                authorizedScopes.add(scope);
            }
        }
    } catch (UserStoreException e) {
        log.error("Error occurred while initializing user store.", e);
    }
    return (!authorizedScopes.isEmpty()) ? authorizedScopes : defaultScope;
}
 
Example 10
Source File: DeleteClaimWFRequestHandler.java    From carbon-identity with Apache License 2.0 4 votes vote down vote up
@Override
public void onWorkflowCompletion(String status, Map<String, Object> requestParams,
                                 Map<String, Object> responseAdditionalParams, int tenantId)
        throws WorkflowException {
    String userName;
    Object requestUsername = requestParams.get(USERNAME);
    if (requestUsername == null || !(requestUsername instanceof String)) {
        throw new WorkflowException("Callback request for Set User Claim received without the mandatory " +
                "parameter 'username'");
    }
    String userStoreDomain = (String) requestParams.get(USER_STORE_DOMAIN);
    if (StringUtils.isNotBlank(userStoreDomain)) {
        userName = userStoreDomain + "/" + requestUsername;
    } else {
        userName = (String) requestUsername;
    }

    String claimURI = (String) requestParams.get(CLAIM_URI);
    String profile = (String) requestParams.get(PROFILE_NAME);

    if (WorkflowRequestStatus.APPROVED.toString().equals(status) ||
            WorkflowRequestStatus.SKIPPED.toString().equals(status)) {
        try {
            RealmService realmService = IdentityWorkflowDataHolder.getInstance().getRealmService();
            UserRealm userRealm = realmService.getTenantUserRealm(tenantId);
            userRealm.getUserStoreManager().deleteUserClaimValue(userName, claimURI, profile);
        } catch (UserStoreException e) {
            // Sending e.getMessage() since it is required to give error message to end user.
            throw new WorkflowException(e.getMessage(), e);
        }
    } else {
        if (retryNeedAtCallback()) {
            //unset threadlocal variable
            unsetWorkFlowCompleted();
        }
        if (log.isDebugEnabled()) {
            log.debug("Deleting User Claim is aborted for user '" + userName + "', ClaimURI:" + claimURI +
                    ", Reason: Workflow response was " + status);
        }
    }
}
 
Example 11
Source File: UpdateRoleUsersWFRequestHandler.java    From carbon-identity with Apache License 2.0 4 votes vote down vote up
@Override
public void onWorkflowCompletion(String status, Map<String, Object> requestParams, Map<String, Object>
        responseAdditionalParams, int tenantId) throws WorkflowException {

    String roleName = (String) requestParams.get(ROLENAME);
    if (roleName == null) {
        throw new WorkflowException("Callback request for Add User received without the mandatory " +
                "parameter 'username'");
    }
    String userStoreDomain = (String) requestParams.get(USER_STORE_DOMAIN);
    if (StringUtils.isNotBlank(userStoreDomain)) {
        roleName = userStoreDomain + "/" + roleName;
    }

    List<String> deletedUserList = ((List<String>) requestParams.get(DELETED_USER_LIST));
    String[] deletedUsers;
    if (deletedUserList != null) {
        deletedUsers = new String[deletedUserList.size()];
        deletedUsers = deletedUserList.toArray(deletedUsers);
    } else {
        deletedUsers = new String[0];
    }

    List<String> newUserList = ((List<String>) requestParams.get(NEW_USER_LIST));
    String[] newUsers;
    if (newUserList != null) {
        newUsers = new String[newUserList.size()];
        newUsers = newUserList.toArray(newUsers);
    } else {
        newUsers = new String[0];
    }

    if (WorkflowRequestStatus.APPROVED.toString().equals(status) ||
            WorkflowRequestStatus.SKIPPED.toString().equals(status)) {
        try {
            RealmService realmService = IdentityWorkflowDataHolder.getInstance().getRealmService();
            UserRealm userRealm = realmService.getTenantUserRealm(tenantId);
            userRealm.getUserStoreManager().updateUserListOfRole(roleName, deletedUsers, newUsers);
        } catch (UserStoreException e) {
            // Sending e.getMessage() since it is required to give error message to end user.
            throw new WorkflowException(e.getMessage(), e);
        }
    } else {
        if (retryNeedAtCallback()) {
            //unset threadlocal variable
            unsetWorkFlowCompleted();
        }
        if (log.isDebugEnabled()) {
            log.debug(
                    "Updating role users is aborted for role '" + roleName + "', Reason: Workflow response was " +
                            status);
        }
    }
}
 
Example 12
Source File: AddRoleWFRequestHandler.java    From carbon-identity with Apache License 2.0 4 votes vote down vote up
@Override
public void onWorkflowCompletion(String status, Map<String, Object> requestParams, Map<String, Object>
        responseAdditionalParams, int tenantId) throws WorkflowException {

    String roleName = (String) requestParams.get(ROLENAME);
    if (roleName == null) {
        throw new WorkflowException("Callback request for Add role received without the mandatory " +
                "parameter 'roleName'");
    }

    String userStoreDomain = (String) requestParams.get(USER_STORE_DOMAIN);
    if (StringUtils.isNotBlank(userStoreDomain)) {
        roleName = userStoreDomain + "/" + roleName;
    }

    List<String> userList = (List<String>) requestParams.get(USER_LIST);
    String[] users;
    if (userList != null) {
        users = new String[userList.size()];
        users = userList.toArray(users);
    } else {
        users = new String[0];
    }

    List<String> permissionList = (List<String>) requestParams.get(PERMISSIONS);
    Permission[] permissions;
    if (permissionList != null) {
        permissions = new Permission[permissionList.size()];
        int i = 0;
        for (String permissionString : permissionList) {
            String[] splittedString = permissionString.split(SEPARATOR);
            if (splittedString.length == 2) {
                permissions[i] = new Permission(splittedString[0], splittedString[1]);
            }
            i++;
        }
    } else {
        permissions = new Permission[0];
    }

    if (WorkflowRequestStatus.APPROVED.toString().equals(status) ||
            WorkflowRequestStatus.SKIPPED.toString().equals(status)) {
        try {
            RealmService realmService = IdentityWorkflowDataHolder.getInstance().getRealmService();
            UserRealm userRealm = realmService.getTenantUserRealm(tenantId);
            userRealm.getUserStoreManager().addRole(roleName, users, permissions);
        } catch (UserStoreException e) {
            // Sending e.getMessage() since it is required to give error message to end user.
            throw new WorkflowException(e.getMessage(), e);
        }
    } else {
        if (retryNeedAtCallback()) {
            //unset threadlocal variable
            unsetWorkFlowCompleted();
        }
        if (log.isDebugEnabled()) {
            log.debug(
                    "Adding role is aborted for role '" + roleName + "', Reason: Workflow response was " + status);
        }
    }
}
 
Example 13
Source File: DeleteMultipleClaimsWFRequestHandler.java    From carbon-identity with Apache License 2.0 4 votes vote down vote up
@Override
public void onWorkflowCompletion(String status, Map<String, Object> requestParams,
                                 Map<String, Object> responseAdditionalParams, int tenantId)
        throws WorkflowException {
    String userName;
    Object requestUsername = requestParams.get(USERNAME);
    if (requestUsername == null || !(requestUsername instanceof String)) {
        throw new WorkflowException("Callback request for Set User Claim received without the mandatory " +
                "parameter 'username'");
    }
    String userStoreDomain = (String) requestParams.get(USER_STORE_DOMAIN);
    if (StringUtils.isNotBlank(userStoreDomain)) {
        userName = userStoreDomain + "/" + requestUsername;
    } else {
        userName = (String) requestUsername;
    }

    List<String> claims = (List<String>) requestParams.get(CLAIMS);
    String profile = (String) requestParams.get(PROFILE_NAME);

    if (WorkflowRequestStatus.APPROVED.toString().equals(status) ||
            WorkflowRequestStatus.SKIPPED.toString().equals(status)) {
        try {
            RealmService realmService = IdentityWorkflowDataHolder.getInstance().getRealmService();
            UserRealm userRealm = realmService.getTenantUserRealm(tenantId);
            userRealm.getUserStoreManager().deleteUserClaimValues(userName,
                    claims.toArray(new String[claims.size()]), profile);
        } catch (UserStoreException e) {
            // Sending e.getMessage() since it is required to give error message to end user.
            throw new WorkflowException(e.getMessage(), e);
        }
    } else {
        if (retryNeedAtCallback()) {
            //unset threadlocal variable
            unsetWorkFlowCompleted();
        }
        if (log.isDebugEnabled()) {
            log.debug("Deleting User Claims is aborted for user '" + userName + "', Reason: Workflow response " +
                    "was: " + status);
        }
    }
}
 
Example 14
Source File: SetUserClaimWFRequestHandler.java    From carbon-identity with Apache License 2.0 4 votes vote down vote up
@Override
public void onWorkflowCompletion(String status, Map<String, Object> requestParams,
                                 Map<String, Object> responseAdditionalParams, int tenantId)
        throws WorkflowException {
    String userName;
    Object requestUsername = requestParams.get(USERNAME);
    if (requestUsername == null || !(requestUsername instanceof String)) {
        throw new WorkflowException("Callback request for Set User Claim received without the mandatory " +
                "parameter 'username'");
    }
    String userStoreDomain = (String) requestParams.get(USER_STORE_DOMAIN);
    if (StringUtils.isNotBlank(userStoreDomain)) {
        userName = userStoreDomain + "/" + requestUsername;
    } else {
        userName = (String) requestUsername;
    }

    String claimURI = (String) requestParams.get(CLAIM_URI);
    String claimValue = (String) requestParams.get(CLAIM_VALUE);
    String profile = (String) requestParams.get(PROFILE_NAME);

    if (WorkflowRequestStatus.APPROVED.toString().equals(status) ||
            WorkflowRequestStatus.SKIPPED.toString().equals(status)) {
        try {
            RealmService realmService = IdentityWorkflowDataHolder.getInstance().getRealmService();
            UserRealm userRealm = realmService.getTenantUserRealm(tenantId);
            userRealm.getUserStoreManager().setUserClaimValue(userName, claimURI, claimValue, profile);
        } catch (UserStoreException e) {
            // Sending e.getMessage() since it is required to give error message to end user.
            throw new WorkflowException(e.getMessage(), e);
        }
    } else {
        if (retryNeedAtCallback()) {
            //unset threadlocal variable
            unsetWorkFlowCompleted();
        }
        if (log.isDebugEnabled()) {
            log.debug("Setting User Claim is aborted for user '" + userName + "', ClaimURI:" + claimURI + " " +
                    "ClaimValue:" + claimValue + ", Reason: Workflow response was " + status);
        }
    }
}
 
Example 15
Source File: UpdateRoleNameWFRequestHandler.java    From carbon-identity with Apache License 2.0 4 votes vote down vote up
@Override
public void onWorkflowCompletion(String status, Map<String, Object> requestParams,
                                 Map<String, Object> responseAdditionalParams, int tenantId)
        throws WorkflowException {
    String roleName = (String) requestParams.get(ROLENAME);
    String newRoleName = (String) requestParams.get(NEW_ROLENAME);
    if (roleName == null) {
        throw new WorkflowException("Callback request for rename role received without the mandatory " +
                "parameter 'roleName'");
    }
    if (newRoleName == null) {
        throw new WorkflowException("Callback request for rename role received without the mandatory " +
                "parameter 'newRoleName'");
    }

    String userStoreDomain = (String) requestParams.get(USER_STORE_DOMAIN);
    if (StringUtils.isNotBlank(userStoreDomain)) {
        roleName = userStoreDomain + "/" + roleName;
        newRoleName = userStoreDomain + "/" + newRoleName;
    }

    if (WorkflowRequestStatus.APPROVED.toString().equals(status) ||
            WorkflowRequestStatus.SKIPPED.toString().equals(status)) {
        try {
            RealmService realmService = IdentityWorkflowDataHolder.getInstance().getRealmService();
            UserRealm userRealm = realmService.getTenantUserRealm(tenantId);
            userRealm.getUserStoreManager().updateRoleName(roleName, newRoleName);
        } catch (UserStoreException e) {
            // Sending e.getMessage() since it is required to give error message to end user.
            throw new WorkflowException(e.getMessage(), e);
        }
    } else {
        if (retryNeedAtCallback()) {
            //unset threadlocal variable
            unsetWorkFlowCompleted();
        }
        if (log.isDebugEnabled()) {
            log.debug("Updating role is aborted for role '" + roleName + "', Reason: Workflow response was " +
                    status);
        }
    }
}
 
Example 16
Source File: UpdateUserRolesWFRequestHandler.java    From carbon-identity with Apache License 2.0 4 votes vote down vote up
@Override
public void onWorkflowCompletion(String status, Map<String, Object> requestParams, Map<String, Object>
        responseAdditionalParams, int tenantId) throws WorkflowException {

    String userName;
    Object requestUsername = requestParams.get(USERNAME);
    if (requestUsername == null || !(requestUsername instanceof String)) {
        throw new WorkflowException("Callback request for Add User received without the mandatory " +
                "parameter 'username'");
    }
    String userStoreDomain = (String) requestParams.get(USER_STORE_DOMAIN);
    if (StringUtils.isNotBlank(userStoreDomain)) {
        userName = userStoreDomain + "/" + requestUsername;
    } else {
        userName = (String) requestUsername;
    }
    List<String> deletedRoleList = ((List<String>) requestParams.get(DELETED_ROLE_LIST));
    String[] deletedRoles;
    if (deletedRoleList != null) {
        deletedRoles = new String[deletedRoleList.size()];
        deletedRoles = deletedRoleList.toArray(deletedRoles);
    } else {
        deletedRoles = new String[0];
    }

    List<String> newRoleList = ((List<String>) requestParams.get(NEW_ROLE_LIST));
    String[] newRoles;
    if (newRoleList != null) {
        newRoles = new String[newRoleList.size()];
        newRoles = newRoleList.toArray(newRoles);
    } else {
        newRoles = new String[0];
    }

    if (WorkflowRequestStatus.APPROVED.toString().equals(status) ||
            WorkflowRequestStatus.SKIPPED.toString().equals(status)) {
        try {
            RealmService realmService = IdentityWorkflowDataHolder.getInstance().getRealmService();
            UserRealm userRealm = realmService.getTenantUserRealm(tenantId);
            userRealm.getUserStoreManager().updateRoleListOfUser(userName, deletedRoles, newRoles);
        } catch (UserStoreException e) {
            // Sending e.getMessage() since it is required to give error message to end user.
            throw new WorkflowException(e.getMessage(), e);
        }
    } else {
        if (retryNeedAtCallback()) {
            //unset threadlocal variable
            unsetWorkFlowCompleted();
        }
        if (log.isDebugEnabled()) {
            log.debug("Updating user roles is aborted for user '" + userName + "', Reason: Workflow response was " +
                    status);
        }
    }
}
 
Example 17
Source File: SetMultipleClaimsWFRequestHandler.java    From carbon-identity with Apache License 2.0 4 votes vote down vote up
@Override
public void onWorkflowCompletion(String status, Map<String, Object> requestParams,
                                 Map<String, Object> responseAdditionalParams, int tenantId)
        throws WorkflowException {
    String userName;
    Object requestUsername = requestParams.get(USERNAME);
    if (requestUsername == null || !(requestUsername instanceof String)) {
        throw new WorkflowException("Callback request for Set User Claim received without the mandatory " +
                "parameter 'username'");
    }
    String userStoreDomain = (String) requestParams.get(USER_STORE_DOMAIN);
    if (StringUtils.isNotBlank(userStoreDomain)) {
        userName = userStoreDomain + "/" + requestUsername;
    } else {
        userName = (String) requestUsername;
    }

    Map<String, String> claims = (Map<String, String>) requestParams.get(CLAIMS);
    String profile = (String) requestParams.get(PROFILE_NAME);

    if (WorkflowRequestStatus.APPROVED.toString().equals(status) ||
            WorkflowRequestStatus.SKIPPED.toString().equals(status)) {
        try {
            RealmService realmService = IdentityWorkflowDataHolder.getInstance().getRealmService();
            UserRealm userRealm = realmService.getTenantUserRealm(tenantId);
            userRealm.getUserStoreManager().setUserClaimValues(userName, claims, profile);
        } catch (UserStoreException e) {
            // Sending e.getMessage() since it is required to give error message to end user.
            throw new WorkflowException(e.getMessage(), e);
        }
    } else {
        if (retryNeedAtCallback()) {
            //unset threadlocal variable
            unsetWorkFlowCompleted();
        }
        if (log.isDebugEnabled()) {
            log.debug("Setting User Claims is aborted for user '" + userName + "', Reason: Workflow response was " +
                    status);
        }
    }
}
 
Example 18
Source File: ClaimMetadataUtils.java    From carbon-identity-framework with Apache License 2.0 4 votes vote down vote up
public static ClaimMapping convertLocalClaimToClaimMapping(LocalClaim localClaim, int tenantId) throws
        UserStoreException {

    ClaimMapping claimMapping = new ClaimMapping();

    Claim claim = new Claim();
    claim.setClaimUri(localClaim.getClaimURI());
    claim.setDialectURI(localClaim.getClaimDialectURI());

    Map<String, String> claimProperties = localClaim.getClaimProperties();

    if (claimProperties.containsKey(ClaimConstants.DISPLAY_NAME_PROPERTY)) {
        claim.setDisplayTag(claimProperties.get(ClaimConstants.DISPLAY_NAME_PROPERTY));
    }

    if (claimProperties.containsKey(ClaimConstants.DESCRIPTION_PROPERTY)) {
        claim.setDescription(claimProperties.get(ClaimConstants.DESCRIPTION_PROPERTY));
    }

    if (claimProperties.containsKey(ClaimConstants.REGULAR_EXPRESSION_PROPERTY)) {
        claim.setRegEx(claimProperties.get(ClaimConstants.REGULAR_EXPRESSION_PROPERTY));
    }

    if (claimProperties.containsKey(ClaimConstants.DISPLAY_ORDER_PROPERTY)) {
        claim.setDisplayOrder(Integer.parseInt(claimProperties.get(ClaimConstants.DISPLAY_ORDER_PROPERTY)));
    }

    if (claimProperties.containsKey(ClaimConstants.SUPPORTED_BY_DEFAULT_PROPERTY)) {
        if ("false".equalsIgnoreCase(claimProperties.get(ClaimConstants.SUPPORTED_BY_DEFAULT_PROPERTY))) {
            claim.setSupportedByDefault(Boolean.FALSE);

        } else {
            claim.setSupportedByDefault(Boolean.TRUE);
        }
    }

    if (claimProperties.containsKey(ClaimConstants.REQUIRED_PROPERTY)) {
        if ("false".equalsIgnoreCase(claimProperties.get(ClaimConstants.REQUIRED_PROPERTY))) {
            claim.setRequired(Boolean.FALSE);

        } else {
            claim.setRequired(Boolean.TRUE);
        }
    }

    if (claimProperties.containsKey(ClaimConstants.READ_ONLY_PROPERTY)) {
        if ("false".equalsIgnoreCase(claimProperties.get(ClaimConstants.READ_ONLY_PROPERTY))) {
            claim.setReadOnly(Boolean.FALSE);

        } else {
            claim.setReadOnly(Boolean.TRUE);
        }
    }

    claimMapping.setClaim(claim);

    List<AttributeMapping> mappedAttributes = localClaim.getMappedAttributes();
    for (AttributeMapping attributeMapping : mappedAttributes) {
        claimMapping.setMappedAttribute(attributeMapping.getUserStoreDomain(), attributeMapping.getAttributeName());
    }

    if (claimProperties.containsKey(ClaimConstants.DEFAULT_ATTRIBUTE)) {
        claimMapping.setMappedAttribute(claimProperties.get(ClaimConstants.DEFAULT_ATTRIBUTE));
    } else {
        RealmService realmService = IdentityClaimManagementServiceDataHolder.getInstance().getRealmService();

        if (realmService != null && realmService.getTenantUserRealm(tenantId) != null) {

            UserRealm realm = realmService.getTenantUserRealm(tenantId);
            String primaryDomainName = realm.getRealmConfiguration().getUserStoreProperty
                    (UserCoreConstants.RealmConfig.PROPERTY_DOMAIN_NAME);
            claimMapping.setMappedAttribute(localClaim.getMappedAttribute(primaryDomainName));
        } else {
            claimMapping.setMappedAttribute(localClaim.getMappedAttribute(UserCoreConstants.
                    PRIMARY_DEFAULT_DOMAIN_NAME));
        }
    }

    return claimMapping;
}
 
Example 19
Source File: BasicAuthHandler.java    From carbon-identity-framework with Apache License 2.0 4 votes vote down vote up
public boolean isAuthenticated(ContainerRequestContext message) {
    // extract authorization header and authenticate.

    // get the value for Authorization Header
    List authzHeaders = message.getHeaders().get(EntitlementEndpointConstants.AUTHORIZATION_HEADER);
    if (authzHeaders != null) {
        // get the authorization header value, if provided
        String authzHeader = (String) authzHeaders.get(0);

        // decode it and extract username and password
        byte[] decodedAuthHeader = Base64.decode(authzHeader.split(" ")[1]);
        String authHeader = new String(decodedAuthHeader);
        String userName = authHeader.split(":")[0];
        String password = authHeader.split(":")[1];
        if (userName != null && password != null) {
            String tenantDomain = MultitenantUtils.getTenantDomain(userName);
            String tenantLessUserName = MultitenantUtils.getTenantAwareUsername(userName);

            try {
                // get super tenant context and get realm service which is an osgi service
                RealmService realmService = (RealmService) PrivilegedCarbonContext
                        .getThreadLocalCarbonContext().getOSGiService(RealmService.class);
                if (realmService != null) {
                    int tenantId = realmService.getTenantManager().getTenantId(tenantDomain);
                    if (tenantId == -1) {
                        log.error("Invalid tenant domain " + tenantDomain);
                        return false;
                    }
                    // get tenant's user realm
                    UserRealm userRealm = realmService.getTenantUserRealm(tenantId);
                    boolean authenticated = userRealm.getUserStoreManager().authenticate(
                            tenantLessUserName, password);
                    if (authenticated) {
                        // authentication success. set the username for authorization header and
                        // proceed the REST call
                        authzHeaders.set(0, userName);
                        return true;
                    } else {
                        log.error("Authentication failed for the user: " + tenantLessUserName
                                + "@" + tenantDomain);
                        return false;
                    }
                } else {
                    log.error("Error in getting Realm Service for user: " + userName);
                    return false;
                }
            } catch (UserStoreException e) {
                log.error("Internal server error while authenticating the user.");
                return false;
            }
        } else {
            log.error("Authentication required for this resource. " +
                            "Username or password not provided.");
            return false;
        }
    } else {
        log.error("Authentication required for this resource. " +
                      "Authorization header not present in the request.");
        return false;
    }

}