public void setUserRoles(
      Session session, final ITenant theTenant, final String userName, final String[] roles)
      throws RepositoryException, NotFoundException {
    if (hasAdminRole(getUserRoles(theTenant, userName)) && (roles.length == 0)) {
      throw new RepositoryException(
          Messages.getInstance()
              .getString("AbstractJcrBackedUserRoleDao.ERROR_0005_LAST_ADMIN_USER", userName));
    }

    Set<String> roleSet = new HashSet<String>();
    if (roles != null) {
      roleSet.addAll(Arrays.asList(roles));
    }
    roleSet.add(authenticatedRoleName);

    User jackrabbitUser = getJackrabbitUser(theTenant, userName, session);

    if ((jackrabbitUser == null)
        || !TenantUtils.isAccessibleTenant(
            theTenant == null
                ? tenantedUserNameUtils.getTenant(jackrabbitUser.getID())
                : theTenant)) {
      throw new NotFoundException(
          Messages.getInstance()
              .getString("AbstractJcrBackedUserRoleDao.ERROR_0003_USER_NOT_FOUND"));
    }
    HashMap<String, Group> currentlyAssignedGroups = new HashMap<String, Group>();
    Iterator<Group> currentGroups = jackrabbitUser.memberOf();
    while (currentGroups.hasNext()) {
      Group currentGroup = currentGroups.next();
      currentlyAssignedGroups.put(currentGroup.getID(), currentGroup);
    }

    HashMap<String, Group> finalCollectionOfAssignedGroups = new HashMap<String, Group>();
    ITenant tenant = theTenant == null ? JcrTenantUtils.getTenant(userName, true) : theTenant;
    for (String role : roleSet) {
      Group jackrabbitGroup = getJackrabbitGroup(tenant, role, session);
      if (jackrabbitGroup != null) {
        finalCollectionOfAssignedGroups.put(
            tenantedRoleNameUtils.getPrincipleId(tenant, role), jackrabbitGroup);
      }
    }

    ArrayList<String> groupsToRemove = new ArrayList<String>(currentlyAssignedGroups.keySet());
    groupsToRemove.removeAll(finalCollectionOfAssignedGroups.keySet());

    ArrayList<String> groupsToAdd = new ArrayList<String>(finalCollectionOfAssignedGroups.keySet());
    groupsToAdd.removeAll(currentlyAssignedGroups.keySet());

    for (String groupId : groupsToRemove) {
      currentlyAssignedGroups.get(groupId).removeMember(jackrabbitUser);
    }

    for (String groupId : groupsToAdd) {
      finalCollectionOfAssignedGroups.get(groupId).addMember(jackrabbitUser);
    }

    // Purge the UserDetails cache
    purgeUserFromCache(userName);
  }
  private IPentahoUser convertToPentahoUser(User jackrabbitUser) throws RepositoryException {
    if (userCache.containsKey(jackrabbitUser.getID())) {
      return (IPentahoUser) userCache.get(jackrabbitUser.getID());
    }
    IPentahoUser pentahoUser = null;
    Value[] propertyValues = null;

    String description = null;
    try {
      propertyValues = jackrabbitUser.getProperty("description"); // $NON-NLS-1$
      description = propertyValues.length > 0 ? propertyValues[0].getString() : null;
    } catch (Exception ex) {
    }

    Credentials credentials = jackrabbitUser.getCredentials();
    String password = null;
    if (credentials instanceof CryptedSimpleCredentials) {
      password = new String(((CryptedSimpleCredentials) credentials).getPassword());
    }

    pentahoUser =
        new PentahoUser(
            tenantedUserNameUtils.getTenant(jackrabbitUser.getID()),
            tenantedUserNameUtils.getPrincipleName(jackrabbitUser.getID()),
            password,
            description,
            !jackrabbitUser.isDisabled());

    userCache.put(jackrabbitUser.getID(), pentahoUser);
    return pentahoUser;
  }
  /**
   * Logs in with given username.
   *
   * @param username username of user
   * @param tenantId tenant to which this user belongs
   * @tenantAdmin true to add the tenant admin authority to the user's roles
   */
  protected void login(final String username, final ITenant tenant, String[] roles) {
    StandaloneSession pentahoSession =
        new StandaloneSession(tenantedUserNameUtils.getPrincipleId(tenant, username));
    pentahoSession.setAuthenticated(
        tenant.getId(), tenantedUserNameUtils.getPrincipleId(tenant, username));
    PentahoSessionHolder.setSession(pentahoSession);
    pentahoSession.setAttribute(IPentahoSession.TENANT_ID_KEY, tenant.getId());
    final String password = "******";

    List<GrantedAuthority> authList = new ArrayList<GrantedAuthority>();

    for (String roleName : roles) {
      authList.add(
          new GrantedAuthorityImpl(tenantedRoleNameUtils.getPrincipleId(tenant, roleName)));
    }
    GrantedAuthority[] authorities = authList.toArray(new GrantedAuthority[0]);
    UserDetails userDetails = new User(username, password, true, true, true, true, authorities);
    Authentication auth =
        new UsernamePasswordAuthenticationToken(userDetails, password, authorities);
    PentahoSessionHolder.setSession(pentahoSession);
    // this line necessary for Spring Security's MethodSecurityInterceptor
    SecurityContextHolder.getContext().setAuthentication(auth);
    SecurityHelper.getInstance().becomeUser(tenantedUserNameUtils.getPrincipleId(tenant, username));
    SecurityContextHolder.getContext().setAuthentication(auth);
  }
  public IPentahoRole createRole(
      Session session,
      final ITenant theTenant,
      final String roleName,
      final String description,
      final String[] memberUserNames)
      throws AuthorizableExistsException, RepositoryException {
    ITenant tenant = theTenant;
    String role = roleName;
    if (tenant == null) {
      tenant = JcrTenantUtils.getTenant(roleName, false);
      role = JcrTenantUtils.getPrincipalName(roleName, false);
    }
    if (tenant == null || tenant.getId() == null) {
      tenant = JcrTenantUtils.getCurrentTenant();
    }
    if (!TenantUtils.isAccessibleTenant(tenant)) {
      throw new NotFoundException(
          Messages.getInstance()
              .getString(
                  "AbstractJcrBackedUserRoleDao.ERROR_0006_TENANT_NOT_FOUND", theTenant.getId()));
    }
    String roleId = tenantedRoleNameUtils.getPrincipleId(tenant, role);

    UserManager tenantUserMgr = getUserManager(tenant, session);
    // Intermediate path will always be an empty string. The path is already provided while creating
    // a user manager
    tenantUserMgr.createGroup(new PrincipalImpl(roleId), ""); // $NON-NLS-1$
    setRoleMembers(session, tenant, role, memberUserNames);
    setRoleDescription(session, tenant, role, description);
    return getRole(session, theTenant, roleName);
  }
  private Group getJackrabbitGroup(ITenant theTenant, String name, Session session)
      throws RepositoryException {
    Group jackrabbitGroup = null;
    String roleId = name;
    String roleName = name;
    ITenant tenant = theTenant;

    if (tenant == null) {
      tenant = JcrTenantUtils.getTenant(roleName, false);
      roleName = JcrTenantUtils.getPrincipalName(roleName, false);
    }
    if (tenant == null || tenant.getId() == null) {
      tenant = JcrTenantUtils.getCurrentTenant();
    }
    if (tenant == null || tenant.getId() == null) {
      tenant = JcrTenantUtils.getDefaultTenant();
    }
    roleId = tenantedRoleNameUtils.getPrincipleId(tenant, roleName);

    UserManager userMgr = getUserManager(tenant, session);
    Authorizable authorizable = userMgr.getAuthorizable(roleId);
    if (authorizable instanceof Group) {
      jackrabbitGroup = (Group) authorizable;
    }
    return jackrabbitGroup;
  }
 @Override
 public List<String> getBoundLogicalRoleNames(Session session, List<String> runtimeRoleNames)
     throws NamespaceException, RepositoryException {
   Set<String> boundRoleNames = new HashSet<String>();
   HashMap<ITenant, List<String>> tenantMap = new HashMap<ITenant, List<String>>();
   boolean includeSuperAdminLogicalRoles = false;
   for (String runtimeRoleName : runtimeRoleNames) {
     if (!superAdminRoleName.equals(runtimeRoleName)) {
       ITenant tenant = JcrTenantUtils.getTenant(runtimeRoleName, false);
       List<String> runtimeRoles = tenantMap.get(tenant);
       if (runtimeRoles == null) {
         runtimeRoles = new ArrayList<String>();
         tenantMap.put(tenant, runtimeRoles);
       }
       runtimeRoles.add(tenantedRoleNameUtils.getPrincipleName(runtimeRoleName));
     } else {
       includeSuperAdminLogicalRoles = true;
     }
   }
   for (Map.Entry<ITenant, List<String>> mapEntry : tenantMap.entrySet()) {
     boundRoleNames.addAll(
         getBoundLogicalRoleNames(session, mapEntry.getKey(), mapEntry.getValue()));
   }
   if (includeSuperAdminLogicalRoles) {
     boundRoleNames.addAll(immutableRoleBindingNames.get(superAdminRoleName));
   }
   return new ArrayList<String>(boundRoleNames);
 }
 private String getPrincipalName(String principalId) {
   String principalName = null;
   if (tenantedRoleNameUtils != null) {
     principalName = tenantedRoleNameUtils.getPrincipleName(principalId);
   }
   return principalName;
 }
  public void deleteUser(Session session, final IPentahoUser user)
      throws NotFoundException, RepositoryException {
    if (canDeleteUser(session, user)) {
      User jackrabbitUser = getJackrabbitUser(user.getTenant(), user.getUsername(), session);
      if (jackrabbitUser != null
          && TenantUtils.isAccessibleTenant(
              tenantedUserNameUtils.getTenant(jackrabbitUser.getID()))) {

        // [BISERVER-9215] Adding new user with same user name as a previously deleted user,
        // defaults to all previous roles
        Iterator<Group> currentGroups = jackrabbitUser.memberOf();
        while (currentGroups.hasNext()) {
          currentGroups.next().removeMember(jackrabbitUser);
        }
        // [BISERVER-9215]

        jackrabbitUser.remove();
      } else {
        throw new NotFoundException(""); // $NON-NLS-1$
      }
    } else {
      throw new RepositoryException(
          Messages.getInstance()
              .getString(
                  "AbstractJcrBackedUserRoleDao.ERROR_0004_LAST_USER_NEEDED_IN_ROLE",
                  tenantAdminRoleName));
    }
  }
  private User getJackrabbitUser(ITenant theTenant, String name, Session session)
      throws RepositoryException {
    User jackrabbitUser = null;
    String userId = name;
    String userName = name;
    ITenant tenant = theTenant;
    if (tenant == null) {
      tenant = JcrTenantUtils.getTenant(userName, true);
      userName = JcrTenantUtils.getPrincipalName(userName, true);
    }
    if (tenant == null || tenant.getId() == null) {
      tenant = JcrTenantUtils.getCurrentTenant();
    }
    if (tenant == null || tenant.getId() == null) {
      tenant = JcrTenantUtils.getDefaultTenant();
    }

    if (tenant != null) {
      userId = tenantedUserNameUtils.getPrincipleId(tenant, userName);

      UserManager userMgr = getUserManager(tenant, session);
      Authorizable authorizable = userMgr.getAuthorizable(userId);
      if (authorizable instanceof User) {
        jackrabbitUser = (User) authorizable;
      }
    }
    return jackrabbitUser;
  }
 public IPentahoUser getUser(Session session, final ITenant tenant, final String name)
     throws RepositoryException {
   User jackrabbitUser = getJackrabbitUser(tenant, name, session);
   return jackrabbitUser != null
           && TenantUtils.isAccessibleTenant(
               tenant == null ? tenantedUserNameUtils.getTenant(jackrabbitUser.getID()) : tenant)
       ? convertToPentahoUser(jackrabbitUser)
       : null;
 }
 public IPentahoRole getRole(Session session, final ITenant tenant, final String name)
     throws RepositoryException {
   Group jackrabbitGroup = getJackrabbitGroup(tenant, name, session);
   return jackrabbitGroup != null
           && TenantUtils.isAccessibleTenant(
               tenant == null ? tenantedRoleNameUtils.getTenant(jackrabbitGroup.getID()) : tenant)
       ? convertToPentahoRole(jackrabbitGroup)
       : null;
 }
  public void setRoleBindings(
      Session session, ITenant tenant, String runtimeRoleName, List<String> logicalRoleNames)
      throws NamespaceException, RepositoryException {
    if (tenant == null) {
      tenant = JcrTenantUtils.getTenant(runtimeRoleName, false);
      runtimeRoleName = getPrincipalName(runtimeRoleName);
    }

    if (!TenantUtils.isAccessibleTenant(tenant)) {
      throw new NotFoundException("Tenant " + tenant.getId() + " not found");
    }

    PentahoJcrConstants pentahoJcrConstants = new PentahoJcrConstants(session);
    final String phoNsPrefix =
        session.getNamespacePrefix(PentahoJcrConstants.PHO_NS) + ":"; // $NON-NLS-1$
    final String onlyPentahoPattern = phoNsPrefix + "*"; // $NON-NLS-1$
    Node runtimeRolesFolderNode = getRuntimeRolesFolderNode(session, tenant);
    NodeIterator runtimeRoleNodes = runtimeRolesFolderNode.getNodes(onlyPentahoPattern);
    int i = 0;
    while (runtimeRoleNodes.hasNext()) {
      runtimeRoleNodes.nextNode();
      i++;
    }
    if (i == 0) {
      // no bindings setup yet; install bootstrap bindings; bootstrapRoleBindings will now no longer
      // be
      // consulted
      for (Map.Entry<String, List<String>> entry : bootstrapRoleBindings.entrySet()) {
        JcrRoleAuthorizationPolicyUtils.internalSetBindings(
            pentahoJcrConstants,
            runtimeRolesFolderNode,
            entry.getKey(),
            entry.getValue(),
            phoNsPrefix);
      }
    }
    if (!isImmutable(runtimeRoleName)) {
      JcrRoleAuthorizationPolicyUtils.internalSetBindings(
          pentahoJcrConstants,
          runtimeRolesFolderNode,
          runtimeRoleName,
          logicalRoleNames,
          phoNsPrefix);
    } else {
      throw new RuntimeException(
          Messages.getInstance()
              .getString(
                  "JcrRoleAuthorizationPolicyRoleBindingDao.ERROR_0001_ATTEMPT_MOD_IMMUTABLE",
                  runtimeRoleName)); //$NON-NLS-1$
    }
    session.save();
    Assert.isTrue(NodeHelper.hasNode(runtimeRolesFolderNode, phoNsPrefix, runtimeRoleName));

    // update cache
    String roleId = tenantedRoleNameUtils.getPrincipleId(tenant, runtimeRoleName);
    cacheManager.putInRegionCache(LOGICAL_ROLE_BINDINGS_REGION, roleId, logicalRoleNames);
  }
  private IPentahoRole convertToPentahoRole(Group jackrabbitGroup) throws RepositoryException {
    IPentahoRole role = null;
    Value[] propertyValues = null;

    String description = null;
    try {
      propertyValues = jackrabbitGroup.getProperty("description"); // $NON-NLS-1$
      description = propertyValues.length > 0 ? propertyValues[0].getString() : null;
    } catch (Exception ex) {
    }

    role =
        new PentahoRole(
            tenantedRoleNameUtils.getTenant(jackrabbitGroup.getID()),
            tenantedRoleNameUtils.getPrincipleName(jackrabbitGroup.getID()),
            description);
    return role;
  }
  private void setUserRolesForNewUser(
      Session session, final ITenant theTenant, final String userName, final String[] roles)
      throws RepositoryException, NotFoundException {
    Set<String> roleSet = new HashSet<String>();
    if (roles != null) {
      roleSet.addAll(Arrays.asList(roles));
    }
    roleSet.add(authenticatedRoleName);

    User jackrabbitUser = getJackrabbitUser(theTenant, userName, session);

    if ((jackrabbitUser == null)
        || !TenantUtils.isAccessibleTenant(
            theTenant == null
                ? tenantedUserNameUtils.getTenant(jackrabbitUser.getID())
                : theTenant)) {
      throw new NotFoundException(
          Messages.getInstance()
              .getString("AbstractJcrBackedUserRoleDao.ERROR_0003_USER_NOT_FOUND"));
    }

    HashMap<String, Group> finalCollectionOfAssignedGroups = new HashMap<String, Group>();
    ITenant tenant = theTenant == null ? JcrTenantUtils.getTenant(userName, true) : theTenant;
    for (String role : roleSet) {
      Group jackrabbitGroup = getJackrabbitGroup(tenant, role, session);
      if (jackrabbitGroup != null) {
        finalCollectionOfAssignedGroups.put(
            tenantedRoleNameUtils.getPrincipleId(tenant, role), jackrabbitGroup);
      }
    }

    ArrayList<String> groupsToAdd = new ArrayList<String>(finalCollectionOfAssignedGroups.keySet());

    for (String groupId : groupsToAdd) {
      finalCollectionOfAssignedGroups.get(groupId).addMember(jackrabbitUser);
      // Purge the UserDetails cache
      purgeUserFromCache(userName);
    }
  }
 protected RepositoryFileAce toAce(final Session session, final AccessControlEntry acEntry)
     throws RepositoryException {
   Principal principal = acEntry.getPrincipal();
   RepositoryFileSid sid = null;
   String name = principal.getName();
   if (principal instanceof Group) {
     if (tenantedRoleNameUtils != null) {
       name = tenantedRoleNameUtils.getPrincipleName(name);
     }
     sid = new RepositoryFileSid(name, RepositoryFileSid.Type.ROLE);
   } else {
     if (tenantedUserNameUtils != null) {
       name = tenantedUserNameUtils.getPrincipleName(name);
     }
     sid = new RepositoryFileSid(name, RepositoryFileSid.Type.USER);
   }
   logger.debug(
       String.format("principal class [%s]", principal.getClass().getName())); // $NON-NLS-1$
   Privilege[] privileges = acEntry.getPrivileges();
   return new RepositoryFileAce(
       sid, permissionConversionHelper.privilegesToPentahoPermissions(session, privileges));
 }
 public void deleteRole(Session session, final IPentahoRole role)
     throws NotFoundException, RepositoryException {
   if (canDeleteRole(session, role)) {
     Group jackrabbitGroup = getJackrabbitGroup(role.getTenant(), role.getName(), session);
     if (jackrabbitGroup != null
         && TenantUtils.isAccessibleTenant(
             tenantedRoleNameUtils.getTenant(jackrabbitGroup.getID()))) {
       jackrabbitGroup.remove();
     } else {
       throw new NotFoundException(""); // $NON-NLS-1$
     }
   } else {
     throw new RepositoryException(
         Messages.getInstance()
             .getString("AbstractJcrBackedUserRoleDao.ERROR_0007_ATTEMPTED_SYSTEM_ROLE_DELETE"));
   }
 }
 public List<IPentahoUser> getRoleMembers(
     Session session, final ITenant theTenant, final String roleName) throws RepositoryException {
   List<IPentahoUser> users = new ArrayList<IPentahoUser>();
   Group jackrabbitGroup = getJackrabbitGroup(theTenant, roleName, session);
   if ((jackrabbitGroup != null)
       && TenantUtils.isAccessibleTenant(
           theTenant == null
               ? tenantedRoleNameUtils.getTenant(jackrabbitGroup.getID())
               : theTenant)) {
     Iterator<Authorizable> authorizables = jackrabbitGroup.getMembers();
     while (authorizables.hasNext()) {
       Authorizable authorizable = authorizables.next();
       if (authorizable instanceof User) {
         users.add(convertToPentahoUser((User) authorizable));
       }
     }
   }
   return users;
 }
  public void setPassword(
      Session session, final ITenant theTenant, final String userName, final String password)
      throws NotFoundException, RepositoryException {
    User jackrabbitUser = getJackrabbitUser(theTenant, userName, session);
    if ((jackrabbitUser == null)
        || !TenantUtils.isAccessibleTenant(
            theTenant == null
                ? tenantedUserNameUtils.getTenant(jackrabbitUser.getID())
                : theTenant)) {
      throw new NotFoundException(
          Messages.getInstance()
              .getString("AbstractJcrBackedUserRoleDao.ERROR_0003_USER_NOT_FOUND"));
    }
    jackrabbitUser.changePassword(password);

    /** BISERVER-9906 Clear cache after changing password */
    purgeUserFromCache(userName);
    userCache.remove(jackrabbitUser.getID());
  }
 public void setUserDescription(
     Session session, final ITenant theTenant, final String userName, final String description)
     throws NotFoundException, RepositoryException {
   User jackrabbitUser = getJackrabbitUser(theTenant, userName, session);
   if ((jackrabbitUser == null)
       || !TenantUtils.isAccessibleTenant(
           theTenant == null
               ? tenantedUserNameUtils.getTenant(jackrabbitUser.getID())
               : theTenant)) {
     throw new NotFoundException(
         Messages.getInstance()
             .getString("AbstractJcrBackedUserRoleDao.ERROR_0003_USER_NOT_FOUND"));
   }
   if (description == null) {
     jackrabbitUser.removeProperty("description"); // $NON-NLS-1$
   } else {
     jackrabbitUser.setProperty(
         "description", session.getValueFactory().createValue(description)); // $NON-NLS-1$
   }
 }
 public List<IPentahoRole> getUserRoles(
     Session session, final ITenant theTenant, final String userName) throws RepositoryException {
   ArrayList<IPentahoRole> roles = new ArrayList<IPentahoRole>();
   User jackrabbitUser = getJackrabbitUser(theTenant, userName, session);
   if ((jackrabbitUser != null)
       && TenantUtils.isAccessibleTenant(
           theTenant == null
               ? tenantedUserNameUtils.getTenant(jackrabbitUser.getID())
               : theTenant)) {
     Iterator<Group> groups = jackrabbitUser.memberOf();
     while (groups.hasNext()) {
       IPentahoRole role = convertToPentahoRole(groups.next());
       // Exclude the extra role from the list of roles to be returned back
       if (!extraRoles.contains(role.getName())) {
         roles.add(role);
       }
     }
   }
   return roles;
 }
 public void setRoleDescription(
     Session session, final ITenant theTenant, final String roleName, final String description)
     throws NotFoundException, RepositoryException {
   Group jackrabbitGroup = getJackrabbitGroup(theTenant, roleName, session);
   if (jackrabbitGroup != null
       && TenantUtils.isAccessibleTenant(
           theTenant == null
               ? tenantedRoleNameUtils.getTenant(jackrabbitGroup.getID())
               : theTenant)) {
     if (description == null) {
       jackrabbitGroup.removeProperty("description"); // $NON-NLS-1$
     } else {
       jackrabbitGroup.setProperty(
           "description", session.getValueFactory().createValue(description)); // $NON-NLS-1$
     }
   } else {
     throw new NotFoundException(
         Messages.getInstance()
             .getString("AbstractJcrBackedUserRoleDao.ERROR_0002_ROLE_NOT_FOUND"));
   }
 }
  private RepositoryFileAcl toAcl(
      final Session session, final PentahoJcrConstants pentahoJcrConstants, final Serializable id)
      throws RepositoryException {

    Node node = session.getNodeByIdentifier(id.toString());
    if (node == null) {
      throw new RepositoryException(
          Messages.getInstance()
              .getString(
                  "JackrabbitRepositoryFileAclDao.ERROR_0001_NODE_NOT_FOUND",
                  id.toString())); // $NON-NLS-1$
    }
    String absPath = node.getPath();
    AccessControlManager acMgr = session.getAccessControlManager();
    AccessControlList acList = getAccessControlList(acMgr, absPath);

    RepositoryFileSid owner = null;
    String ownerString = getOwner(session, absPath, acList);

    if (ownerString != null) {
      // for now, just assume all owners are users; only has UI impact
      if (tenantedUserNameUtils != null) {
        ownerString = tenantedUserNameUtils.getPrincipleName(ownerString);
      }
      owner = new RepositoryFileSid(ownerString, RepositoryFileSid.Type.USER);
    }

    RepositoryFileAcl.Builder aclBuilder = new RepositoryFileAcl.Builder(id, owner);

    aclBuilder.entriesInheriting(isEntriesInheriting(session, absPath, acList));

    List<AccessControlEntry> cleanedAcEntries =
        JcrRepositoryFileAclUtils.removeAclMetadata(
            Arrays.asList(acList.getAccessControlEntries()));

    for (AccessControlEntry acEntry : cleanedAcEntries) {
      aclBuilder.ace(toAce(session, acEntry));
    }
    return aclBuilder.build();
  }
 public IPentahoUser createUser(
     Session session,
     final ITenant theTenant,
     final String userName,
     final String password,
     final String description,
     final String[] roles)
     throws AuthorizableExistsException, RepositoryException {
   ITenant tenant = theTenant;
   String user = userName;
   if (tenant == null) {
     tenant = JcrTenantUtils.getTenant(userName, true);
     user = JcrTenantUtils.getPrincipalName(userName, true);
   }
   if (tenant == null || tenant.getId() == null) {
     tenant = JcrTenantUtils.getCurrentTenant();
   }
   if (!TenantUtils.isAccessibleTenant(tenant)) {
     throw new NotFoundException(
         Messages.getInstance()
             .getString(
                 "AbstractJcrBackedUserRoleDao.ERROR_0006_TENANT_NOT_FOUND", theTenant.getId()));
   }
   String userId = tenantedUserNameUtils.getPrincipleId(tenant, user);
   UserManager tenantUserMgr = getUserManager(tenant, session);
   tenantUserMgr.createUser(userId, password, new PrincipalImpl(userId), ""); // $NON-NLS-1$
   session.save();
   /**
    * This call is absolutely necessary. setUserRolesForNewUser will never * inspect what roles
    * this user is a part of. Since this is a new user * it will not be a part of new roles
    */
   setUserRolesForNewUser(session, tenant, user, roles);
   setUserDescription(session, tenant, user, description);
   session.save();
   createUserHomeFolder(tenant, user, session);
   session.save();
   this.userDetailsCache.removeUserFromCache(userName);
   return getUser(session, tenant, userName);
 }
  public void setRoleMembers(
      Session session,
      final ITenant theTenant,
      final String roleName,
      final String[] memberUserNames)
      throws RepositoryException, NotFoundException {
    List<IPentahoUser> currentRoleMembers = getRoleMembers(session, theTenant, roleName);
    if (tenantAdminRoleName.equals(roleName)
        && (currentRoleMembers != null && currentRoleMembers.size() > 0)
        && memberUserNames.length == 0) {
      throw new RepositoryException(
          Messages.getInstance()
              .getString(
                  "AbstractJcrBackedUserRoleDao.ERROR_0001_LAST_ADMIN_ROLE", tenantAdminRoleName));
    }
    Group jackrabbitGroup = getJackrabbitGroup(theTenant, roleName, session);

    if ((jackrabbitGroup == null)
        || !TenantUtils.isAccessibleTenant(
            theTenant == null
                ? tenantedRoleNameUtils.getTenant(jackrabbitGroup.getID())
                : theTenant)) {
      throw new NotFoundException(
          Messages.getInstance()
              .getString("AbstractJcrBackedUserRoleDao.ERROR_0002_ROLE_NOT_FOUND"));
    }
    HashMap<String, User> currentlyAssignedUsers = new HashMap<String, User>();
    Iterator<Authorizable> currentMembers = jackrabbitGroup.getMembers();
    while (currentMembers.hasNext()) {
      Authorizable member = currentMembers.next();
      if (member instanceof User) {
        currentlyAssignedUsers.put(member.getID(), (User) member);
      }
    }

    HashMap<String, User> finalCollectionOfAssignedUsers = new HashMap<String, User>();
    if (memberUserNames != null) {
      ITenant tenant = theTenant == null ? JcrTenantUtils.getTenant(roleName, false) : theTenant;
      for (String user : memberUserNames) {
        User jackrabbitUser = getJackrabbitUser(tenant, user, session);
        if (jackrabbitUser != null) {
          finalCollectionOfAssignedUsers.put(
              tenantedRoleNameUtils.getPrincipleId(tenant, user), jackrabbitUser);
        }
      }
    }

    ArrayList<String> usersToRemove = new ArrayList<String>(currentlyAssignedUsers.keySet());
    usersToRemove.removeAll(finalCollectionOfAssignedUsers.keySet());

    ArrayList<String> usersToAdd = new ArrayList<String>(finalCollectionOfAssignedUsers.keySet());
    usersToAdd.removeAll(currentlyAssignedUsers.keySet());

    for (String userId : usersToRemove) {
      jackrabbitGroup.removeMember(currentlyAssignedUsers.get(userId));
    }

    for (String userId : usersToAdd) {
      jackrabbitGroup.addMember(finalCollectionOfAssignedUsers.get(userId));

      // Purge the UserDetails cache
      purgeUserFromCache(userId);
    }
  }
  @Override
  public List<String> getBoundLogicalRoleNames(
      Session session, ITenant tenant, List<String> runtimeRoleNames)
      throws NamespaceException, RepositoryException {
    if ((tenant == null) || (tenant.getId() == null)) {
      return getBoundLogicalRoleNames(session, runtimeRoleNames);
    }

    if (!TenantUtils.isAccessibleTenant(tenant)) {
      return new ArrayList<String>();
    }

    final List<String> uncachedRuntimeRoleNames = new ArrayList<String>();
    final Set<String> cachedBoundLogicalRoleNames = new HashSet<String>();
    for (String runtimeRoleName : runtimeRoleNames) {
      String roleName = tenantedRoleNameUtils.getPrincipleName(runtimeRoleName);
      String roleId = tenantedRoleNameUtils.getPrincipleId(tenant, runtimeRoleName);
      Object fromRegionCache =
          cacheManager.getFromRegionCache(LOGICAL_ROLE_BINDINGS_REGION, roleId);
      if (fromRegionCache != null) {
        cachedBoundLogicalRoleNames.addAll((Collection<String>) fromRegionCache);
      } else {
        uncachedRuntimeRoleNames.add(roleName);
      }
    }
    if (uncachedRuntimeRoleNames.isEmpty()) {
      // no need to hit the repo
      return new ArrayList<String>(cachedBoundLogicalRoleNames);
    }

    PentahoJcrConstants pentahoJcrConstants = new PentahoJcrConstants(session);
    final String phoNsPrefix =
        session.getNamespacePrefix(PentahoJcrConstants.PHO_NS) + ":"; // $NON-NLS-1$
    final String onlyPentahoPattern = phoNsPrefix + "*"; // $NON-NLS-1$
    HashMultimap<String, String> boundLogicalRoleNames = HashMultimap.create();
    Node runtimeRolesFolderNode = getRuntimeRolesFolderNode(session, tenant);
    NodeIterator runtimeRoleNodes = runtimeRolesFolderNode.getNodes(onlyPentahoPattern);
    if (!runtimeRoleNodes.hasNext()) {
      // no bindings setup yet; fall back on bootstrap bindings
      for (String runtimeRoleName : uncachedRuntimeRoleNames) {
        String roleId = tenantedRoleNameUtils.getPrincipleId(tenant, runtimeRoleName);
        if (bootstrapRoleBindings.containsKey(runtimeRoleName)) {
          boundLogicalRoleNames.putAll(roleId, bootstrapRoleBindings.get(runtimeRoleName));
        }
      }
    } else {
      for (String runtimeRoleName : uncachedRuntimeRoleNames) {
        if (NodeHelper.hasNode(runtimeRolesFolderNode, phoNsPrefix, runtimeRoleName)) {
          Node runtimeRoleFolderNode =
              NodeHelper.getNode(runtimeRolesFolderNode, phoNsPrefix, runtimeRoleName);
          if (runtimeRoleFolderNode.hasProperty(pentahoJcrConstants.getPHO_BOUNDROLES())) {
            Value[] values =
                runtimeRoleFolderNode
                    .getProperty(pentahoJcrConstants.getPHO_BOUNDROLES())
                    .getValues();
            String roleId = tenantedRoleNameUtils.getPrincipleId(tenant, runtimeRoleName);
            for (Value value : values) {
              boundLogicalRoleNames.put(roleId, value.getString());
            }
          }
        }
      }
    }
    // now add in immutable bound logical role names
    for (String runtimeRoleName : uncachedRuntimeRoleNames) {
      if (immutableRoleBindings.containsKey(runtimeRoleName)) {
        String roleId = tenantedRoleNameUtils.getPrincipleId(tenant, runtimeRoleName);
        boundLogicalRoleNames.putAll(roleId, immutableRoleBindingNames.get(runtimeRoleName));
      }
    }

    // update cache
    Map<String, Collection<String>> stringCollectionMap = boundLogicalRoleNames.asMap();
    for (Entry<String, Collection<String>> stringCollectionEntry : stringCollectionMap.entrySet()) {
      cacheManager.putInRegionCache(
          LOGICAL_ROLE_BINDINGS_REGION,
          stringCollectionEntry.getKey(),
          stringCollectionEntry.getValue());
    }

    // now add in those runtime roles that have no bindings to the cache
    for (String runtimeRoleName : uncachedRuntimeRoleNames) {
      String roleId = tenantedRoleNameUtils.getPrincipleId(tenant, runtimeRoleName);

      if (cacheManager.getFromRegionCache(LOGICAL_ROLE_BINDINGS_REGION, roleId) == null) {
        cacheManager.putInRegionCache(
            LOGICAL_ROLE_BINDINGS_REGION, roleId, Collections.emptyList());
      }
    }

    // combine cached findings plus ones from repo
    Set<String> res = new HashSet<String>();
    res.addAll(cachedBoundLogicalRoleNames);
    res.addAll(boundLogicalRoleNames.values());
    return new ArrayList<String>(res);
  }
  private RepositoryFile createUserHomeFolder(ITenant theTenant, String username, Session session)
      throws RepositoryException {
    Builder aclsForUserHomeFolder = null;
    Builder aclsForTenantHomeFolder = null;

    if (theTenant == null) {
      theTenant = JcrTenantUtils.getTenant(username, true);
      username = JcrTenantUtils.getPrincipalName(username, true);
    }
    if (theTenant == null || theTenant.getId() == null) {
      theTenant = JcrTenantUtils.getCurrentTenant();
    }
    if (theTenant == null || theTenant.getId() == null) {
      theTenant = JcrTenantUtils.getDefaultTenant();
    }
    RepositoryFile userHomeFolder = null;
    String userId = tenantedUserNameUtils.getPrincipleId(theTenant, username);
    final RepositoryFileSid userSid = new RepositoryFileSid(userId);
    RepositoryFile tenantHomeFolder = null;
    RepositoryFile tenantRootFolder = null;
    RepositoryFileSid ownerSid = null;
    // Get the Tenant Root folder. If the Tenant Root folder does not exist then exit.
    tenantRootFolder =
        JcrRepositoryFileUtils.getFileByAbsolutePath(
            session,
            ServerRepositoryPaths.getTenantRootFolderPath(theTenant),
            pathConversionHelper,
            lockHelper,
            false,
            null);
    if (tenantRootFolder != null) {
      // Try to see if Tenant Home folder exist
      tenantHomeFolder =
          JcrRepositoryFileUtils.getFileByAbsolutePath(
              session,
              ServerRepositoryPaths.getTenantHomeFolderPath(theTenant),
              pathConversionHelper,
              lockHelper,
              false,
              null);

      if (tenantHomeFolder == null) {
        String ownerId = tenantedUserNameUtils.getPrincipleId(theTenant, username);
        ownerSid = new RepositoryFileSid(ownerId, Type.USER);

        String tenantAuthenticatedRoleId =
            tenantedRoleNameUtils.getPrincipleId(theTenant, authenticatedRoleName);
        RepositoryFileSid tenantAuthenticatedRoleSid =
            new RepositoryFileSid(tenantAuthenticatedRoleId, Type.ROLE);

        aclsForTenantHomeFolder =
            new RepositoryFileAcl.Builder(userSid)
                .ace(tenantAuthenticatedRoleSid, EnumSet.of(RepositoryFilePermission.READ));

        aclsForUserHomeFolder =
            new RepositoryFileAcl.Builder(userSid)
                .ace(ownerSid, EnumSet.of(RepositoryFilePermission.ALL));
        tenantHomeFolder =
            internalCreateFolder(
                session,
                tenantRootFolder.getId(),
                new RepositoryFile.Builder(ServerRepositoryPaths.getTenantHomeFolderName())
                    .folder(true)
                    .title(
                        Messages.getInstance()
                            .getString("AbstractJcrBackedUserRoleDao.usersFolderDisplayName"))
                    .build(),
                aclsForTenantHomeFolder.build(),
                "tenant home folder"); //$NON-NLS-1$
      } else {
        String ownerId = tenantedUserNameUtils.getPrincipleId(theTenant, username);
        ownerSid = new RepositoryFileSid(ownerId, Type.USER);
        aclsForUserHomeFolder =
            new RepositoryFileAcl.Builder(userSid)
                .ace(ownerSid, EnumSet.of(RepositoryFilePermission.ALL));
      }

      // now check if user's home folder exist
      userHomeFolder =
          JcrRepositoryFileUtils.getFileByAbsolutePath(
              session,
              ServerRepositoryPaths.getUserHomeFolderPath(theTenant, username),
              pathConversionHelper,
              lockHelper,
              false,
              null);
      if (userHomeFolder == null) {
        userHomeFolder =
            internalCreateFolder(
                session,
                tenantHomeFolder.getId(),
                new RepositoryFile.Builder(username).folder(true).build(),
                aclsForUserHomeFolder.build(),
                "user home folder"); //$NON-NLS-1$
      }
    }
    return userHomeFolder;
  }
  @Test
  public void testGetUsernamesInRole() {
    loginAsRepositoryAdmin();
    ITenant systemTenant =
        tenantManager.createTenant(
            null,
            ServerRepositoryPaths.getPentahoRootFolderName(),
            tenantAdminAuthorityName,
            tenantAuthenticatedAuthorityName,
            "Anonymous");
    userRoleDao.createUser(
        systemTenant, sysAdminUserName, "password", "", new String[] {tenantAdminAuthorityName});
    login(
        sysAdminUserName,
        systemTenant,
        new String[] {tenantAdminAuthorityName, tenantAuthenticatedAuthorityName});
    ITenant mainTenant_1 =
        tenantManager.createTenant(
            systemTenant,
            MAIN_TENANT_1,
            tenantAdminAuthorityName,
            tenantAuthenticatedAuthorityName,
            "Anonymous");
    userRoleDao.createUser(
        mainTenant_1, "admin", "password", "", new String[] {tenantAdminAuthorityName});
    ITenant mainTenant_2 =
        tenantManager.createTenant(
            systemTenant,
            MAIN_TENANT_2,
            tenantAdminAuthorityName,
            tenantAuthenticatedAuthorityName,
            "Anonymous");
    userRoleDao.createUser(
        mainTenant_2, "admin", "password", "", new String[] {tenantAdminAuthorityName});

    login(
        "admin",
        mainTenant_1,
        new String[] {tenantAdminAuthorityName, tenantAuthenticatedAuthorityName});
    IPentahoUser pentahoUser =
        userRoleDao.createUser(mainTenant_1, USER_2, PASSWORD_2, USER_DESCRIPTION_2, null);
    pentahoUser = userRoleDao.createUser(null, USER_3, PASSWORD_3, USER_DESCRIPTION_3, null);
    pentahoUser =
        userRoleDao.createUser(
            null,
            tenantedUserNameUtils.getPrincipleId(mainTenant_1, USER_4),
            PASSWORD_4,
            USER_DESCRIPTION_4,
            null);
    pentahoUser =
        userRoleDao.createUser(mainTenant_1, USER_5, PASSWORD_5, USER_DESCRIPTION_5, null);
    pentahoUser =
        userRoleDao.createUser(mainTenant_1, USER_6, PASSWORD_6, USER_DESCRIPTION_6, null);
    logout();
    login(
        "admin",
        mainTenant_2,
        new String[] {tenantAdminAuthorityName, tenantAuthenticatedAuthorityName});
    pentahoUser =
        userRoleDao.createUser(mainTenant_2, USER_7, PASSWORD_7, USER_DESCRIPTION_7, null);
    pentahoUser =
        userRoleDao.createUser(mainTenant_2, USER_8, PASSWORD_8, USER_DESCRIPTION_8, null);
    logout();
    login(
        "admin",
        mainTenant_1,
        new String[] {tenantAdminAuthorityName, tenantAuthenticatedAuthorityName});
    IPentahoRole pentahoRole =
        userRoleDao.createRole(mainTenant_1, ROLE_1, ROLE_DESCRIPTION_1, null);
    pentahoRole = userRoleDao.createRole(null, ROLE_2, ROLE_DESCRIPTION_2, null);
    pentahoRole =
        userRoleDao.createRole(
            null,
            tenantedRoleNameUtils.getPrincipleId(mainTenant_1, ROLE_3),
            ROLE_DESCRIPTION_3,
            null);
    logout();
    login(
        "admin",
        mainTenant_2,
        new String[] {tenantAdminAuthorityName, tenantAuthenticatedAuthorityName});
    pentahoRole = userRoleDao.createRole(mainTenant_2, ROLE_4, ROLE_DESCRIPTION_4, null);
    logout();
    login(
        "admin",
        mainTenant_1,
        new String[] {tenantAdminAuthorityName, tenantAuthenticatedAuthorityName});
    userRoleDao.setRoleMembers(null, ROLE_1, new String[] {USER_2, USER_3, USER_4});
    userRoleDao.setRoleMembers(mainTenant_1, ROLE_2, new String[] {USER_5, USER_6, USER_7});
    userRoleDao.setRoleMembers(
        null,
        tenantedRoleNameUtils.getPrincipleId(mainTenant_1, ROLE_3),
        new String[] {USER_2, USER_4, USER_6});
    logout();
    login(
        "admin",
        mainTenant_2,
        new String[] {tenantAdminAuthorityName, tenantAuthenticatedAuthorityName});
    userRoleDao.setRoleMembers(null, ROLE_4, new String[] {USER_3, USER_5, USER_7});
    logout();
    login(
        "admin",
        mainTenant_1,
        new String[] {tenantAdminAuthorityName, tenantAuthenticatedAuthorityName});
    UserRoleDaoUserDetailsService userDetailsService = new UserRoleDaoUserDetailsService();
    userDetailsService.setUserRoleDao(userRoleDao);
    userDetailsService.setDefaultRole(tenantAuthenticatedAuthorityName);
    List<String> systemRoles = new ArrayList<String>();
    systemRoles.add("Admin");

    List<String> extraRoles = Arrays.asList(new String[] {"Authenticated", "Anonymous"});
    String adminRole = "Admin";

    UserRoleDaoUserRoleListService service =
        new UserRoleDaoUserRoleListService(
            userRoleDao,
            userDetailsService,
            tenantedUserNameUtils,
            systemRoles,
            extraRoles,
            adminRole);

    List<String> usersInRole_1 = service.getUsersInRole(mainTenant_1, ROLE_1);
    List<String> usersInRole_2 = service.getUsersInRole(null, ROLE_2);
    List<String> usersInRole_3 =
        service.getUsersInRole(null, tenantedRoleNameUtils.getPrincipleId(mainTenant_1, ROLE_3));

    logout();
    login(
        "admin",
        mainTenant_2,
        new String[] {tenantAdminAuthorityName, tenantAuthenticatedAuthorityName});

    List<String> usersInRole_4 = service.getUsersInRole(mainTenant_2, ROLE_4);

    assertTrue(usersInRole_1.size() == 3);
    assertTrue(usersInRole_2.size() == 2);
    assertTrue(usersInRole_3.size() == 3);
    assertTrue(usersInRole_4.size() == 1);

    logout();

    cleanupUserAndRoles("admin", mainTenant_1);
    cleanupUserAndRoles("admin", mainTenant_2);
    cleanupUserAndRoles(sysAdminUserName, systemTenant);
  }
  @Test
  public void testGetAuthoritiesForUser() {
    loginAsRepositoryAdmin();
    ITenant systemTenant =
        tenantManager.createTenant(
            null,
            ServerRepositoryPaths.getPentahoRootFolderName(),
            tenantAdminAuthorityName,
            tenantAuthenticatedAuthorityName,
            "Anonymous");
    userRoleDao.createUser(
        systemTenant, sysAdminUserName, "password", "", new String[] {tenantAdminAuthorityName});
    login(
        sysAdminUserName,
        systemTenant,
        new String[] {tenantAdminAuthorityName, tenantAuthenticatedAuthorityName});
    ITenant mainTenant_1 =
        tenantManager.createTenant(
            systemTenant,
            MAIN_TENANT_1,
            tenantAdminAuthorityName,
            tenantAuthenticatedAuthorityName,
            "Anonymous");
    userRoleDao.createUser(
        mainTenant_1, "admin", "password", "", new String[] {tenantAdminAuthorityName});
    ITenant mainTenant_2 =
        tenantManager.createTenant(
            systemTenant,
            MAIN_TENANT_2,
            tenantAdminAuthorityName,
            tenantAuthenticatedAuthorityName,
            "Anonymous");
    userRoleDao.createUser(
        mainTenant_2, "admin", "password", "", new String[] {tenantAdminAuthorityName});

    login(
        "admin",
        mainTenant_1,
        new String[] {tenantAdminAuthorityName, tenantAuthenticatedAuthorityName});
    IPentahoUser pentahoUser =
        userRoleDao.createUser(mainTenant_1, USER_2, PASSWORD_2, USER_DESCRIPTION_2, null);
    pentahoUser =
        userRoleDao.createUser(
            null,
            tenantedUserNameUtils.getPrincipleId(mainTenant_1, USER_3),
            PASSWORD_3,
            USER_DESCRIPTION_3,
            null);
    pentahoUser = userRoleDao.createUser(null, USER_4, PASSWORD_4, USER_DESCRIPTION_4, null);
    logout();

    login(
        "admin",
        mainTenant_2,
        new String[] {tenantAdminAuthorityName, tenantAuthenticatedAuthorityName});
    pentahoUser =
        userRoleDao.createUser(mainTenant_2, USER_5, PASSWORD_5, USER_DESCRIPTION_5, null);
    pentahoUser =
        userRoleDao.createUser(
            null,
            tenantedUserNameUtils.getPrincipleId(mainTenant_2, USER_6),
            PASSWORD_6,
            USER_DESCRIPTION_6,
            null);

    logout();

    login(
        "admin",
        mainTenant_1,
        new String[] {tenantAdminAuthorityName, tenantAuthenticatedAuthorityName});
    IPentahoRole pentahoRole =
        userRoleDao.createRole(mainTenant_1, ROLE_1, ROLE_DESCRIPTION_1, null);
    pentahoRole =
        userRoleDao.createRole(
            null,
            tenantedRoleNameUtils.getPrincipleId(mainTenant_1, ROLE_2),
            ROLE_DESCRIPTION_2,
            null);
    pentahoRole = userRoleDao.createRole(null, ROLE_3, ROLE_DESCRIPTION_3, null);
    logout();

    login(
        "admin",
        mainTenant_2,
        new String[] {tenantAdminAuthorityName, tenantAuthenticatedAuthorityName});
    pentahoRole = userRoleDao.createRole(mainTenant_2, ROLE_4, ROLE_DESCRIPTION_4, null);
    userRoleDao.setUserRoles(null, USER_5, new String[] {ROLE_4});
    userRoleDao.setUserRoles(
        null, tenantedUserNameUtils.getPrincipleId(mainTenant_2, USER_6), new String[] {ROLE_4});
    logout();
    login(
        "admin",
        mainTenant_1,
        new String[] {tenantAdminAuthorityName, tenantAuthenticatedAuthorityName});
    userRoleDao.setUserRoles(mainTenant_1, USER_2, new String[] {ROLE_1, ROLE_2, ROLE_3});

    List<String> systemRoles = Arrays.asList(new String[] {"Admin"});

    try {
      userRoleDao.setUserRoles(mainTenant_1, USER_3, new String[] {ROLE_2, ROLE_3, ROLE_4});
      fail("Exception should be thrown");
    } catch (Throwable th) {
      assertNotNull(th);
    }

    try {
      userRoleDao.setUserRoles(mainTenant_1, USER_4, new String[] {ROLE_2, ROLE_4});
      fail("Exception should be thrown");
    } catch (Throwable th) {
      assertNotNull(th);
    }
    UserRoleDaoUserDetailsService userDetailsService = new UserRoleDaoUserDetailsService();
    userDetailsService.setUserRoleDao(userRoleDao);
    userDetailsService.setDefaultRole(tenantAuthenticatedAuthorityName);

    List<String> extraRoles = Arrays.asList(new String[] {"Authenticated", "Anonymous"});
    String adminRole = "Admin";

    UserRoleDaoUserRoleListService service =
        new UserRoleDaoUserRoleListService(
            userRoleDao,
            userDetailsService,
            tenantedUserNameUtils,
            systemRoles,
            extraRoles,
            adminRole);
    service.setUserDetailsService(userDetailsService);

    logout();
    login(
        "admin",
        mainTenant_1,
        new String[] {tenantAdminAuthorityName, tenantAuthenticatedAuthorityName});
    List<String> rolesForUser_2 = service.getRolesForUser(mainTenant_1, USER_2);
    List<String> rolesForUser_2_1 = service.getRolesForUser(null, USER_2);
    List<String> rolesForUser_2_1_1 =
        service.getRolesForUser(null, tenantedUserNameUtils.getPrincipleId(mainTenant_1, USER_2));
    List<String> rolesForUser_3 = service.getRolesForUser(mainTenant_1, USER_3);
    List<String> rolesForUser_4 = service.getRolesForUser(mainTenant_1, USER_4);

    assertTrue(rolesForUser_2.size() == 4);
    assertTrue(rolesForUser_2_1.size() == 4);
    assertTrue(rolesForUser_2_1_1.size() == 4);
    assertTrue(rolesForUser_3.size() == 3);
    assertTrue(rolesForUser_4.size() == 2);

    cleanupUserAndRoles("admin", mainTenant_1);
    cleanupUserAndRoles("admin", mainTenant_2);
    cleanupUserAndRoles(sysAdminUserName, systemTenant);
  }
  @Test
  public void testGetAllUsernames() {
    loginAsRepositoryAdmin();
    ITenant systemTenant =
        tenantManager.createTenant(
            null,
            ServerRepositoryPaths.getPentahoRootFolderName(),
            tenantAdminAuthorityName,
            tenantAuthenticatedAuthorityName,
            "Anonymous");
    userRoleDao.createUser(
        systemTenant, sysAdminUserName, "password", "", new String[] {tenantAdminAuthorityName});
    login(
        sysAdminUserName,
        systemTenant,
        new String[] {tenantAdminAuthorityName, tenantAuthenticatedAuthorityName});
    ITenant mainTenant_1 =
        tenantManager.createTenant(
            systemTenant,
            MAIN_TENANT_1,
            tenantAdminAuthorityName,
            tenantAuthenticatedAuthorityName,
            "Anonymous");
    userRoleDao.createUser(
        mainTenant_1, "admin", "password", "", new String[] {tenantAdminAuthorityName});
    ITenant mainTenant_2 =
        tenantManager.createTenant(
            systemTenant,
            MAIN_TENANT_2,
            tenantAdminAuthorityName,
            tenantAuthenticatedAuthorityName,
            "Anonymous");
    userRoleDao.createUser(
        mainTenant_2, "admin", "password", "", new String[] {tenantAdminAuthorityName});

    login(
        "admin",
        mainTenant_1,
        new String[] {tenantAdminAuthorityName, tenantAuthenticatedAuthorityName});
    IPentahoUser pentahoUser =
        userRoleDao.createUser(mainTenant_1, USER_2, PASSWORD_2, USER_DESCRIPTION_2, null);
    pentahoUser =
        userRoleDao.createUser(mainTenant_1, USER_3, PASSWORD_3, USER_DESCRIPTION_3, null);
    pentahoUser =
        userRoleDao.createUser(
            null,
            tenantedUserNameUtils.getPrincipleId(mainTenant_1, USER_4),
            PASSWORD_4,
            USER_DESCRIPTION_4,
            null);
    pentahoUser = userRoleDao.createUser(null, USER_5, PASSWORD_5, USER_DESCRIPTION_5, null);
    pentahoUser =
        userRoleDao.createUser(
            null,
            tenantedUserNameUtils.getPrincipleId(mainTenant_1, USER_6),
            PASSWORD_6,
            USER_DESCRIPTION_6,
            null);
    logout();
    login(
        "admin",
        mainTenant_2,
        new String[] {tenantAdminAuthorityName, tenantAuthenticatedAuthorityName});
    pentahoUser =
        userRoleDao.createUser(mainTenant_2, USER_7, PASSWORD_7, USER_DESCRIPTION_7, null);
    pentahoUser = userRoleDao.createUser(null, USER_8, PASSWORD_8, USER_DESCRIPTION_8, null);
    UserRoleDaoUserDetailsService userDetailsService = new UserRoleDaoUserDetailsService();
    userDetailsService.setUserRoleDao(userRoleDao);

    List<String> systemRoles = Arrays.asList(new String[] {"Admin"});
    List<String> extraRoles = Arrays.asList(new String[] {"Authenticated", "Anonymous"});
    String adminRole = "Admin";

    UserRoleDaoUserRoleListService service =
        new UserRoleDaoUserRoleListService(
            userRoleDao,
            userDetailsService,
            tenantedUserNameUtils,
            systemRoles,
            extraRoles,
            adminRole);
    service.setUserRoleDao(userRoleDao);
    service.setUserDetailsService(userDetailsService);

    logout();
    login(
        "admin",
        mainTenant_1,
        new String[] {tenantAdminAuthorityName, tenantAuthenticatedAuthorityName});
    List<String> allUserForDefaultTenant = service.getAllUsers();
    List<String> allUserForTenant = service.getAllUsers(mainTenant_2);

    assertTrue(allUserForDefaultTenant.size() == 5 + DEFAULT_USER_COUNT);
    assertTrue(allUserForTenant.size() == 0);
    logout();
    login(
        "admin",
        mainTenant_2,
        new String[] {tenantAdminAuthorityName, tenantAuthenticatedAuthorityName});
    allUserForDefaultTenant = service.getAllUsers();
    allUserForTenant = service.getAllUsers(mainTenant_1);

    assertTrue(allUserForDefaultTenant.size() == 2 + DEFAULT_USER_COUNT);
    assertTrue(allUserForTenant.size() == 0);

    allUserForTenant = service.getAllUsers(mainTenant_1);

    assertTrue(allUserForTenant.size() == 0);
    allUserForTenant = service.getAllUsers(mainTenant_2);
    assertTrue(allUserForTenant.size() == 2 + DEFAULT_USER_COUNT);
    logout();

    login(
        "admin",
        mainTenant_1,
        new String[] {tenantAdminAuthorityName, tenantAuthenticatedAuthorityName});
    allUserForTenant = service.getAllUsers(mainTenant_1);
    assertTrue(allUserForTenant.size() == 5 + DEFAULT_USER_COUNT);

    allUserForTenant = service.getAllUsers(mainTenant_2);
    assertTrue(allUserForTenant.size() == 0);

    cleanupUserAndRoles("admin", mainTenant_1);
    cleanupUserAndRoles("admin", mainTenant_2);
    cleanupUserAndRoles(sysAdminUserName, systemTenant);
  }