Handler fro user and group extracted from managers

This commit is contained in:
lucio 2024-03-27 22:23:30 +01:00
parent 335204d3ee
commit 26bc4c93ac
5 changed files with 793 additions and 655 deletions

View File

@ -14,9 +14,9 @@ services:
ports:
- '5423:5432'
volumes:
- ./postgres-data:/var/lib/postgresql/data
- /data/postgres-data:/var/lib/postgresql/data
copy the sql script to create tables
- ./sql/create_tables.sql:/docker-entrypoint-initdb.d/create_tables.sql
- /data/sql/create_tables.sql:/docker-entrypoint-initdb.d/create_tables.sql
storagehub:
build:
dockerfile: Dockerfile-standalone

View File

@ -1,7 +1,12 @@
package org.gcube.data.access.storagehub.handlers;
import jakarta.inject.Inject;
import jakarta.inject.Singleton;
import java.security.Principal;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Iterator;
import java.util.List;
import java.util.Objects;
import javax.jcr.ItemNotFoundException;
import javax.jcr.Node;
import javax.jcr.NodeIterator;
@ -9,21 +14,41 @@ import javax.jcr.PathNotFoundException;
import javax.jcr.RepositoryException;
import javax.jcr.security.AccessControlEntry;
import javax.jcr.security.AccessControlManager;
import javax.jcr.security.Privilege;
import org.apache.jackrabbit.api.JackrabbitSession;
import org.apache.jackrabbit.api.security.JackrabbitAccessControlList;
import org.apache.jackrabbit.api.security.user.Authorizable;
import org.apache.jackrabbit.api.security.user.Group;
import org.apache.jackrabbit.api.security.user.Query;
import org.apache.jackrabbit.api.security.user.QueryBuilder;
import org.apache.jackrabbit.api.security.user.User;
import org.apache.jackrabbit.commons.jackrabbit.authorization.AccessControlUtils;
import org.gcube.common.security.ContextBean;
import org.gcube.common.security.ContextBean.Type;
import org.gcube.common.security.providers.SecretManagerProvider;
import org.gcube.common.storagehub.model.Excludes;
import org.gcube.common.storagehub.model.Paths;
import org.gcube.common.storagehub.model.acls.AccessType;
import org.gcube.common.storagehub.model.exceptions.InvalidCallParameters;
import org.gcube.common.storagehub.model.exceptions.NotFoundException;
import org.gcube.common.storagehub.model.exceptions.StorageHubException;
import org.gcube.common.storagehub.model.items.Item;
import org.gcube.common.storagehub.model.types.NodeProperty;
import org.gcube.common.storagehub.model.types.PrimaryNodeType;
import org.gcube.data.access.storagehub.Constants;
import org.gcube.data.access.storagehub.PathUtil;
import org.gcube.data.access.storagehub.StorageHubAppllicationManager;
import org.gcube.data.access.storagehub.Utils;
import org.gcube.data.access.storagehub.handlers.items.builders.FolderCreationParameters;
import org.gcube.data.access.storagehub.services.GroupManager;
import org.gcube.data.access.storagehub.services.RepositoryInitializer;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import jakarta.inject.Inject;
import jakarta.inject.Singleton;
@Singleton
public class GroupHandler {
@ -32,35 +57,200 @@ public class GroupHandler {
@Inject
PathUtil pathUtil;
public boolean removeUserFromGroup(String groupId, String userId, JackrabbitSession session) throws StorageHubException, RepositoryException {
@Inject
TrashHandler trashHandler;
RepositoryInitializer repository = StorageHubAppllicationManager.getRepository();
public List<String> getGroups(JackrabbitSession session) throws RepositoryException {
List<String> groups = new ArrayList<>();
session = (JackrabbitSession) repository.getRepository().login(Constants.JCR_CREDENTIALS);
Iterator<Authorizable> result = session.getUserManager().findAuthorizables(new Query() {
@Override
public <T> void build(QueryBuilder<T> builder) {
builder.setSelector(Group.class);
}
});
while (result.hasNext()) {
Authorizable group = result.next();
log.info("group {} found", group.getPrincipal().getName());
groups.add(group.getPrincipal().getName());
}
return groups;
}
public void createGroup(JackrabbitSession session, String groupId, AccessType accessType, String folderOwner,
boolean useDefaultStorage) throws StorageHubException, Throwable {
log.info("create group called with groupid {} , accessType {} and folderOwner {}", groupId, accessType,
folderOwner);
org.apache.jackrabbit.api.security.user.UserManager usrManager = session.getUserManager();
Group group = (Group)usrManager.getAuthorizable(groupId);
User user = (User)usrManager.getAuthorizable(userId);
Group createdGroup = usrManager.createGroup(groupId);
User user = (User) usrManager.getAuthorizable(folderOwner);
createVreFolder(session, groupId, accessType != null ? accessType : AccessType.WRITE_OWNER, folderOwner,
useDefaultStorage);
boolean success = this.internalAddUserToGroup(session, createdGroup, user);
if (!success)
log.warn("the user have not been added to the group");
else
log.debug("the user have been added to the group");
}
public void deleteGroup(JackrabbitSession session, String group) throws RepositoryException {
org.apache.jackrabbit.api.security.user.UserManager usrManager = session.getUserManager();
Authorizable authorizable = usrManager.getAuthorizable(group);
if (authorizable != null && authorizable.isGroup())
authorizable.remove();
try {
Node node = this.getFolderNodeRelatedToGroup(session, group);
List<Item> workspaceItems = Utils.getItemList(node, Excludes.GET_ONLY_CONTENT, null, true, null);
trashHandler.removeOnlyNodesContent(session, workspaceItems);
node.removeSharedSet();
} catch (Exception e) {
log.warn("vreFolder {} not found, removing only the group", group);
}
}
public void addAdministratorToGroup(JackrabbitSession session, String groupId, String userId)
throws StorageHubException, Throwable {
Objects.nonNull(groupId);
Objects.nonNull(userId);
Node vreFolder = this.getFolderNodeRelatedToGroup(session, groupId);
org.apache.jackrabbit.api.security.user.UserManager usrManager = ((JackrabbitSession) session).getUserManager();
Group group = (Group) usrManager.getAuthorizable(groupId);
User authUser = (User) usrManager.getAuthorizable(userId);
if (group == null)
throw new NotFoundException("group", groupId);
if (authUser == null)
throw new NotFoundException("user", userId);
if (!group.isMember(authUser))
throw new InvalidCallParameters(String.format("user %s is not in the group %s", userId, groupId));
AccessControlManager acm = session.getAccessControlManager();
JackrabbitAccessControlList acls = AccessControlUtils.getAccessControlList(acm, vreFolder.getPath());
Privilege[] userPrivileges = new Privilege[] { acm.privilegeFromName(AccessType.ADMINISTRATOR.getValue()) };
Principal principal = AccessControlUtils.getPrincipal(session, userId);
acls.addAccessControlEntry(principal, userPrivileges);
acm.setPolicy(vreFolder.getPath(), acls);
}
public void removeAdministratorFromGroup(JackrabbitSession session, String groupId, String userId)
throws StorageHubException, Throwable {
Objects.nonNull(groupId);
Objects.nonNull(userId);
if (!this.getGroupAdministators(session, groupId).contains(userId))
throw new InvalidCallParameters(String.format("user %s is not admin of the group %s", userId, groupId));
Node vreFolder = this.getFolderNodeRelatedToGroup(session, groupId);
org.apache.jackrabbit.api.security.user.UserManager usrManager = ((JackrabbitSession) session).getUserManager();
Group group = (Group) usrManager.getAuthorizable(groupId);
User authUser = (User) usrManager.getAuthorizable(userId);
if (group == null)
throw new NotFoundException("group", groupId);
if (authUser == null)
throw new NotFoundException("user", userId);
AccessControlManager acm = session.getAccessControlManager();
JackrabbitAccessControlList acls = AccessControlUtils.getAccessControlList(acm, vreFolder.getPath());
AccessControlEntry toRemove = null;
for (AccessControlEntry acl : acls.getAccessControlEntries())
if (acl.getPrincipal().getName().equals(userId)) {
toRemove = acl;
break;
}
acls.removeAccessControlEntry(toRemove);
acm.setPolicy(vreFolder.getPath(), acls);
}
public List<String> getGroupAdministators(JackrabbitSession session, String groupId) throws Throwable {
List<String> users = new ArrayList<String>();
Node node = getFolderNodeRelatedToGroup(session, groupId);
AccessControlManager acm = session.getAccessControlManager();
JackrabbitAccessControlList acls = AccessControlUtils.getAccessControlList(acm, node.getPath());
for (AccessControlEntry acl : acls.getAccessControlEntries())
for (Privilege pr : acl.getPrivileges()) {
if (pr.getName().equals(AccessType.ADMINISTRATOR.getValue())) {
users.add(acl.getPrincipal().getName());
}
}
return users;
}
public void addUserToGroup(JackrabbitSession session, String userId, String groupId) throws StorageHubException, RepositoryException {
org.apache.jackrabbit.api.security.user.UserManager usrManager = session.getUserManager();
Group group = (Group) usrManager.getAuthorizable(groupId);
User user = (User) usrManager.getAuthorizable(userId);
if (user == null)
throw new InvalidCallParameters("user " + userId + " not exists");
if (group.isMember(user))
throw new InvalidCallParameters("user " + userId + " is already member of group " + groupId);
this.internalAddUserToGroup(session, group, user);
}
public boolean removeUserFromGroup(JackrabbitSession session, String groupId, String userId)
throws StorageHubException, RepositoryException {
org.apache.jackrabbit.api.security.user.UserManager usrManager = session.getUserManager();
Group group = (Group) usrManager.getAuthorizable(groupId);
User user = (User) usrManager.getAuthorizable(userId);
if (!group.isMember(user))
throw new InvalidCallParameters("user "+userId+" is not member of group "+groupId);
throw new InvalidCallParameters(String.format("user %s is not in the group %s", userId, groupId));
//delete folder on user
String folderName = group.getPrincipal().getName();
// delete folder on user
String folderName = group.getPrincipal().getName();
Node folder = getFolderNodeRelatedToGroup(session, folderName);
//Removing the ACL for the user
// Removing the ACL for the user
AccessControlManager acm = session.getAccessControlManager();
JackrabbitAccessControlList acls = AccessControlUtils.getAccessControlList(acm, folder.getPath());
AccessControlEntry entryToDelete= null;
for (AccessControlEntry ace :acls.getAccessControlEntries()) {
AccessControlEntry entryToDelete = null;
for (AccessControlEntry ace : acls.getAccessControlEntries()) {
if (ace.getPrincipal().getName().equals(userId)) {
entryToDelete = ace;
break;
}
}
if (entryToDelete!=null)
if (entryToDelete != null)
acls.removeAccessControlEntry(entryToDelete);
boolean found = false;
NodeIterator ni = folder.getSharedSet();
while (ni.hasNext()) {
@ -72,35 +262,130 @@ public class GroupHandler {
}
}
if (!found)
log.warn("sharing not removed for user {} ",userId);
log.warn("sharing not removed for user {} ", userId);
return group.removeMember(user);
}
public List<String> getUsersBelongingToGroup(JackrabbitSession session, String groupId)
throws StorageHubException, RepositoryException {
List<String> users = new ArrayList<>();
org.apache.jackrabbit.api.security.user.UserManager usrManager = session.getUserManager();
Group group = (Group) usrManager.getAuthorizable(groupId);
Iterator<Authorizable> it = group.getMembers();
while (it.hasNext()) {
Authorizable user = it.next();
users.add(user.getPrincipal().getName());
}
return users;
}
public Node getFolderNodeRelatedToGroup(JackrabbitSession session, String name) throws ItemNotFoundException, RepositoryException {
public Node getFolderNodeRelatedToGroup(JackrabbitSession session, String name)
throws ItemNotFoundException, RepositoryException {
Node sharedRootNode = session.getNode(Constants.SHARED_FOLDER_PATH);
Node vreFolder = null;
try {
vreFolder = sharedRootNode.getNode(name);
}catch (PathNotFoundException e) {
} catch (PathNotFoundException e) {
log.debug("is an old HL VRE");
}
if (vreFolder==null) {
if (vreFolder == null) {
NodeIterator nodes = sharedRootNode.getNodes();
while (nodes.hasNext()) {
Node node = nodes.nextNode();
if (node.hasProperty(NodeProperty.TITLE.toString()) && node.getProperty(NodeProperty.TITLE.toString()).getString().equals(name)) {
vreFolder= node;
if (node.hasProperty(NodeProperty.TITLE.toString())
&& node.getProperty(NodeProperty.TITLE.toString()).getString().equals(name)) {
vreFolder = node;
break;
}
}
}
if (vreFolder==null) throw new ItemNotFoundException("vre folder not found for group "+name);
if (vreFolder == null)
throw new ItemNotFoundException("vre folder not found for group " + name);
return vreFolder;
}
private void createVreFolder(JackrabbitSession session, String groupId, AccessType defaultAccessType, String owner,
boolean useDefaultStorage) throws Exception {
Node sharedRootNode = session.getNode(Constants.SHARED_FOLDER_PATH);
String name = groupId;
String currentScope = SecretManagerProvider.get().getContext();
ContextBean bean = new ContextBean(currentScope);
while (!bean.is(Type.INFRASTRUCTURE)) {
bean = bean.enclosingScope();
}
String root = bean.toString().replaceAll("/", "");
String displayName = groupId.replaceAll(root + "-[^\\-]*\\-(.*)", "$1");
log.info("creating vreFolder with name {} and title {} and owner {} and default storage {}", name, displayName,
owner, useDefaultStorage);
FolderCreationParameters folderParameters;
if (!useDefaultStorage)
folderParameters = FolderCreationParameters.builder().onRepository("gcube-minio")
.withParameters(Collections.singletonMap("bucketName", name + "-gcube-vre")).name(name)
.description("VREFolder for " + groupId).author(owner).on(sharedRootNode.getIdentifier())
.with(session).build();
else
folderParameters = FolderCreationParameters.builder().name(name).description("VREFolder for " + groupId)
.author(owner).on(sharedRootNode.getIdentifier()).with(session).build();
Node folder = Utils.createFolderInternally(folderParameters, null, useDefaultStorage);
folder.setPrimaryType(PrimaryNodeType.NT_WORKSPACE_SHARED_FOLDER);
folder.setProperty(NodeProperty.IS_VRE_FOLDER.toString(), true);
folder.setProperty(NodeProperty.TITLE.toString(), name);
folder.setProperty(NodeProperty.DISPLAY_NAME.toString(), displayName);
session.save();
AccessControlManager acm = session.getAccessControlManager();
JackrabbitAccessControlList acls = AccessControlUtils.getAccessControlList(acm, folder.getPath());
/*
* Privilege[] adminPrivileges = new Privilege[] {
* acm.privilegeFromName(AccessType.ADMINISTRATOR.getValue()) };
* acls.addAccessControlEntry(AccessControlUtils.getPrincipal(session,
* AuthorizationProvider.instance.get().getClient().getId()), adminPrivileges );
*/
Privilege[] usersPrivileges = new Privilege[] { acm.privilegeFromName(defaultAccessType.getValue()) };
acls.addAccessControlEntry(AccessControlUtils.getPrincipal(session, groupId), usersPrivileges);
acm.setPolicy(folder.getPath(), acls);
log.debug("vrefolder created with id {}", folder.getIdentifier());
}
private boolean internalAddUserToGroup(JackrabbitSession session, Group group, User user)
throws RepositoryException, StorageHubException {
boolean success = group.addMember(user);
session.save();
String folderName = group.getPrincipal().getName();
Node folder = this.getFolderNodeRelatedToGroup(session, folderName);
String userPath = Paths.append(pathUtil.getVREsPath(user.getPrincipal().getName(), session), folderName)
.toPath();
log.debug("creating folder in user path {} from {}", userPath, folder.getPath());
session.getWorkspace().clone(session.getWorkspace().getName(), folder.getPath(), userPath, false);
try {
session.getNode(userPath);
log.debug("the new folder exists ({}) ", userPath);
} catch (PathNotFoundException e) {
log.debug("the new folder doesn't exists ({}) ", userPath);
}
return success;
}
}

View File

@ -0,0 +1,392 @@
package org.gcube.data.access.storagehub.handlers;
import java.util.ArrayList;
import java.util.Collections;
import java.util.HashSet;
import java.util.Iterator;
import java.util.List;
import java.util.Set;
import java.util.function.Predicate;
import java.util.stream.Collectors;
import javax.jcr.Node;
import javax.jcr.PathNotFoundException;
import javax.jcr.RepositoryException;
import org.apache.jackrabbit.api.JackrabbitSession;
import org.apache.jackrabbit.api.security.user.Authorizable;
import org.apache.jackrabbit.api.security.user.Group;
import org.apache.jackrabbit.api.security.user.Query;
import org.apache.jackrabbit.api.security.user.QueryBuilder;
import org.apache.jackrabbit.api.security.user.User;
import org.apache.jackrabbit.core.security.principal.PrincipalImpl;
import org.gcube.common.storagehub.model.Excludes;
import org.gcube.common.storagehub.model.Paths;
import org.gcube.common.storagehub.model.exceptions.BackendGenericError;
import org.gcube.common.storagehub.model.exceptions.InvalidCallParameters;
import org.gcube.common.storagehub.model.exceptions.NotFoundException;
import org.gcube.common.storagehub.model.exceptions.StorageHubException;
import org.gcube.common.storagehub.model.exceptions.UserNotAuthorizedException;
import org.gcube.common.storagehub.model.items.Item;
import org.gcube.common.storagehub.model.items.SharedFolder;
import org.gcube.common.storagehub.model.types.SHUBUser;
import org.gcube.data.access.storagehub.AuthorizationChecker;
import org.gcube.data.access.storagehub.Constants;
import org.gcube.data.access.storagehub.PathUtil;
import org.gcube.data.access.storagehub.Utils;
import org.gcube.data.access.storagehub.handlers.items.builders.FolderCreationParameters;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import jakarta.inject.Inject;
public class UserHandler {
private static final Logger log = LoggerFactory.getLogger(UserHandler.class);
@Inject
UnshareHandler unshareHandler;
@Inject
AuthorizationChecker authChecker;
@Inject
TrashHandler trashHandler;
@Inject
GroupHandler groupHandler;
@Inject
PathUtil pathUtil;
public List<SHUBUser> getAllUsers(JackrabbitSession session) throws Throwable {
List<SHUBUser> users = null;
Iterator<Authorizable> result = session.getUserManager().findAuthorizables(new Query() {
@Override
public <T> void build(QueryBuilder<T> builder) {
builder.setSelector(User.class);
}
});
Set<SHUBUser> usersSet = new HashSet<>();
String adminUser = Constants.ADMIN_USER;
Node homeNode = session.getNode("/Home");
while (result.hasNext()) {
Authorizable user = result.next();
log.debug("user {} found", user.getPrincipal().getName());
if (user.getPrincipal().getName().equals(adminUser))
continue;
long homeVersion = -1;
try {
Node userHome = homeNode.getNode(user.getPrincipal().getName());
if (userHome.hasProperty(Constants.HOME_VERSION_PROP))
homeVersion = userHome.getProperty(Constants.HOME_VERSION_PROP).getLong();
else
homeVersion = 0;
usersSet.add(new SHUBUser(user.getPrincipal().getName(), homeVersion));
} catch (Exception e) {
log.warn("error retrieving user {} home", user.getPrincipal().getName());
}
}
users = new ArrayList<>(usersSet);
Collections.sort(users);
return users;
}
public SHUBUser getUser(JackrabbitSession session, String userId) throws StorageHubException, RepositoryException {
org.apache.jackrabbit.api.security.user.UserManager usrManager = session.getUserManager();
Authorizable authorizable = usrManager.getAuthorizable(userId);
if (authorizable != null && !authorizable.isGroup()) {
long homeVersion = -1;
try {
Node homeNode = session.getNode("/Home");
Node userHome = homeNode.getNode(authorizable.getPrincipal().getName());
if (userHome.hasProperty(Constants.HOME_VERSION_PROP))
homeVersion = userHome.getProperty(Constants.HOME_VERSION_PROP).getLong();
else
homeVersion = 0;
} catch (Exception e) {
log.warn("error retrieving user {} home", authorizable.getPrincipal().getName(), e);
}
return new SHUBUser(authorizable.getPrincipal().getName(), homeVersion);
} else
throw new NotFoundException("user", userId);
}
public String createUser(JackrabbitSession session, String user, String password)
throws StorageHubException, RepositoryException {
org.apache.jackrabbit.api.security.user.UserManager usrManager = session.getUserManager();
User createdUser = usrManager.createUser(user, password);
String userId = createdUser.getID();
Node homeNode = session.getNode("/Home");
Node userHome = homeNode.addNode(user, "nthl:home");
userHome.setProperty(Constants.HOME_VERSION_PROP, 1l);
// creating workspace folder
FolderCreationParameters wsFolderParameters = FolderCreationParameters.builder()
.name(Constants.WORKSPACE_ROOT_FOLDER_NAME).description("workspace of " + user).author(user)
.on(userHome.getIdentifier()).with(session).build();
Utils.createFolderInternally(wsFolderParameters, null, true);
// creating thrash folder
FolderCreationParameters trashFolderParameters = FolderCreationParameters.builder()
.name(Constants.TRASH_ROOT_FOLDER_NAME).description("trash of " + user).author(user)
.on(userHome.getIdentifier()).with(session).build();
Utils.createFolderInternally(trashFolderParameters, null, true);
// creating Vre container folder
FolderCreationParameters vreFolderParameters = FolderCreationParameters.builder()
.name(Constants.PERSONAL_VRES_FOLDER_PARENT_NAME).description("vre folder container of " + user)
.author(user).on(userHome.getIdentifier()).with(session).build();
Utils.createFolderInternally(vreFolderParameters, null, true);
// creating inbox folder
FolderCreationParameters inboxFolderParameters = FolderCreationParameters.builder()
.name(Constants.INBOX_FOLDER_NAME).description("inbox of " + user).author(user)
.on(userHome.getIdentifier()).with(session).build();
Utils.createFolderInternally(inboxFolderParameters, null, true);
// creating outbox folder
FolderCreationParameters outboxFolderParameters = FolderCreationParameters.builder()
.name(Constants.OUTBOX_FOLDER_NAME).description("outbox of " + user).author(user)
.on(userHome.getIdentifier()).with(session).build();
Utils.createFolderInternally(outboxFolderParameters, null, true);
return userId;
}
public String updateHomeUserToLatestVersion(JackrabbitSession session, String user)
throws StorageHubException, RepositoryException {
org.apache.jackrabbit.api.security.user.UserManager usrManager = session.getUserManager();
Authorizable auth = usrManager.getAuthorizable(user);
if (auth == null || auth.isGroup())
throw new InvalidCallParameters("invalid user passed");
Node homeNode = session.getNode("/Home");
Node userHome = homeNode.getNode(user);
if (userHome == null)
throw new BackendGenericError("home for user {} not found");
/*
* //creating workspace folder FolderCreationParameters wsFolderParameters =
* FolderCreationParameters.builder().name(Constants.WORKSPACE_ROOT_FOLDER_NAME)
* .description("workspace of "+user).author(user).on(userHome.getIdentifier()).
* with(session).build(); Utils.createFolderInternally(wsFolderParameters, null,
* true);
*/
// updating thrash folder
if (!userHome.hasProperty(Constants.HOME_VERSION_PROP)
|| userHome.getProperty(Constants.HOME_VERSION_PROP).getLong() < 1) {
org.gcube.common.storagehub.model.Path workspacePath = Paths.append(Paths.getPath(userHome.getPath()),
Constants.WORKSPACE_ROOT_FOLDER_NAME);
Boolean oldTrashExists = session
.nodeExists(Paths.append(workspacePath, Constants.TRASH_ROOT_FOLDER_NAME).toPath());
if (oldTrashExists)
session.move(Paths.append(workspacePath, Constants.TRASH_ROOT_FOLDER_NAME).toPath(),
Paths.append(Paths.getPath(userHome.getPath()), Constants.TRASH_ROOT_FOLDER_NAME).toPath());
else {
FolderCreationParameters trashFolderParameters = FolderCreationParameters.builder()
.name(Constants.TRASH_ROOT_FOLDER_NAME).description("trash of " + user).author(user)
.on(userHome.getIdentifier()).with(session).build();
Utils.createFolderInternally(trashFolderParameters, null, true);
}
Boolean oldVresExists = session
.nodeExists(Paths.append(workspacePath, Constants.OLD_VRE_FOLDER_PARENT_NAME).toPath());
if (oldVresExists)
session.move(Paths.append(workspacePath, Constants.OLD_VRE_FOLDER_PARENT_NAME).toPath(),
Paths.append(Paths.getPath(userHome.getPath()), Constants.PERSONAL_VRES_FOLDER_PARENT_NAME)
.toPath());
else {
// creating Vre container folder
FolderCreationParameters vreFolderParameters = FolderCreationParameters.builder()
.name(Constants.PERSONAL_VRES_FOLDER_PARENT_NAME).description("vre folder container of " + user)
.author(user).on(userHome.getIdentifier()).with(session).build();
Utils.createFolderInternally(vreFolderParameters, null, true);
}
}
/*
* //creating inbox folder FolderCreationParameters inboxFolderParameters =
* FolderCreationParameters.builder().name(Constants.INBOX_FOLDER_NAME).
* description("inbox of "+user).author(user).on(userHome.getIdentifier()).with(
* session).build(); Utils.createFolderInternally(inboxFolderParameters, null,
* true);
*
* //creating outbox folder FolderCreationParameters outboxFolderParameters =
* FolderCreationParameters.builder().name(Constants.OUTBOX_FOLDER_NAME).
* description("outbox of "+user).author(user).on(userHome.getIdentifier()).with
* (session).build(); Utils.createFolderInternally(outboxFolderParameters, null,
* true);
*/
userHome.setProperty(Constants.HOME_VERSION_PROP, 1l);
return user;
}
public String deleteUser(JackrabbitSession session, String user) throws StorageHubException, RepositoryException {
org.apache.jackrabbit.api.security.user.UserManager usrManager = session.getUserManager();
User authorizable = (User) usrManager.getAuthorizable(new PrincipalImpl(user));
if (authorizable != null)
removeUserFromBelongingGroup(session, authorizable, usrManager);
else
log.warn("user was already deleted from jackrabbit, trying to delete folders");
unshareUsersFolders(session, user);
removeUserHomeAndDeleteFiles(session, user);
// FINALIZE user removal
if (authorizable != null && !authorizable.isGroup()) {
log.info("removing user {}", user);
authorizable.remove();
} else
log.warn("the user {} was already deleted, it should never happen", user);
return user;
}
public List<String> getGroupsPerUser(JackrabbitSession session, String user)
throws RepositoryException {
List<String> groups = new ArrayList<>();
org.apache.jackrabbit.api.security.user.UserManager usrManager = session.getUserManager();
User authUser = (User) usrManager.getAuthorizable(new PrincipalImpl(user));
Iterator<Group> groupsAuth = authUser.memberOf();
while (groupsAuth.hasNext()) {
Authorizable group = groupsAuth.next();
groups.add(group.getPrincipal().getName());
}
return groups;
}
private void removeUserFromBelongingGroup(JackrabbitSession session, User authorizable,
org.apache.jackrabbit.api.security.user.UserManager usrManager)
throws RepositoryException, StorageHubException {
Iterator<Authorizable> groups = session.getUserManager().findAuthorizables(new Query() {
@Override
public <T> void build(QueryBuilder<T> builder) {
builder.setSelector(Group.class);
}
});
String user = authorizable.getPrincipal().getName();
while (groups.hasNext()) {
Authorizable group = groups.next();
log.info("group found {}", group.getPrincipal().getName());
if (group.isGroup() && ((Group) group).isMember(authorizable)) {
boolean success = groupHandler.removeUserFromGroup(session, group.getPrincipal().getName(), user);
log.warn("user {} {} removed from vre {}", user, success ? "" : "not", group.getPrincipal().getName());
}
}
}
private void unshareUsersFolders(JackrabbitSession session, String user) {
try {
Node sharedFolderNode = session.getNode(Constants.SHARED_FOLDER_PATH);
Predicate<Node> sharedWithUserChecker = new Predicate<Node>() {
@Override
public boolean test(Node t) {
try {
authChecker.checkReadAuthorizationControl(t.getSession(), user, t.getIdentifier());
return true;
} catch (UserNotAuthorizedException | BackendGenericError | RepositoryException e) {
return false;
}
}
};
List<SharedFolder> items = Utils.getItemList(sharedWithUserChecker, sharedFolderNode, Excludes.ALL, null,
false, SharedFolder.class);
log.debug(" Shared folder to unshare found are {}", items.size());
for (SharedFolder item : items) {
String title = item.getTitle();
log.debug("in list folder name {} with title {} and path {} ", item.getName(), title, item.getPath());
if (item.isPublicItem() && !item.getUsers().getMap().containsKey(user))
continue;
if (item.isVreFolder())
continue;
log.info("removing sharing for folder name {} with title {} and path {} ", item.getName(), title,
item.getPath());
String owner = item.getOwner();
Set<String> usersToUnshare = owner.equals(user) ? Collections.emptySet() : Collections.singleton(user);
try {
unshareHandler.unshareForRemoval(session, usersToUnshare, session.getNodeByIdentifier(item.getId()),
user);
} catch (Throwable e) {
log.warn("error unsharing folder with title '{}' and id {} ", title, item.getId(), e);
}
}
} catch (Throwable t) {
log.warn("error getting folder shared with {}", user, t);
}
}
private void removeUserHomeAndDeleteFiles(JackrabbitSession session, String user)
throws RepositoryException, StorageHubException {
org.gcube.common.storagehub.model.Path homePath = pathUtil.getHome(user);
org.gcube.common.storagehub.model.Path workspacePath = pathUtil.getWorkspacePath(user);
try {
Node workspaceNode = session.getNode(workspacePath.toPath());
List<Item> workspaceItems = Utils.getItemList(workspaceNode, Excludes.GET_ONLY_CONTENT, null, true, null)
.stream().filter(i -> !i.isShared()).collect(Collectors.toList());
trashHandler.removeOnlyNodesContent(session, workspaceItems);
} catch (PathNotFoundException e) {
log.warn("{} workspace dir {} was already deleted", user, homePath.toPath());
}
try {
org.gcube.common.storagehub.model.Path trashPath = pathUtil.getTrashPath(user, session);
Node trashNode = session.getNode(trashPath.toPath());
List<Item> trashItems = Utils.getItemList(trashNode, Excludes.ALL, null, true, null);
trashHandler.removeOnlyNodesContent(session, trashItems);
} catch (PathNotFoundException e) {
log.warn("{} trash dir {} was already deleted", user, homePath.toPath());
}
try {
Node homeNode = session.getNode(homePath.toPath());
homeNode.remove();
} catch (PathNotFoundException e) {
log.warn("{} home dir {} was already deleted", user, homePath.toPath());
}
}
}

View File

@ -3,54 +3,24 @@ package org.gcube.data.access.storagehub.services;
import static org.gcube.data.access.storagehub.Roles.INFRASTRUCTURE_MANAGER_ROLE;
import static org.gcube.data.access.storagehub.Roles.VREMANAGER_ROLE;
import java.security.Principal;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Iterator;
import java.util.List;
import java.util.Objects;
import javax.jcr.Node;
import javax.jcr.PathNotFoundException;
import javax.jcr.RepositoryException;
import javax.jcr.security.AccessControlEntry;
import javax.jcr.security.AccessControlManager;
import javax.jcr.security.Privilege;
import org.apache.jackrabbit.api.JackrabbitSession;
import org.apache.jackrabbit.api.security.JackrabbitAccessControlList;
import org.apache.jackrabbit.api.security.user.Authorizable;
import org.apache.jackrabbit.api.security.user.Group;
import org.apache.jackrabbit.api.security.user.Query;
import org.apache.jackrabbit.api.security.user.QueryBuilder;
import org.apache.jackrabbit.api.security.user.User;
import org.apache.jackrabbit.commons.jackrabbit.authorization.AccessControlUtils;
import org.gcube.common.authorization.control.annotations.AuthorizationControl;
import org.gcube.common.gxrest.response.outbound.GXOutboundErrorResponse;
import org.gcube.common.security.ContextBean;
import org.gcube.common.security.ContextBean.Type;
import org.gcube.common.security.providers.SecretManagerProvider;
import org.gcube.common.storagehub.model.Excludes;
import org.gcube.common.storagehub.model.Paths;
import org.gcube.common.storagehub.model.acls.AccessType;
import org.gcube.common.storagehub.model.exceptions.BackendGenericError;
import org.gcube.common.storagehub.model.exceptions.InvalidCallParameters;
import org.gcube.common.storagehub.model.exceptions.StorageHubException;
import org.gcube.common.storagehub.model.exceptions.UserNotAuthorizedException;
import org.gcube.common.storagehub.model.items.Item;
import org.gcube.common.storagehub.model.types.NodeProperty;
import org.gcube.common.storagehub.model.types.PrimaryNodeType;
import org.gcube.data.access.storagehub.AuthorizationChecker;
import org.gcube.data.access.storagehub.Constants;
import org.gcube.data.access.storagehub.PathUtil;
import org.gcube.data.access.storagehub.StorageHubAppllicationManager;
import org.gcube.data.access.storagehub.Utils;
import org.gcube.data.access.storagehub.handlers.GroupHandler;
import org.gcube.data.access.storagehub.handlers.TrashHandler;
import org.gcube.data.access.storagehub.handlers.items.Node2ItemConverter;
import org.gcube.data.access.storagehub.handlers.items.builders.FolderCreationParameters;
import org.gcube.data.access.storagehub.handlers.vres.VRE;
import org.gcube.data.access.storagehub.handlers.vres.VREManager;
import org.gcube.smartgears.annotations.ManagedBy;
import org.gcube.smartgears.utils.InnerMethodName;
import org.glassfish.jersey.media.multipart.FormDataParam;
@ -62,7 +32,6 @@ import com.webcohesion.enunciate.metadata.rs.RequestHeaders;
import jakarta.inject.Inject;
import jakarta.inject.Singleton;
import jakarta.servlet.ServletContext;
import jakarta.ws.rs.Consumes;
import jakarta.ws.rs.DELETE;
import jakarta.ws.rs.DefaultValue;
@ -73,7 +42,6 @@ import jakarta.ws.rs.PUT;
import jakarta.ws.rs.Path;
import jakarta.ws.rs.PathParam;
import jakarta.ws.rs.Produces;
import jakarta.ws.rs.core.Context;
import jakarta.ws.rs.core.MediaType;
import jakarta.ws.rs.core.Response;
@ -86,32 +54,16 @@ import jakarta.ws.rs.core.Response;
public class GroupManager {
@Context
ServletContext context;
@Inject
TrashHandler trashHandler;
private static final Logger log = LoggerFactory.getLogger(GroupManager.class);
RepositoryInitializer repository = StorageHubAppllicationManager.getRepository();
@Inject
VREManager vreManager;
@Inject
GroupHandler groupHandler;
@Inject
Node2ItemConverter node2Item;
@Inject
PathUtil pathUtil;
@Inject
AuthorizationChecker authChecker;
@GET
@Path("")
@ -119,25 +71,11 @@ public class GroupManager {
public List<String> getGroups(){
InnerMethodName.set("getGroups");
JackrabbitSession session = null;
List<String> groups= new ArrayList<>();
try {
session = (JackrabbitSession) repository.getRepository().login(Constants.JCR_CREDENTIALS);
Iterator<Authorizable> result = session.getUserManager().findAuthorizables(new Query() {
@Override
public <T> void build(QueryBuilder<T> builder) {
builder.setSelector(Group.class);
}
});
while (result.hasNext()) {
Authorizable group = result.next();
log.info("group {} found",group.getPrincipal().getName());
groups.add(group.getPrincipal().getName());
}
groups = groupHandler.getGroups(session);
}catch(RepositoryException re ){
log.error("jcr error creating item", re);
GXOutboundErrorResponse.throwException(new BackendGenericError("jcr error creating item", re));
@ -155,28 +93,10 @@ public class GroupManager {
public String createGroup(@FormDataParam("group") String group, @FormDataParam("accessType") AccessType accessType, @FormDataParam("folderOwner") String folderOwner, @FormDataParam("useDefaultStorage") @DefaultValue("true") boolean useDefaultStorage){
InnerMethodName.set("createGroup");
JackrabbitSession session = null;
String groupId = null;
try {
log.info("create group called with groupid {} , accessType {} and folderOwner {}",group, accessType, folderOwner);
session = (JackrabbitSession) repository.getRepository().login(Constants.JCR_CREDENTIALS);
org.apache.jackrabbit.api.security.user.UserManager usrManager = session.getUserManager();
Group createdGroup = usrManager.createGroup(group);
groupId = createdGroup.getID();
User user = (User)usrManager.getAuthorizable(folderOwner);
createVreFolder(groupId, session, accessType!=null?accessType:AccessType.WRITE_OWNER, folderOwner, useDefaultStorage);
boolean success = this.internalAddUserToGroup(session, createdGroup, user);
if (!success) log.warn("the user have not been added to the group");
else log.debug("the user have been added to the group");
groupHandler.createGroup(session, group, accessType, folderOwner, useDefaultStorage);
session.save();
}catch(StorageHubException se) {
log.error("error creating group {}", group, se);
@ -188,8 +108,7 @@ public class GroupManager {
if (session!=null)
session.logout();
}
return groupId;
return group;
}
@DELETE
@ -198,27 +117,10 @@ public class GroupManager {
public String deleteGroup(@PathParam("group") String group){
InnerMethodName.set("deleteGroup");
JackrabbitSession session = null;
try {
session = (JackrabbitSession) repository.getRepository().login(Constants.JCR_CREDENTIALS);
org.apache.jackrabbit.api.security.user.UserManager usrManager = session.getUserManager();
Authorizable authorizable = usrManager.getAuthorizable(group);
if (authorizable!=null && authorizable.isGroup())
authorizable.remove();
try {
Node node = groupHandler.getFolderNodeRelatedToGroup(session, group);
List<Item> workspaceItems = Utils.getItemList(node, Excludes.GET_ONLY_CONTENT, null, true, null);
trashHandler.removeOnlyNodesContent(session, workspaceItems);
node.removeSharedSet();
}catch (Exception e) {
log.warn("vreFolder {} not found, removing only the group", group);
}
groupHandler.deleteGroup(session, group);
session.save();
}catch(RepositoryException re ){
log.error("jcr error creating item", re);
@ -247,36 +149,15 @@ public class GroupManager {
Objects.nonNull(groupId);
Objects.nonNull(userId);
session = (JackrabbitSession) repository.getRepository().login(Constants.JCR_CREDENTIALS);
Node vreFolder = groupHandler.getFolderNodeRelatedToGroup(session, groupId);
String currentUser = SecretManagerProvider.get().getOwner().getId();
if (!isInfraManager() && !(isVREManager() && isValidGroupForContext(groupId) ))
authChecker.checkAdministratorControl(session, currentUser, node2Item.getItem(vreFolder, Excludes.ALL));
if (!isInfraManager() && !(isVREManager() && isValidGroupForContext(groupId)) &&
!groupHandler.getGroupAdministators(session, groupId).contains(currentUser))
throw new UserNotAuthorizedException();
org.apache.jackrabbit.api.security.user.UserManager usrManager = ((JackrabbitSession)session).getUserManager();
session = (JackrabbitSession) repository.getRepository().login(Constants.JCR_CREDENTIALS);
Group group = (Group)usrManager.getAuthorizable(groupId);
User authUser = (User)usrManager.getAuthorizable(userId);
if (group ==null)
throw new InvalidCallParameters("invalid group "+groupId);
if (authUser ==null)
throw new InvalidCallParameters("invalid user "+userId);
if (!group.isMember(authUser))
throw new InvalidCallParameters("user "+userId+" is not in the group "+groupId);
AccessControlManager acm = session.getAccessControlManager();
JackrabbitAccessControlList acls = AccessControlUtils.getAccessControlList(acm, vreFolder.getPath());
Privilege[] userPrivileges = new Privilege[] { acm.privilegeFromName(AccessType.ADMINISTRATOR.getValue()) };
Principal principal = AccessControlUtils.getPrincipal(session, userId);
acls.addAccessControlEntry(principal, userPrivileges);
acm.setPolicy(vreFolder.getPath(), acls);
groupHandler.addAdministratorToGroup(session, groupId, userId);
session.save();
}catch(StorageHubException she ){
@ -289,6 +170,8 @@ public class GroupManager {
if (session!=null)
session.logout();
}
}
@DELETE
@ -299,32 +182,20 @@ public class GroupManager {
InnerMethodName.set("removeAdmin");
JackrabbitSession session = null;
try {
Objects.nonNull(groupId);
Objects.nonNull(userId);
session = (JackrabbitSession) repository.getRepository().login(Constants.JCR_CREDENTIALS);
Node vreFolder = groupHandler.getFolderNodeRelatedToGroup(session, groupId);
String currentUser = SecretManagerProvider.get().getOwner().getId();
if (!isInfraManager() && !(isVREManager() && isValidGroupForContext(groupId) ))
authChecker.checkAdministratorControl(session, currentUser, node2Item.getItem(vreFolder, Excludes.ALL));
if (!isInfraManager() && !(isVREManager() && isValidGroupForContext(groupId)) &&
!groupHandler.getGroupAdministators(session, groupId).contains(currentUser))
throw new UserNotAuthorizedException();
session = (JackrabbitSession) repository.getRepository().login(Constants.JCR_CREDENTIALS);
groupHandler.removeAdministratorFromGroup(session, groupId, userId);
AccessControlManager acm = session.getAccessControlManager();
JackrabbitAccessControlList acls = AccessControlUtils.getAccessControlList(acm, vreFolder.getPath());
AccessControlEntry toRemove = null;
for (AccessControlEntry acl: acls.getAccessControlEntries())
if (acl.getPrincipal().getName().equals(userId)) {
toRemove = acl;
break;
}
acls.removeAccessControlEntry(toRemove);
acm.setPolicy(vreFolder.getPath(), acls);
session.save();
}catch(StorageHubException she ){
log.error(she.getErrorMessage(), she);
@ -332,7 +203,7 @@ public class GroupManager {
}catch(Throwable re ){
log.error("jcr error creating item", re);
GXOutboundErrorResponse.throwException(new BackendGenericError("jcr error removing admin to VREFolder", re));
}finally {
} finally {
if (session!=null)
session.logout();
}
@ -344,36 +215,18 @@ public class GroupManager {
public List<String> getAdmins(@PathParam("groupId") String groupId){
InnerMethodName.set("getAdmins");
String login = SecretManagerProvider.get().getOwner().getId();
JackrabbitSession session = null;
List<String> users = new ArrayList<>();
JackrabbitSession session = null;
try {
session = (JackrabbitSession) repository.getRepository().login(Constants.JCR_CREDENTIALS);
VRE vreFolder = vreManager.getVreFolderItemByGroupName(session, groupId, login, Excludes.ALL);
AccessControlManager acm = session.getAccessControlManager();
//authChecker.checkAdministratorControl(session, (VreFolder)vreFolder.getVreFolder());
Node node = session.getNodeByIdentifier(vreFolder.getVreFolder().getId());
JackrabbitAccessControlList acls = AccessControlUtils.getAccessControlList(acm, node.getPath());
for (AccessControlEntry acl: acls.getAccessControlEntries())
for (Privilege pr: acl.getPrivileges()) {
if (pr.getName().equals(AccessType.ADMINISTRATOR.getValue())){
users.add(acl.getPrincipal().getName());
}
}
users = groupHandler.getGroupAdministators(session, groupId);
}catch(StorageHubException she ){
log.error(she.getErrorMessage(), she);
GXOutboundErrorResponse.throwException(she, Response.Status.fromStatusCode(she.getStatus()));
}catch(Exception re ){
log.error("jcr error creating item", re);
GXOutboundErrorResponse.throwException(new BackendGenericError("jcr error creating item", re));
}finally {
}catch(Throwable re ){
log.error("jcr error getting admins", re);
GXOutboundErrorResponse.throwException(new BackendGenericError("jcr error getting admins", re));
} finally {
if (session!=null)
session.logout();
}
@ -389,38 +242,25 @@ public class GroupManager {
public boolean addUserToGroup(@PathParam("id") String groupId, @FormParam("userId") String userId){
InnerMethodName.set("addUserToGroup");
JackrabbitSession session = null;
boolean success = false;
try {
if (!isInfraManager() && !isValidGroupForContext(groupId))
if (!isInfraManager() && !(isVREManager() && isValidGroupForContext(groupId)))
throw new UserNotAuthorizedException("only VREManager of the selected VRE can execute this operation");
session = (JackrabbitSession) repository.getRepository().login(Constants.JCR_CREDENTIALS);
groupHandler.addUserToGroup(session, userId, groupId);
org.apache.jackrabbit.api.security.user.UserManager usrManager = session.getUserManager();
Group group = (Group)usrManager.getAuthorizable(groupId);
User user = (User)usrManager.getAuthorizable(userId);
if (user==null)
throw new InvalidCallParameters("user "+userId+" not exists");
if (group.isMember(user))
throw new InvalidCallParameters("user "+userId+" is already member of group "+groupId);
this.internalAddUserToGroup(session, group, user);
session.save();
success = true;
session.save();
}catch(StorageHubException she ){
log.error(she.getErrorMessage(), she);
GXOutboundErrorResponse.throwException(she, Response.Status.fromStatusCode(she.getStatus()));
}catch(RepositoryException re ){
log.error("jcr error creating item", re);
GXOutboundErrorResponse.throwException(new BackendGenericError("jcr error creating item", re));
}finally {
log.error("jcr error adding user to group", re);
GXOutboundErrorResponse.throwException(new BackendGenericError("jcr error adding user to group", re));
} finally {
if (session!=null)
session.logout();
}
@ -428,25 +268,7 @@ public class GroupManager {
return success;
}
private boolean internalAddUserToGroup(JackrabbitSession session, Group group, User user) throws RepositoryException, StorageHubException {
boolean success = group.addMember(user);
session.save();
String folderName = group.getPrincipal().getName();
Node folder = groupHandler.getFolderNodeRelatedToGroup(session, folderName);
String userPath = Paths.append(pathUtil.getVREsPath(user.getPrincipal().getName(), session), folderName).toPath();
log.debug("creating folder in user path {} from {}", userPath, folder.getPath() );
session.getWorkspace().clone(session.getWorkspace().getName(), folder.getPath(),userPath , false);
try {
session.getNode(userPath);
log.debug("the new folder exists ({}) ", userPath );
}catch (PathNotFoundException e) {
log.debug("the new folder doesn't exists ({}) ", userPath );
}
return success;
}
@DELETE
@Path("{groupId}/users/{userId}")
@ -459,12 +281,12 @@ public class GroupManager {
boolean success = false;
try {
if (!isValidGroupForContext(groupId) && !isInfraManager())
if (!isInfraManager() && !(isVREManager() && isValidGroupForContext(groupId)))
throw new UserNotAuthorizedException("only VREManager of the selected VRE can execute this operation");
session = (JackrabbitSession) repository.getRepository().login(Constants.JCR_CREDENTIALS);
success = groupHandler.removeUserFromGroup(groupId, userId, session);
success = groupHandler.removeUserFromGroup(session, groupId, userId);
session.save();
}catch(StorageHubException she ){
@ -486,35 +308,23 @@ public class GroupManager {
@Produces(MediaType.APPLICATION_JSON)
@AuthorizationControl(allowedRoles={VREMANAGER_ROLE, INFRASTRUCTURE_MANAGER_ROLE})
public List<String> getUsersOfGroup(@PathParam("groupId") String groupId){
InnerMethodName.set("getUsersOfGroup");
JackrabbitSession session = null;
List<String> users = new ArrayList<>();
try {
if (!isValidGroupForContext(groupId) && !isInfraManager())
if (!isInfraManager() && !(isVREManager() && isValidGroupForContext(groupId)))
throw new UserNotAuthorizedException("only VREManager of the selected VRE can execute this operation");
session = (JackrabbitSession) repository.getRepository().login(Constants.JCR_CREDENTIALS);
org.apache.jackrabbit.api.security.user.UserManager usrManager = session.getUserManager();
Group group = (Group)usrManager.getAuthorizable(groupId);
Iterator<Authorizable> it = group.getMembers();
while (it.hasNext()) {
Authorizable user = it.next();
users.add(user.getPrincipal().getName());
}
users = groupHandler.getUsersBelongingToGroup(session, groupId);
}catch (StorageHubException e) {
log.error("error getting users", e);
GXOutboundErrorResponse.throwException(e);
}catch(RepositoryException re ){
log.error("jcr error getting users", re);
GXOutboundErrorResponse.throwException(new BackendGenericError("jcr error getting users", re));
}finally {
} finally {
if (session!=null)
session.logout();
}
@ -522,51 +332,7 @@ public class GroupManager {
return users;
}
private void createVreFolder(String groupId, JackrabbitSession session, AccessType defaultAccessType, String owner, boolean useDefaultStorage ) throws Exception{
Node sharedRootNode = session.getNode(Constants.SHARED_FOLDER_PATH);
String name = groupId;
String currentScope = SecretManagerProvider.get().getContext();
ContextBean bean = new ContextBean(currentScope);
while (!bean.is(Type.INFRASTRUCTURE)) {
bean = bean.enclosingScope();
}
String root = bean.toString().replaceAll("/", "");
String displayName = groupId.replaceAll(root+"-[^\\-]*\\-(.*)", "$1");
log.info("creating vreFolder with name {} and title {} and owner {} and default storage {}", name, displayName, owner, useDefaultStorage);
FolderCreationParameters folderParameters;
if (!useDefaultStorage)
folderParameters = FolderCreationParameters.builder().onRepository("gcube-minio").withParameters(Collections.singletonMap("bucketName", name+"-gcube-vre")).name(name).description( "VREFolder for "+groupId).author(owner).on(sharedRootNode.getIdentifier()).with(session).build();
else
folderParameters = FolderCreationParameters.builder().name(name).description( "VREFolder for "+groupId).author(owner).on(sharedRootNode.getIdentifier()).with(session).build();
Node folder= Utils.createFolderInternally(folderParameters, null, useDefaultStorage);
folder.setPrimaryType(PrimaryNodeType.NT_WORKSPACE_SHARED_FOLDER);
folder.setProperty(NodeProperty.IS_VRE_FOLDER.toString(), true);
folder.setProperty(NodeProperty.TITLE.toString(), name);
folder.setProperty(NodeProperty.DISPLAY_NAME.toString(), displayName);
session.save();
AccessControlManager acm = session.getAccessControlManager();
JackrabbitAccessControlList acls = AccessControlUtils.getAccessControlList(acm, folder.getPath());
/*Privilege[] adminPrivileges = new Privilege[] { acm.privilegeFromName(AccessType.ADMINISTRATOR.getValue()) };
acls.addAccessControlEntry(AccessControlUtils.getPrincipal(session, AuthorizationProvider.instance.get().getClient().getId()), adminPrivileges );
*/
Privilege[] usersPrivileges = new Privilege[] { acm.privilegeFromName(defaultAccessType.getValue()) };
acls.addAccessControlEntry(AccessControlUtils.getPrincipal(session,groupId), usersPrivileges );
acm.setPolicy(folder.getPath(), acls);
log.debug("vrefolder created with id {}",folder.getIdentifier());
}
private boolean isValidGroupForContext(String group){

View File

@ -1,46 +1,20 @@
package org.gcube.data.access.storagehub.services;
import java.util.ArrayList;
import java.util.Collections;
import java.util.HashSet;
import java.util.Iterator;
import java.util.List;
import java.util.Set;
import java.util.function.Predicate;
import java.util.stream.Collectors;
import javax.jcr.Node;
import javax.jcr.PathNotFoundException;
import javax.jcr.RepositoryException;
import org.apache.jackrabbit.api.JackrabbitSession;
import org.apache.jackrabbit.api.security.user.Authorizable;
import org.apache.jackrabbit.api.security.user.Group;
import org.apache.jackrabbit.api.security.user.Query;
import org.apache.jackrabbit.api.security.user.QueryBuilder;
import org.apache.jackrabbit.api.security.user.User;
import org.apache.jackrabbit.core.security.principal.PrincipalImpl;
import org.gcube.common.authorization.control.annotations.AuthorizationControl;
import org.gcube.common.gxrest.response.outbound.GXOutboundErrorResponse;
import org.gcube.common.storagehub.model.Excludes;
import org.gcube.common.storagehub.model.Paths;
import org.gcube.common.storagehub.model.exceptions.BackendGenericError;
import org.gcube.common.storagehub.model.exceptions.IdNotFoundException;
import org.gcube.common.storagehub.model.exceptions.InvalidCallParameters;
import org.gcube.common.storagehub.model.exceptions.StorageHubException;
import org.gcube.common.storagehub.model.exceptions.UserNotAuthorizedException;
import org.gcube.common.storagehub.model.items.Item;
import org.gcube.common.storagehub.model.items.SharedFolder;
import org.gcube.common.storagehub.model.types.SHUBUser;
import org.gcube.data.access.storagehub.AuthorizationChecker;
import org.gcube.data.access.storagehub.Constants;
import org.gcube.data.access.storagehub.PathUtil;
import org.gcube.data.access.storagehub.StorageHubAppllicationManager;
import org.gcube.data.access.storagehub.Utils;
import org.gcube.data.access.storagehub.handlers.GroupHandler;
import org.gcube.data.access.storagehub.handlers.TrashHandler;
import org.gcube.data.access.storagehub.handlers.UnshareHandler;
import org.gcube.data.access.storagehub.handlers.items.builders.FolderCreationParameters;
import org.gcube.data.access.storagehub.handlers.UserHandler;
import org.gcube.smartgears.annotations.ManagedBy;
import org.gcube.smartgears.utils.InnerMethodName;
import org.slf4j.Logger;
@ -50,7 +24,6 @@ import com.webcohesion.enunciate.metadata.rs.RequestHeader;
import com.webcohesion.enunciate.metadata.rs.RequestHeaders;
import jakarta.inject.Inject;
import jakarta.servlet.ServletContext;
import jakarta.ws.rs.Consumes;
import jakarta.ws.rs.DELETE;
import jakarta.ws.rs.FormParam;
@ -60,140 +33,61 @@ import jakarta.ws.rs.PUT;
import jakarta.ws.rs.Path;
import jakarta.ws.rs.PathParam;
import jakarta.ws.rs.Produces;
import jakarta.ws.rs.core.Context;
import jakarta.ws.rs.core.MediaType;
import jakarta.ws.rs.core.Response;
@Path("users")
@ManagedBy(StorageHubAppllicationManager.class)
@RequestHeaders({
@RequestHeader( name = "Authorization", description = "Bearer token, see https://dev.d4science.org/how-to-access-resources"),
})
@RequestHeader(name = "Authorization", description = "Bearer token, see https://dev.d4science.org/how-to-access-resources"), })
public class UserManager {
private static final String INFRASTRUCTURE_MANAGER_ROLE = "Infrastructure-Manager";
@Context ServletContext context;
private static final Logger log = LoggerFactory.getLogger(UserManager.class);
RepositoryInitializer repository = StorageHubAppllicationManager.getRepository();
@Inject
UnshareHandler unshareHandler;
@Inject
AuthorizationChecker authChecker;
@Inject
TrashHandler trashHandler;
@Inject
GroupHandler groupHandler;
@Inject
PathUtil pathUtil;
private List<SHUBUser> retrieveUsers() throws Throwable{
JackrabbitSession session = null;
List<SHUBUser> users = null;
try {
session = (JackrabbitSession) repository.getRepository().login(Constants.JCR_CREDENTIALS);
Iterator<Authorizable> result = session.getUserManager().findAuthorizables(new Query() {
@Override
public <T> void build(QueryBuilder<T> builder) {
builder.setSelector(User.class);
}
});
Set<SHUBUser> usersSet= new HashSet<>();
String adminUser = Constants.ADMIN_USER;
Node homeNode = session.getNode("/Home");
while (result.hasNext()) {
Authorizable user = result.next();
log.debug("user {} found",user.getPrincipal().getName());
if (user.getPrincipal().getName().equals(adminUser)) continue;
long homeVersion = -1;
try {
Node userHome = homeNode.getNode(user.getPrincipal().getName());
if(userHome.hasProperty(Constants.HOME_VERSION_PROP))
homeVersion = userHome.getProperty(Constants.HOME_VERSION_PROP).getLong();
else homeVersion = 0;
usersSet.add(new SHUBUser(user.getPrincipal().getName(), homeVersion));
}catch (Exception e) {
log.warn("error retrieving user {} home", user.getPrincipal().getName());
}
}
users = new ArrayList<>(usersSet);
Collections.sort(users);
} finally {
if (session!=null)
session.logout();
}
return users;
}
UserHandler userHandler;
@GET
@Path("")
@Produces(MediaType.APPLICATION_JSON)
public List<SHUBUser> getUsers(){
public List<SHUBUser> getUsers() {
InnerMethodName.set("getUsers");
JackrabbitSession session = null;
try {
return retrieveUsers();
}catch (Throwable e) {
session = (JackrabbitSession) repository.getRepository().login(Constants.JCR_CREDENTIALS);
return userHandler.getAllUsers(null);
} catch (Throwable e) {
log.error("jcr error getting users", e);
GXOutboundErrorResponse.throwException(new BackendGenericError(e));
} finally {
if (session != null)
session.logout();
}
return null;
}
@GET
@Path("{user}")
public SHUBUser getUser(@PathParam("user") String user){
public SHUBUser getUser(@PathParam("user") String user) {
InnerMethodName.set("getUser");
JackrabbitSession session = null;
try {
session = (JackrabbitSession) repository.getRepository().login(Constants.JCR_CREDENTIALS);
org.apache.jackrabbit.api.security.user.UserManager usrManager = session.getUserManager();
Authorizable authorizable = usrManager.getAuthorizable(user);
if (authorizable != null && !authorizable.isGroup()) {
long homeVersion = -1;
try {
Node homeNode = session.getNode("/Home");
Node userHome = homeNode.getNode(authorizable.getPrincipal().getName());
if(userHome.hasProperty(Constants.HOME_VERSION_PROP))
homeVersion = userHome.getProperty(Constants.HOME_VERSION_PROP).getLong();
else homeVersion = 0;
}catch (Exception e) {
log.warn("error retrieving user {} home", authorizable.getPrincipal().getName(), e );
}
return new SHUBUser(authorizable.getPrincipal().getName(), homeVersion);
}
log.debug("user {} not found", user);
}catch(Exception e) {
userHandler.getUser(session, user);
} catch (StorageHubException se) {
log.error("error getting user", se);
GXOutboundErrorResponse.throwException(se);
} catch (Exception e) {
log.error("jcr error getting user", e);
GXOutboundErrorResponse.throwException(new BackendGenericError(e));
} finally {
if (session!=null)
if (session != null)
session.logout();
}
@ -205,8 +99,8 @@ public class UserManager {
@POST
@Path("")
@Consumes(MediaType.APPLICATION_FORM_URLENCODED)
@AuthorizationControl(allowedRoles={INFRASTRUCTURE_MANAGER_ROLE})
public String createUser(@FormParam("user") String user, @FormParam("password") String password){
@AuthorizationControl(allowedRoles = { INFRASTRUCTURE_MANAGER_ROLE })
public String createUser(@FormParam("user") String user, @FormParam("password") String password) {
InnerMethodName.set("createUser");
@ -215,45 +109,17 @@ public class UserManager {
try {
session = (JackrabbitSession) repository.getRepository().login(Constants.JCR_CREDENTIALS);
org.apache.jackrabbit.api.security.user.UserManager usrManager = session.getUserManager();
User createdUser = usrManager.createUser(user, password);
userId = createdUser.getID();
Node homeNode = session.getNode("/Home");
Node userHome = homeNode.addNode(user, "nthl:home");
userHome.setProperty(Constants.HOME_VERSION_PROP, 1l);
//creating workspace folder
FolderCreationParameters wsFolderParameters = FolderCreationParameters.builder().name(Constants.WORKSPACE_ROOT_FOLDER_NAME).description("workspace of "+user).author(user).on(userHome.getIdentifier()).with(session).build();
Utils.createFolderInternally(wsFolderParameters, null, true);
//creating thrash folder
FolderCreationParameters trashFolderParameters = FolderCreationParameters.builder().name(Constants.TRASH_ROOT_FOLDER_NAME).description("trash of "+user).author(user).on(userHome.getIdentifier()).with(session).build();
Utils.createFolderInternally(trashFolderParameters, null, true);
//creating Vre container folder
FolderCreationParameters vreFolderParameters = FolderCreationParameters.builder().name(Constants.PERSONAL_VRES_FOLDER_PARENT_NAME).description("vre folder container of "+user).author(user).on(userHome.getIdentifier()).with(session).build();
Utils.createFolderInternally(vreFolderParameters, null, true);
//creating inbox folder
FolderCreationParameters inboxFolderParameters = FolderCreationParameters.builder().name(Constants.INBOX_FOLDER_NAME).description("inbox of "+user).author(user).on(userHome.getIdentifier()).with(session).build();
Utils.createFolderInternally(inboxFolderParameters, null, true);
//creating outbox folder
FolderCreationParameters outboxFolderParameters = FolderCreationParameters.builder().name(Constants.OUTBOX_FOLDER_NAME).description("outbox of "+user).author(user).on(userHome.getIdentifier()).with(session).build();
Utils.createFolderInternally(outboxFolderParameters, null, true);
userId = userHandler.createUser(session, user, password);
session.save();
}catch(StorageHubException she ){
} catch (StorageHubException she) {
log.error(she.getErrorMessage(), she);
GXOutboundErrorResponse.throwException(she, Response.Status.fromStatusCode(she.getStatus()));
}catch(RepositoryException re ){
} catch (RepositoryException re) {
log.error("jcr error creating item", re);
GXOutboundErrorResponse.throwException(new BackendGenericError("jcr error creating item", re));
} finally {
if (session!=null)
if (session != null)
session.logout();
}
@ -263,8 +129,8 @@ public class UserManager {
@PUT
@Path("{user}")
@Consumes(MediaType.APPLICATION_FORM_URLENCODED)
@AuthorizationControl(allowedRoles={INFRASTRUCTURE_MANAGER_ROLE})
public String updateHomeUserToLatestVersion(@PathParam("user") String user){
@AuthorizationControl(allowedRoles = { INFRASTRUCTURE_MANAGER_ROLE })
public String updateHomeUserToLatestVersion(@PathParam("user") String user) {
InnerMethodName.set("updateHomeUserToLatestVersion");
@ -273,78 +139,27 @@ public class UserManager {
try {
session = (JackrabbitSession) repository.getRepository().login(Constants.JCR_CREDENTIALS);
userId = userHandler.updateHomeUserToLatestVersion(session, userId);
org.apache.jackrabbit.api.security.user.UserManager usrManager = session.getUserManager();
Authorizable auth = usrManager.getAuthorizable(user);
if( auth==null || auth.isGroup())
throw new InvalidCallParameters("invalid user passed");
Node homeNode = session.getNode("/Home");
Node userHome = homeNode.getNode(user);
if (userHome == null)
throw new BackendGenericError("home for user {} not found");
/*
//creating workspace folder
FolderCreationParameters wsFolderParameters = FolderCreationParameters.builder().name(Constants.WORKSPACE_ROOT_FOLDER_NAME).description("workspace of "+user).author(user).on(userHome.getIdentifier()).with(session).build();
Utils.createFolderInternally(wsFolderParameters, null, true);
*/
//updating thrash folder
if (!userHome.hasProperty(Constants.HOME_VERSION_PROP) || userHome.getProperty(Constants.HOME_VERSION_PROP).getLong()<1) {
org.gcube.common.storagehub.model.Path workspacePath = Paths.append(Paths.getPath(userHome.getPath()),Constants.WORKSPACE_ROOT_FOLDER_NAME);
Boolean oldTrashExists = session.nodeExists(Paths.append(workspacePath, Constants.TRASH_ROOT_FOLDER_NAME).toPath());
if (oldTrashExists)
session.move(Paths.append(workspacePath, Constants.TRASH_ROOT_FOLDER_NAME).toPath(), Paths.append(Paths.getPath(userHome.getPath()), Constants.TRASH_ROOT_FOLDER_NAME).toPath());
else {
FolderCreationParameters trashFolderParameters = FolderCreationParameters.builder().name(Constants.TRASH_ROOT_FOLDER_NAME).description("trash of "+user).author(user).on(userHome.getIdentifier()).with(session).build();
Utils.createFolderInternally(trashFolderParameters, null, true);
}
Boolean oldVresExists = session.nodeExists(Paths.append(workspacePath, Constants.OLD_VRE_FOLDER_PARENT_NAME).toPath());
if (oldVresExists)
session.move(Paths.append(workspacePath, Constants.OLD_VRE_FOLDER_PARENT_NAME).toPath(), Paths.append(Paths.getPath(userHome.getPath()), Constants.PERSONAL_VRES_FOLDER_PARENT_NAME).toPath());
else {
//creating Vre container folder
FolderCreationParameters vreFolderParameters = FolderCreationParameters.builder().name(Constants.PERSONAL_VRES_FOLDER_PARENT_NAME).description("vre folder container of "+user).author(user).on(userHome.getIdentifier()).with(session).build();
Utils.createFolderInternally(vreFolderParameters, null, true);
}
}
/*
//creating inbox folder
FolderCreationParameters inboxFolderParameters = FolderCreationParameters.builder().name(Constants.INBOX_FOLDER_NAME).description("inbox of "+user).author(user).on(userHome.getIdentifier()).with(session).build();
Utils.createFolderInternally(inboxFolderParameters, null, true);
//creating outbox folder
FolderCreationParameters outboxFolderParameters = FolderCreationParameters.builder().name(Constants.OUTBOX_FOLDER_NAME).description("outbox of "+user).author(user).on(userHome.getIdentifier()).with(session).build();
Utils.createFolderInternally(outboxFolderParameters, null, true);
*/
userHome.setProperty(Constants.HOME_VERSION_PROP, 1l);
session.save();
}catch(StorageHubException she ){
} catch (StorageHubException she) {
log.error(she.getErrorMessage(), she);
GXOutboundErrorResponse.throwException(she, Response.Status.fromStatusCode(she.getStatus()));
}catch(RepositoryException re ){
} catch (RepositoryException re) {
log.error("jcr error creating item", re);
GXOutboundErrorResponse.throwException(new BackendGenericError("jcr error creating item", re));
} finally {
if (session!=null)
if (session != null)
session.logout();
}
return userId;
}
@DELETE
@Path("{user}")
@AuthorizationControl(allowedRoles={INFRASTRUCTURE_MANAGER_ROLE})
public String deleteUser(@PathParam("user") final String user){
@AuthorizationControl(allowedRoles = { INFRASTRUCTURE_MANAGER_ROLE })
public String deleteUser(@PathParam("user") final String user) {
InnerMethodName.set("deleteUser");
@ -353,33 +168,17 @@ public class UserManager {
session = (JackrabbitSession) repository.getRepository().login(Constants.JCR_CREDENTIALS);
org.apache.jackrabbit.api.security.user.UserManager usrManager = session.getUserManager();
User authorizable = (User) usrManager.getAuthorizable(new PrincipalImpl(user));
if (authorizable!=null)
removeUserFromBelongingGroup(session, authorizable, usrManager);
else log.warn("user was already deleted from jackrabbit, trying to delete folders");
unshareUsersFolders(session, user);
removeUserHomeAndDeleteFiles(session, user);
//FINALIZE user removal
if (authorizable!=null && !authorizable.isGroup()) {
log.info("removing user {}", user);
authorizable.remove();
} else log.warn("the user {} was already deleted, it should never happen", user);
userHandler.deleteUser(session, user);
session.save();
}catch(StorageHubException she ){
} catch (StorageHubException she) {
log.error(she.getErrorMessage(), she);
GXOutboundErrorResponse.throwException(she, Response.Status.fromStatusCode(she.getStatus()));
}catch(RepositoryException re ){
} catch (RepositoryException re) {
log.error("jcr error creating item", re);
GXOutboundErrorResponse.throwException(new BackendGenericError("jcr error creating item", re));
} finally {
if (session!=null)
if (session != null)
session.logout();
}
@ -389,129 +188,25 @@ public class UserManager {
@GET
@Path("{user}/groups")
@Produces(MediaType.APPLICATION_JSON)
public List<String> getGroupsPerUser(@PathParam("user") final String user){
public List<String> getGroupsPerUser(@PathParam("user") final String user) {
InnerMethodName.set("getGroupsPerUser");
JackrabbitSession session = null;
List<String> groups= new ArrayList<>();
List<String> groups = new ArrayList<>();
try {
session = (JackrabbitSession) repository.getRepository().login(Constants.JCR_CREDENTIALS);
org.apache.jackrabbit.api.security.user.UserManager usrManager = session.getUserManager();
User authUser = (User) usrManager.getAuthorizable(new PrincipalImpl(user));
Iterator<Group> groupsAuth =authUser.memberOf();
while (groupsAuth.hasNext()) {
Authorizable group = groupsAuth.next();
groups.add(group.getPrincipal().getName());
}
}catch(RepositoryException re ){
userHandler.getGroupsPerUser(session, user);
} catch (RepositoryException re) {
log.error("jcr error creating item", re);
GXOutboundErrorResponse.throwException(new BackendGenericError("jcr error creating item", re));
} finally {
if (session!=null)
if (session != null)
session.logout();
}
return groups;
}
private void removeUserFromBelongingGroup(JackrabbitSession session, User authorizable, org.apache.jackrabbit.api.security.user.UserManager usrManager) throws RepositoryException, StorageHubException {
Iterator<Authorizable> groups = session.getUserManager().findAuthorizables(new Query() {
@Override
public <T> void build(QueryBuilder<T> builder) {
builder.setSelector(Group.class);
}
});
String user = authorizable.getPrincipal().getName();
while(groups.hasNext()) {
Authorizable group = groups.next();
log.info("group found {}", group.getPrincipal().getName() );
if (group.isGroup() && ((Group)group).isMember(authorizable)) {
boolean success = groupHandler.removeUserFromGroup(group.getPrincipal().getName(), user, session);
log.warn("user {} {} removed from vre {}",user,success?"":"not" ,group.getPrincipal().getName());
}
}
}
private void unshareUsersFolders(JackrabbitSession session, String user){
try {
Node sharedFolderNode = session.getNode(Constants.SHARED_FOLDER_PATH);
Predicate<Node> sharedWithUserChecker = new Predicate<Node>() {
@Override
public boolean test(Node t) {
try {
authChecker.checkReadAuthorizationControl(t.getSession(), user, t.getIdentifier());
return true;
} catch (UserNotAuthorizedException | BackendGenericError | RepositoryException e) {
return false;
}
}
};
List<SharedFolder> items = Utils.getItemList(sharedWithUserChecker, sharedFolderNode, Excludes.ALL, null, false, SharedFolder.class);
log.debug(" Shared folder to unshare found are {}", items.size());
for (SharedFolder item: items) {
String title = item.getTitle();
log.debug("in list folder name {} with title {} and path {} ",item.getName(), title, item.getPath());
if (item.isPublicItem() && !item.getUsers().getMap().containsKey(user)) continue;
if (item.isVreFolder()) continue;
log.info("removing sharing for folder name {} with title {} and path {} ",item.getName(), title, item.getPath());
String owner = item.getOwner();
Set<String> usersToUnshare= owner.equals(user)? Collections.emptySet():Collections.singleton(user);
try {
unshareHandler.unshareForRemoval(session, usersToUnshare, session.getNodeByIdentifier(item.getId()), user);
}catch (Throwable e) {
log.warn("error unsharing folder with title '{}' and id {} ", title, item.getId(), e);
}
}
} catch (Throwable t) {
log.warn("error getting folder shared with {}",user, t);
}
}
private void removeUserHomeAndDeleteFiles(JackrabbitSession session, String user) throws RepositoryException, StorageHubException {
org.gcube.common.storagehub.model.Path homePath = pathUtil.getHome(user);
org.gcube.common.storagehub.model.Path workspacePath = pathUtil.getWorkspacePath(user);
try {
Node workspaceNode = session.getNode(workspacePath.toPath());
List<Item> workspaceItems = Utils.getItemList(workspaceNode, Excludes.GET_ONLY_CONTENT, null, true, null).stream().filter(i -> !i.isShared()).collect(Collectors.toList());
trashHandler.removeOnlyNodesContent(session, workspaceItems);
} catch (PathNotFoundException e) {
log.warn("{} workspace dir {} was already deleted", user, homePath.toPath());
}
try {
org.gcube.common.storagehub.model.Path trashPath = pathUtil.getTrashPath(user, session);
Node trashNode = session.getNode(trashPath.toPath());
List<Item> trashItems = Utils.getItemList(trashNode, Excludes.ALL, null, true, null);
trashHandler.removeOnlyNodesContent(session, trashItems);
} catch (PathNotFoundException e) {
log.warn("{} trash dir {} was already deleted", user, homePath.toPath());
}
try {
Node homeNode = session.getNode(homePath.toPath());
homeNode.remove();
} catch (PathNotFoundException e) {
log.warn("{} home dir {} was already deleted", user, homePath.toPath());
}
}
}