org.apache.jackrabbit.api.security.user.Group Java Examples

The following examples show how to use org.apache.jackrabbit.api.security.user.Group. 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: AdminPermissionCheckerTest.java    From jackrabbit-filevault with Apache License 2.0 6 votes vote down vote up
@Test
public void testAdditionalAdminGroup() throws Exception {
    JackrabbitSession jackrabbitSession = (JackrabbitSession) admin;
    Authorizable admins = jackrabbitSession.getUserManager().getAuthorizable("myadmins");
    if (admins == null) {
        admins = jackrabbitSession.getUserManager().createGroup("myadmins");
    }
    Group adminsGroup = (Group) admins;
    User testUser = (User) jackrabbitSession.getUserManager().getAuthorizable(TEST_USER);
    if (testUser == null) {
        testUser = jackrabbitSession.getUserManager().createUser(TEST_USER, TEST_USER);
    }
    adminsGroup.addMember(testUser);
    admin.save();
    Session session = repository.login(new SimpleCredentials(TEST_USER, TEST_USER.toCharArray()));
    try {
        assertTrue(
                "user \"" + TEST_USER + "\" has been added to additional administrators group thus should have admin permissions",
                AdminPermissionChecker.hasAdministrativePermissions(session, "myadmins"));
    } finally {
        session.logout();
    }
}
 
Example #2
Source File: ClearFromGroupDetacher.java    From APM with Apache License 2.0 6 votes vote down vote up
public ActionResult detachMembersFromGroup() {
  ActionResult actionResult = context.createActionResult();

  try {
    Authorizable authorizable = context.getCurrentAuthorizable();

    if (authorizable.isGroup()) {
      final Group group = context.getCurrentGroup();
      LOGGER.info(String.format("Removing all members of group with id = %s", group.getID()));
      Iterator<Authorizable> groupMembers = getGroupMembers(actionResult, group);

      detachAllMembers(actionResult, group, groupMembers);
    } else {
      actionResult.logError("Child members can only be removed from groups");
    }
  } catch (RepositoryException | ActionExecutionException e) {
    actionResult.logError(MessagingUtils.createMessage(e));
  }
  return actionResult;
}
 
Example #3
Source File: ForAuthorizable.java    From APM with Apache License 2.0 6 votes vote down vote up
public ActionResult process(final Context context) {
  ActionResult actionResult = context.createActionResult();
  try {

    if (shouldBeGroup) {
      Group group = context.getAuthorizableManager().getGroup(id);
      context.setCurrentAuthorizable(group);
      actionResult.logMessage("Group with id: " + group.getID() + " set as current authorizable");
    } else {
      User user = context.getAuthorizableManager().getUser(id);
      context.setCurrentAuthorizable(user);
      actionResult.logMessage("User with id: " + user.getID() + " set as current authorizable");
    }

  } catch (RepositoryException | ActionExecutionException e) {
    actionResult.logError(MessagingUtils.createMessage(e));
  }
  return actionResult;
}
 
Example #4
Source File: CheckIncludes.java    From APM with Apache License 2.0 6 votes vote down vote up
private boolean checkMembers(final Context context, final ActionResult actionResult,
    final Group authorizable, final List<String> errors) {
  boolean checkFailed = false;
  for (String id : groupIds) {
    try {
      Authorizable group = context.getAuthorizableManager().getAuthorizable(id);

      if (!authorizable.isMember(group)) {
        actionResult.logError(id + " is excluded from group " + authorizableId);
        checkFailed = true;
      }
      actionResult.logMessage(id + " is a member of group " + authorizableId);
    } catch (RepositoryException | ActionExecutionException e) {
      errors.add(MessagingUtils.createMessage(e));
    }
  }
  return checkFailed;
}
 
Example #5
Source File: CheckIncludes.java    From APM with Apache License 2.0 6 votes vote down vote up
private ActionResult process(final Context context, boolean execute) {
  ActionResult actionResult = context.createActionResult();
  Group authorizable = tryGetGroup(context, actionResult);
  if (authorizable == null) {
    return actionResult;
  }

  List<String> errors = new ArrayList<>();

  boolean checkFailed = checkMembers(context, actionResult, authorizable, errors);

  if (execute && checkFailed) {
    actionResult.logError(ActionUtils.ASSERTION_FAILED_MSG);
    return actionResult;
  }

  ActionUtils.logErrors(errors, actionResult);

  return actionResult;

}
 
Example #6
Source File: CheckExcludes.java    From APM with Apache License 2.0 6 votes vote down vote up
private boolean checkMembers(final Context context, final ActionResult actionResult, final Group group,
    final List<String> errors) {
  boolean checkFailed = false;
  for (String authorizableId : authorizableIds) {
    try {
      Authorizable authorizable = context.getAuthorizableManager().getAuthorizableIfExists(authorizableId);
      if (authorizable == null) {
        actionResult.logWarning(MessagingUtils.authorizableNotExists(authorizableId));
        continue;
      }
      if (group.isMember(authorizable)) {
        actionResult.logError(authorizable.getID() + " belongs to group " + groupId);
        checkFailed = true;
      }
    } catch (RepositoryException e) {
      errors.add(MessagingUtils.createMessage(e));
    }
  }
  return checkFailed;
}
 
Example #7
Source File: CheckExcludes.java    From APM with Apache License 2.0 6 votes vote down vote up
private ActionResult process(final Context context, boolean execute) {

    ActionResult actionResult = context.createActionResult();
    Group group = tryGetGroup(context, actionResult);
    if (group == null) {
      return actionResult;
    }

    List<String> errors = new ArrayList<>();

    boolean checkFailed = checkMembers(context, actionResult, group, errors);

    if (execute && checkFailed) {
      actionResult.logError(ActionUtils.ASSERTION_FAILED_MSG);
      return actionResult;
    }

    ActionUtils.logErrors(errors, actionResult);

    return actionResult;
  }
 
Example #8
Source File: UserServiceImpl.java    From publick-sling-blog with Apache License 2.0 6 votes vote down vote up
/**
 * Get the authorable status of the current user.
 *
 * @param session The current session.
 * @return true if the current user is an admin or author.
 */
public boolean isAuthorable(Session session) {
    boolean authorable = false;

    JackrabbitSession js = (JackrabbitSession)session;

    try {
        Group authors = (Group)js.getUserManager().getAuthorizable(PublickConstants.GROUP_ID_AUTHORS);
        User user = (User)js.getUserManager().getAuthorizable(js.getUserID());

        authorable = user.isAdmin() || authors.isMember(user);
    } catch (RepositoryException e) {
        LOGGER.error("Could not determine group membership", e);
    }

    return authorable;
}
 
Example #9
Source File: WCMUse.java    From publick-sling-blog with Apache License 2.0 6 votes vote down vote up
/**
 * Get the authorable status of the current user.
 * TODO: remove and use UserService
 *
 * @return true if the current user is an admin or author.
 */
public boolean isAuthorable() {
    boolean authorable = false;

    JackrabbitSession js = (JackrabbitSession)getSession();

    try {
        Group authors = (Group)js.getUserManager().getAuthorizable(PublickConstants.GROUP_ID_AUTHORS);
        User user = (User)js.getUserManager().getAuthorizable(js.getUserID());

        authorable = user.isAdmin() || authors.isMember(user);
    } catch (RepositoryException e) {
        LOGGER.error("Could not determine group membership", e);
    }

    return authorable;
}
 
Example #10
Source File: TestGroupMergePackage.java    From jackrabbit-filevault with Apache License 2.0 6 votes vote down vote up
/**
 * Installs a package that contains a "test-group" and a "test-user-a" as member of the group.
 */
@Test
public void installGroupA() throws RepositoryException, IOException, PackageException {
    UserManager mgr = ((JackrabbitSession) admin).getUserManager();
    assertNull("test-group must not exist", mgr.getAuthorizable("test-group"));
    assertNull("test-user-a must not exist", mgr.getAuthorizable("test-user-a"));

    JcrPackage pack = packMgr.upload(getStream("/test-packages/group_with_a.zip"), false);
    assertNotNull(pack);
    pack.install(getDefaultOptions());

    // check if group exists
    Group grp = (Group) mgr.getAuthorizable("test-group");
    assertNotNull("test-group must exist", grp);
    User userA = (User) mgr.getAuthorizable("test-user-a");
    assertNotNull("test-user-a must exist", userA);
    assertTrue("test-user-a is member of test-group", grp.isMember(userA));
}
 
Example #11
Source File: AdminPermissionCheckerTest.java    From jackrabbit-filevault with Apache License 2.0 6 votes vote down vote up
@Test
public void testAdminGroup() throws Exception {
    JackrabbitSession jackrabbitSession = (JackrabbitSession) admin;
    Authorizable admins = jackrabbitSession.getUserManager().getAuthorizable("administrators");
    if (admins == null) {
        admins = jackrabbitSession.getUserManager().createGroup("administrators");
    }
    Group adminsGroup = (Group) admins;
    User testUser = (User) jackrabbitSession.getUserManager().getAuthorizable(TEST_USER);
    if (testUser == null) {
        testUser = jackrabbitSession.getUserManager().createUser(TEST_USER, TEST_USER);
    }
    adminsGroup.addMember(testUser);
    admin.save();
    Session session = repository.login(new SimpleCredentials(TEST_USER, TEST_USER.toCharArray()));
    try {
        assertTrue(
                "user \"" + TEST_USER + "\" has been added to administrators group thus should have admin permissions",
                AdminPermissionChecker.hasAdministrativePermissions(session));
    } finally {
        session.logout();
    }
}
 
Example #12
Source File: ContextImpl.java    From APM with Apache License 2.0 5 votes vote down vote up
@Override
public User getCurrentUser() throws ActionExecutionException {
  if (getCurrentAuthorizable() instanceof Group) {
    throw new ActionExecutionException("Current authorizable is not a user");
  }
  return (User) currentAuthorizable;
}
 
Example #13
Source File: ContextImpl.java    From APM with Apache License 2.0 5 votes vote down vote up
@Override
public Group getCurrentGroup() throws ActionExecutionException {
  if (getCurrentAuthorizable() instanceof User) {
    throw new ActionExecutionException("Current authorizable is not a group");
  }
  return (Group) currentAuthorizable;
}
 
Example #14
Source File: AdminPermissionChecker.java    From jackrabbit-filevault with Apache License 2.0 5 votes vote down vote up
/**
 * Checks if the user who opened the session has administrative permissions
 *
 * @param session a JCR session
 * @return whether the passed session is an admin session
 * @throws RepositoryException If an error occurrs.
 */
public static boolean hasAdministrativePermissions(@NotNull Session session, String... additionalAdminAuthorizableIds) throws RepositoryException {
    String userId = session.getUserID();
    if (ADMIN_USER.equals(userId) || SYSTEM_USER.equals(userId)) {
        return true;
    }
    List<String> additionalAdminIds = Arrays.asList(Optional.ofNullable(additionalAdminAuthorizableIds).orElse(new String[0]));
    if (additionalAdminIds.contains(userId)) {
        return true;
    }
    if (!(session instanceof JackrabbitSession)) {
        log.warn("could not evaluate group permissions but just user name");
        return false;
    }

    JackrabbitSession jackrabbitSession = (JackrabbitSession) session;
    Authorizable authorizable = jackrabbitSession.getUserManager().getAuthorizable(userId);
    if (authorizable == null) {
        return false;
    }

    Iterator<Group> groupIterator = authorizable.memberOf();
    while (groupIterator.hasNext()) {
        String groupId = groupIterator.next().getID();
        if (ADMINISTRATORS_GROUP.equals(groupId)) {
            return true;
        }
        if (additionalAdminIds.contains(groupId)) {
            return true;
        }
    }

    return false;
}
 
Example #15
Source File: TestUserContentPackage.java    From jackrabbit-filevault with Apache License 2.0 5 votes vote down vote up
private void install_moved_user_with_rep_cache(ImportMode mode) throws RepositoryException, IOException, PackageException {
    UserManager mgr = ((JackrabbitSession) admin).getUserManager();
    User u = mgr.createUser(ID_TEST_USER_A, ID_TEST_PASSWORD);
    String newPath = u.getPath() + "_moved";
    admin.move(u.getPath(), newPath);
    admin.save();

    Group g = mgr.createGroup(ID_TEST_GROUP_A);
    g.addMember(u);
    admin.save();

    // login to the repository to generate some rep:cache nodes
    repository.login(new SimpleCredentials(ID_TEST_USER_A, ID_TEST_PASSWORD.toCharArray())).logout();
    admin.refresh(false);

    // ensure that there is a rep:cache node
    assertNodeExists(newPath + "/rep:cache");

    // install user package
    JcrPackage pack = packMgr.upload(getStream("/test-packages/test_user_a.zip"), false);
    assertNotNull(pack);
    ImportOptions opts = getDefaultOptions();
    opts.setImportMode(mode);
    pack.install(opts);

    // check if user exists
    User userA = (User) mgr.getAuthorizable(ID_TEST_USER_A);
    assertNotNull("test-user-a must exist", userA);
}
 
Example #16
Source File: TestGroupMergePackage.java    From jackrabbit-filevault with Apache License 2.0 5 votes vote down vote up
private void assertABC(UserManager mgr) throws RepositoryException {
    // check if group exists
    Group grp = (Group) mgr.getAuthorizable("test-group");
    assertNotNull("test-group must exist", grp);
    User userA = (User) mgr.getAuthorizable("test-user-a");
    User userB = (User) mgr.getAuthorizable("test-user-b");
    User userC = (User) mgr.getAuthorizable("test-user-c");
    assertNotNull("test-user-a must exist", userA);
    assertNotNull("test-user-b must exist", userB);
    assertNotNull("test-user-c must exist", userC);

    assertTrue("test-user-a is member of test-group", grp.isMember(userA));
    assertTrue("test-user-b is member of test-group", grp.isMember(userB));
    assertTrue("test-user-c is member of test-group", grp.isMember(userC));
}
 
Example #17
Source File: AuthorizableManagerImpl.java    From APM with Apache License 2.0 5 votes vote down vote up
@Override
public void removeUser(User user) throws RepositoryException {
  Iterator<Group> groups = user.memberOf();
  while (groups.hasNext()) {
    groups.next().removeMember(user);
  }
  existingAuthorizables.remove(user.getID());
  user.remove();
}
 
Example #18
Source File: AuthorizableManagerImpl.java    From APM with Apache License 2.0 5 votes vote down vote up
@Override
public Group createMockGroup(String id) {
  Group group = new MockGroup(id);
  existingAuthorizables.put(id, group);
  removedAuthorizables.remove(id);
  return group;
}
 
Example #19
Source File: AuthorizableManagerImpl.java    From APM with Apache License 2.0 5 votes vote down vote up
@Override
public Group createGroup(String id, Principal namePrincipal, String path) throws RepositoryException {
  Group group = userManager.createGroup(id, namePrincipal, path);
  existingAuthorizables.put(id, group);
  removedAuthorizables.remove(id);
  return group;
}
 
Example #20
Source File: ClearFromGroupDetacher.java    From APM with Apache License 2.0 5 votes vote down vote up
private void detachAllMembers(final ActionResult actionResult, final Group group,
    Iterator<Authorizable> groupMembers) throws RepositoryException {
  while (groupMembers.hasNext()) {
    Authorizable currentMember = groupMembers.next();
    if (currentMember.isGroup()) {
      if (!simulate) {
        group.removeMember(currentMember);
      }
      actionResult
          .logMessage(MessagingUtils.removedFromGroup(currentMember.getID(), group.getID()));
    }
  }
}
 
Example #21
Source File: DestroyUser.java    From APM with Apache License 2.0 5 votes vote down vote up
private List<String> getGroups(User user) throws RepositoryException {
  List<String> groups = new ArrayList<>();
  Iterator<Group> groupIterator = user.declaredMemberOf();
  while (groupIterator.hasNext()) {
    Group group = groupIterator.next();
    groups.add(group.getID());
  }
  return groups;
}
 
Example #22
Source File: DeleteGroup.java    From APM with Apache License 2.0 5 votes vote down vote up
private ActionResult process(final Context context, boolean execute) {
  ActionResult actionResult = context.createActionResult();

  List<String> errors = new ArrayList<>();
  LOGGER.info(String.format("Removing groups with ids = %s", StringUtils.join(ids, ", ")));
  for (String id : ids) {
    try {
      Group group = context.getAuthorizableManager().getGroupIfExists(id);
      if (group != null) {
        context.getAuthorizableManager().markAuthorizableAsRemoved(group);
        if (execute) {
          context.getAuthorizableManager().removeGroup(group);
        }
        actionResult.logMessage("Group with id: " + id + " removed");
      }

    } catch (RepositoryException | ActionExecutionException e) {
      errors.add(MessagingUtils.createMessage(e));
    }
  }
  if (!errors.isEmpty()) {
    for (String error : errors) {
      actionResult.logError(error);
    }
    actionResult.logError("Execution interrupted");
  }
  return actionResult;
}
 
Example #23
Source File: ClearFromGroupDetacher.java    From APM with Apache License 2.0 5 votes vote down vote up
private Iterator<Authorizable> getGroupMembers(final ActionResult actionResult, final Group group)
    throws RepositoryException {
  String id = group.getID();
  actionResult.setAuthorizable(id);
  Iterator<Authorizable> groupMembers = group.getDeclaredMembers();
  if (!groupMembers.hasNext()) {
    actionResult.logWarning(MessagingUtils.groupHasNoMembers(id));
  }
  return groupMembers;
}
 
Example #24
Source File: ClearFromGroupDetacher.java    From APM with Apache License 2.0 5 votes vote down vote up
private Iterator<Group> getGroupParents(final ActionResult actionResult, final Authorizable authorizable)
    throws RepositoryException {
  String id = authorizable.getID();
  actionResult.setAuthorizable(id);
  Iterator<Group> groups = authorizable.memberOf();
  if (!groups.hasNext()) {
    actionResult.logWarning(MessagingUtils.groupIsMemberOfNoGroups(id));
  }
  return groups;
}
 
Example #25
Source File: ClearFromGroupDetacher.java    From APM with Apache License 2.0 5 votes vote down vote up
private void detachFromParents(final ActionResult actionResult, final Authorizable authorizable,
    Iterator<Group> groups) throws RepositoryException {
  while (groups.hasNext()) {
    Group currentGroup = groups.next();
    if (currentGroup.isGroup()) {
      if (!simulate) {
        currentGroup.removeMember(authorizable);
      }
      actionResult.logMessage(
          MessagingUtils.removedFromGroup(authorizable.getID(), currentGroup.getID()));
    }
  }
}
 
Example #26
Source File: ClearFromGroupDetacher.java    From APM with Apache License 2.0 5 votes vote down vote up
public ActionResult detachAuthorizableFromParents() {
  ActionResult actionResult = context.createActionResult();

  try {
    Authorizable currentAuthorizable = context.getCurrentAuthorizable();
    Iterator<Group> groups = getGroupParents(actionResult, currentAuthorizable);

    LOGGER.info(String.format("Removing all memberships of authorizable with id = %s",
        currentAuthorizable.getID()));
    detachFromParents(actionResult, currentAuthorizable, groups);
  } catch (RepositoryException | ActionExecutionException e) {
    actionResult.logError(MessagingUtils.createMessage(e));
  }
  return actionResult;
}
 
Example #27
Source File: CreateAuthorizable.java    From APM with Apache License 2.0 5 votes vote down vote up
private void logMessage(ActionResult actionResult, Authorizable authorizable) throws RepositoryException {
  if (!ignoreIfExists) {
    if (authorizable instanceof Group) {
      actionResult.logError(MessagingUtils.authorizableExists(authorizable.getID(), "Group"));
    } else {
      actionResult.logError(MessagingUtils.authorizableExists(authorizable.getID(), "User"));
    }
  } else {
    if (authorizable instanceof Group) {
      actionResult.logWarning(MessagingUtils.authorizableExists(authorizable.getID(), "Group"));
    } else {
      actionResult.logWarning(MessagingUtils.authorizableExists(authorizable.getID(), "User"));
    }
  }
}
 
Example #28
Source File: ActionUtils.java    From APM with Apache License 2.0 5 votes vote down vote up
/**
 * Adding group to another group may result in cyclic relation. Let current group be the group where we
 * want to add current authorizable to. If current authorizable contains group such that current group
 * belongs to, then we prevent such operation.
 *
 * @param currentGroup   The group where we want to add current authorizable
 * @param groupToBeAdded Authorizable we want to add
 * @throws ActionExecutionException Throw exception, if adding operation results in cyclic relation
 */
public static void checkCyclicRelations(Group currentGroup, Group groupToBeAdded)
		throws ActionExecutionException {
	try {
		if (groupToBeAdded.getID().equals(currentGroup.getID())) {
			throw new ActionExecutionException(MessagingUtils.addingGroupToItself(currentGroup.getID()));
		}
		Iterator<Group> parents = currentGroup.memberOf();
		while (parents.hasNext()) {
			Group currentParent = parents.next();
			// Is added group among my parents?
			if (currentParent.getID().equals(groupToBeAdded.getID())) {
				throw new ActionExecutionException(MessagingUtils.cyclicRelationsForbidden(
						currentGroup.getID(), groupToBeAdded.getID()));
			}
			// ... and are its children among my parents?
			for (Iterator<Authorizable> children = groupToBeAdded.getMembers(); children.hasNext(); ) {
				Authorizable currentChild = children.next();
				if (currentParent.getID().equals(currentChild.getID())) {
					throw new ActionExecutionException(MessagingUtils.cyclicRelationsForbidden(
							currentChild.getID(), groupToBeAdded.getID()));
				}
			}
		}
	} catch (RepositoryException e) {
		throw new ActionExecutionException(MessagingUtils.createMessage(e));
	}
}
 
Example #29
Source File: CheckIncludes.java    From APM with Apache License 2.0 5 votes vote down vote up
private Group tryGetGroup(final Context context, final ActionResult actionResult) {
  try {
    return context.getAuthorizableManager().getGroup(authorizableId);
  } catch (RepositoryException | ActionExecutionException e) {
    actionResult.logError(MessagingUtils.createMessage(e));
  }
  return null;
}
 
Example #30
Source File: ActionUtils.java    From APM with Apache License 2.0 5 votes vote down vote up
/**
 * Adding group to another group may result in cyclic relation. Let current group be the group where we
 * want to add current authorizable to. If current authorizable contains group such that current group
 * belongs to, then we prevent such operation.
 *
 * @param currentGroup   The group where we want to add current authorizable
 * @param groupToBeAdded Authorizable we want to add
 * @throws ActionExecutionException Throw exception, if adding operation results in cyclic relation
 */
public static void checkCyclicRelations(Group currentGroup, Group groupToBeAdded)
		throws ActionExecutionException {
	try {
		if (groupToBeAdded.getID().equals(currentGroup.getID())) {
			throw new ActionExecutionException(MessagingUtils.addingGroupToItself(currentGroup.getID()));
		}
		Iterator<Group> parents = currentGroup.memberOf();
		while (parents.hasNext()) {
			Group currentParent = parents.next();
			// Is added group among my parents?
			if (currentParent.getID().equals(groupToBeAdded.getID())) {
				throw new ActionExecutionException(MessagingUtils.cyclicRelationsForbidden(
						currentGroup.getID(), groupToBeAdded.getID()));
			}
			// ... and are its children among my parents?
			for (Iterator<Authorizable> children = groupToBeAdded.getMembers(); children.hasNext(); ) {
				Authorizable currentChild = children.next();
				if (currentParent.getID().equals(currentChild.getID())) {
					throw new ActionExecutionException(MessagingUtils.cyclicRelationsForbidden(
							currentChild.getID(), groupToBeAdded.getID()));
				}
			}
		}
	} catch (RepositoryException e) {
		throw new ActionExecutionException(MessagingUtils.createMessage(e));
	}
}