From daeaaf929989e6b7a8b508774e09ebf2e31678a9 Mon Sep 17 00:00:00 2001 From: Lucio Lelii Date: Fri, 30 Nov 2018 16:49:35 +0000 Subject: [PATCH] git-svn-id: https://svn.d4science-ii.research-infrastructures.eu/gcube/branches/data-access/storagehub-webapp/1.0@174493 82a268e6-3cf1-43bd-a215-b396298e98cf --- pom.xml | 78 ++++++++-- .../storagehub/AuthorizationChecker.java | 19 ++- .../data/access/storagehub/Constants.java | 5 +- .../data/access/storagehub/MetaInfo.java | 33 +++- .../data/access/storagehub/StorageHub.java | 2 + .../gcube/data/access/storagehub/Utils.java | 7 +- .../storagehub/services/ItemSharing.java | 12 +- .../storagehub/services/ItemsCreator.java | 10 +- .../storagehub/services/ItemsManager.java | 55 ++++--- .../storagehub/services/UserManager.java | 141 ++++++++++++++++++ .../org/gcube/data/access/fs/Expressions.java | 4 +- .../org/gcube/data/access/fs/TestFields.java | 2 +- 12 files changed, 309 insertions(+), 59 deletions(-) create mode 100644 src/main/java/org/gcube/data/access/storagehub/services/UserManager.java diff --git a/pom.xml b/pom.xml index 3958396..71c8026 100644 --- a/pom.xml +++ b/pom.xml @@ -43,11 +43,22 @@ pom import + + org.aspectj + aspectjrt + 1.8.2 + - + + + org.aspectj + aspectjrt + provided + + org.gcube.core common-smartgears @@ -94,7 +105,7 @@ org.gcube.common gxRest [1.0.0-SNAPSHOT,2.0.0-SNAPSHOT) - + @@ -305,18 +316,65 @@ - - ${artifactId} + + + + org.eclipse.m2e + lifecycle-mapping + 1.0.0 + + + + + + org.codehaus.mojo + aspectj-maven-plugin + + [1.0,) + + test-compile + compile + + + + + + + + + + + + org.codehaus.mojo + aspectj-maven-plugin + 1.7 + + 1.8 + 1.8 + 1.8 + + + org.gcube.common + common-authorization + + + + + + + compile + + + + + + - maven-compiler-plugin - 2.3.2 - - 1.8 - 1.8 - + org.codehaus.mojo + aspectj-maven-plugin org.apache.maven.plugins diff --git a/src/main/java/org/gcube/data/access/storagehub/AuthorizationChecker.java b/src/main/java/org/gcube/data/access/storagehub/AuthorizationChecker.java index dae87c9..754429e 100644 --- a/src/main/java/org/gcube/data/access/storagehub/AuthorizationChecker.java +++ b/src/main/java/org/gcube/data/access/storagehub/AuthorizationChecker.java @@ -14,6 +14,7 @@ import org.gcube.common.authorization.library.provider.AuthorizationProvider; import org.gcube.common.storagehub.model.Excludes; 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.UserNotAuthorizedException; import org.gcube.common.storagehub.model.items.Item; import org.gcube.common.storagehub.model.items.SharedFolder; @@ -38,7 +39,7 @@ public class AuthorizationChecker { if (item.isShared()) { SharedFolder parentShared = node2Item.getItem(retrieveSharedFolderParent(node, session), Excludes.EXCLUDE_ACCOUNTING); - if (!parentShared.getUsers().getValues().containsKey(login)) + if (!parentShared.getUsers().getMap().containsKey(login)) throw new UserNotAuthorizedException("Insufficent Provileges for user "+login+" to read node with id "+id); } else if (item.getOwner()==null || !item.getOwner().equals(login)) throw new UserNotAuthorizedException("Insufficent Provileges for user "+login+" to read node with id "+id); @@ -61,8 +62,8 @@ public class AuthorizationChecker { String login = AuthorizationProvider.instance.get().getClient().getId(); if (item==null) throw new UserNotAuthorizedException("Insufficent Provileges for user "+login+" to write into node with id "+id+": it's not a valid StorageHub node"); - - if (Constants.PROTECTED_FOLDER.contains(item.getName()) || Constants.PROTECTED_FOLDER.contains(item.getTitle())) + + if (Constants.WRITE_PROTECTED_FOLDER.contains(item.getName()) || Constants.WRITE_PROTECTED_FOLDER.contains(item.getTitle())) throw new UserNotAuthorizedException("Insufficent Provileges for user "+login+" to write into node with id "+id+": it's a protected folder"); if (item.isShared()) { @@ -95,11 +96,19 @@ public class AuthorizationChecker { } + public void checkMoveOpsForProtectedFolders(Session session, String id) throws InvalidCallParameters, BackendGenericError, RepositoryException { + Node node = session.getNodeByIdentifier(id); + Item item = node2Item.getItem(node, Excludes.ALL); + if (Constants.PROTECTED_FOLDER.contains(item.getName()) || Constants.PROTECTED_FOLDER.contains(item.getTitle())) + throw new InvalidCallParameters("protected folder cannot be moved or deleted"); + } + + public void checkAdministratorControl(Session session, SharedFolder item) throws UserNotAuthorizedException, BackendGenericError, RepositoryException { - + //TODO: riguardare qeusto pezzo di codice String login = AuthorizationProvider.instance.get().getClient().getId(); - if (item==null) throw new UserNotAuthorizedException("Insufficent Provileges for user "+login+" to read node with id "+item.getId()+": it's not a valid StorageHub node"); + if (item==null) throw new UserNotAuthorizedException("Insufficent Provileges for user "+login+": it's not a valid StorageHub node"); Node node = session.getNodeByIdentifier(item.getId()); diff --git a/src/main/java/org/gcube/data/access/storagehub/Constants.java b/src/main/java/org/gcube/data/access/storagehub/Constants.java index 070da7a..8d7a25b 100644 --- a/src/main/java/org/gcube/data/access/storagehub/Constants.java +++ b/src/main/java/org/gcube/data/access/storagehub/Constants.java @@ -9,6 +9,7 @@ public class Constants { public static final String SHARED_FOLDER_PATH = "/Share"; + public static final String WORKSPACE_ROOT_FOLDER_NAME ="Workspace"; public static final String TRASH_ROOT_FOLDER_NAME ="Trash"; @@ -20,5 +21,7 @@ public class Constants { public static final List FOLDERS_TO_EXLUDE = Arrays.asList(Constants.VRE_FOLDER_PARENT_NAME, Constants.TRASH_ROOT_FOLDER_NAME); - public static final List PROTECTED_FOLDER = Arrays.asList(Constants.VRE_FOLDER_PARENT_NAME, Constants.TRASH_ROOT_FOLDER_NAME); + public static final List WRITE_PROTECTED_FOLDER = Arrays.asList(Constants.VRE_FOLDER_PARENT_NAME, Constants.TRASH_ROOT_FOLDER_NAME); + + public static final List PROTECTED_FOLDER = Arrays.asList(Constants.WORKSPACE_ROOT_FOLDER_NAME, Constants.VRE_FOLDER_PARENT_NAME, Constants.TRASH_ROOT_FOLDER_NAME); } diff --git a/src/main/java/org/gcube/data/access/storagehub/MetaInfo.java b/src/main/java/org/gcube/data/access/storagehub/MetaInfo.java index f75a031..e04a540 100644 --- a/src/main/java/org/gcube/data/access/storagehub/MetaInfo.java +++ b/src/main/java/org/gcube/data/access/storagehub/MetaInfo.java @@ -1,13 +1,36 @@ package org.gcube.data.access.storagehub; -import lombok.Data; -@Data public class MetaInfo { - long size; - String storageId; + private long size; + + private String storageId; - String remotePath; + private String remotePath; + + public long getSize() { + return size; + } + + public void setSize(long size) { + this.size = size; + } + + public String getStorageId() { + return storageId; + } + + public void setStorageId(String storageId) { + this.storageId = storageId; + } + + public String getRemotePath() { + return remotePath; + } + + public void setRemotePath(String remotePath) { + this.remotePath = remotePath; + } } diff --git a/src/main/java/org/gcube/data/access/storagehub/StorageHub.java b/src/main/java/org/gcube/data/access/storagehub/StorageHub.java index 94ba28e..d22764d 100644 --- a/src/main/java/org/gcube/data/access/storagehub/StorageHub.java +++ b/src/main/java/org/gcube/data/access/storagehub/StorageHub.java @@ -10,6 +10,7 @@ import org.gcube.data.access.storagehub.services.ACLManager; import org.gcube.data.access.storagehub.services.ItemSharing; import org.gcube.data.access.storagehub.services.ItemsCreator; import org.gcube.data.access.storagehub.services.ItemsManager; +import org.gcube.data.access.storagehub.services.UserManager; import org.gcube.data.access.storagehub.services.WorkspaceManager; import org.glassfish.jersey.media.multipart.MultiPartFeature; @@ -26,6 +27,7 @@ public class StorageHub extends Application { classes.add(ItemsCreator.class); classes.add(ACLManager.class); classes.add(ItemSharing.class); + classes.add(UserManager.class); return classes; } diff --git a/src/main/java/org/gcube/data/access/storagehub/Utils.java b/src/main/java/org/gcube/data/access/storagehub/Utils.java index 6dea100..14d43c4 100644 --- a/src/main/java/org/gcube/data/access/storagehub/Utils.java +++ b/src/main/java/org/gcube/data/access/storagehub/Utils.java @@ -268,7 +268,7 @@ public class Utils { } } - public static Node createFolderInternally(Session ses, Node destinationNode, String name, String description, String login, AccountingHandler accountingHandler) throws BackendGenericError { + public static Node createFolderInternally(Session ses, Node destinationNode, String name, String description, boolean hidden, String login, AccountingHandler accountingHandler) throws BackendGenericError { String uniqueName = Utils.checkExistanceAndGetUniqueName(ses, destinationNode, name); @@ -278,7 +278,7 @@ public class Utils { item.setTitle(uniqueName); item.setDescription(description); //item.setCreationTime(now); - item.setHidden(false); + item.setHidden(hidden); item.setLastAction(ItemAction.CREATED); item.setLastModificationTime(now); item.setLastModifiedBy(login); @@ -289,7 +289,8 @@ public class Utils { //item.setHidden(destinationItem.isHidden()); Node newNode = new Item2NodeConverter().getNode(ses, destinationNode, item); - accountingHandler.createFolderAddObj(name, item.getClass().getSimpleName(), null, ses, newNode, false); + if (accountingHandler!=null) + accountingHandler.createFolderAddObj(name, item.getClass().getSimpleName(), null, ses, newNode, false); return newNode; } diff --git a/src/main/java/org/gcube/data/access/storagehub/services/ItemSharing.java b/src/main/java/org/gcube/data/access/storagehub/services/ItemSharing.java index 3d55be8..38ffd68 100644 --- a/src/main/java/org/gcube/data/access/storagehub/services/ItemSharing.java +++ b/src/main/java/org/gcube/data/access/storagehub/services/ItemSharing.java @@ -213,7 +213,7 @@ public class ItemSharing { throw new InvalidItemException("item with id "+id+" cannot be unshared"); SharedFolder sharedItem =(SharedFolder) item; - Set usersInSharedFolder = new HashSet<>(sharedItem.getUsers().getValues().keySet()); + Set usersInSharedFolder = new HashSet<>(sharedItem.getUsers().getMap().keySet()); usersInSharedFolder.removeAll(users); if (users==null || users.size()==0 || usersInSharedFolder.size()<=1) @@ -257,7 +257,7 @@ public class ItemSharing { try { log.debug("user list is empty, I'm going to remove also the shared dir"); //TODO: take the admin folder and remove his clone then move the shared folder from share to the user home and change the folder type - String adminDirPath = (String)item.getUsers().getValues().get(login); + String adminDirPath = (String)item.getUsers().getMap().get(login); String[] splitString = adminDirPath.split("/"); String parentDirectoryId = splitString[0]; String directoryName = splitString[1]; @@ -296,7 +296,7 @@ public class ItemSharing { if (login.equals(item.getOwner())) throw new InvalidCallParameters("the callor is the owner, the folder cannot be unshared"); - if (item.getUsers().getValues().get(login)==null) + if (item.getUsers().getMap().get(login)==null) throw new InvalidCallParameters("the folder is not shared with user "+login); Node sharedFolderNode =ses.getNodeByIdentifier(item.getId()); @@ -323,7 +323,7 @@ public class ItemSharing { usersNode.remove(); Node newUsersNode = sharedItemNode.addNode(NodeConstants.USERS_NAME); - item.getUsers().getValues().entrySet().stream().filter(entry -> !entry.getKey().equals(login)).forEach(entry-> {try { + item.getUsers().getMap().entrySet().stream().filter(entry -> !entry.getKey().equals(login)).forEach(entry-> {try { newUsersNode.setProperty(entry.getKey(), (String)entry.getValue()); } catch (Exception e) { log.error("error adding property to shared node users node under "+item.getId()); @@ -371,7 +371,7 @@ public class ItemSharing { usersNode.remove(); Node newUsersNode = sharedItemNode.addNode(NodeConstants.USERS_NAME); - item.getUsers().getValues().entrySet().stream().filter(entry -> !usersToUnshare.contains(entry.getKey())).forEach(entry-> {try { + item.getUsers().getMap().entrySet().stream().filter(entry -> !usersToUnshare.contains(entry.getKey())).forEach(entry-> {try { newUsersNode.setProperty(entry.getKey(), (String)entry.getValue()); } catch (Exception e) { log.error("error adding property to shared node users node under "+item.getId()); @@ -387,7 +387,7 @@ public class ItemSharing { public String removeSharingForUser(String user, Session ses, SharedFolder item) throws RepositoryException { - String userDirPath = (String)item.getUsers().getValues().get(user); + String userDirPath = (String)item.getUsers().getMap().get(user); if (userDirPath==null) return null; String[] splitString = userDirPath.split("/"); String parentDirectoryId = splitString[0]; diff --git a/src/main/java/org/gcube/data/access/storagehub/services/ItemsCreator.java b/src/main/java/org/gcube/data/access/storagehub/services/ItemsCreator.java index ec04d9e..86e90eb 100644 --- a/src/main/java/org/gcube/data/access/storagehub/services/ItemsCreator.java +++ b/src/main/java/org/gcube/data/access/storagehub/services/ItemsCreator.java @@ -102,7 +102,7 @@ public class ItemsCreator { @Produces(MediaType.TEXT_PLAIN) @Consumes(MediaType.APPLICATION_FORM_URLENCODED) @Path("/{id}/create/FOLDER") - public String createFolder(@PathParam("id") String id, @FormParam("name") String name, @FormParam("description") String description) { + public String createFolder(@PathParam("id") String id, @FormParam("name") String name, @FormParam("description") String description, @FormParam("hidden") boolean hidden) { InnerMethodName.instance.set("createItem(FOLDER)"); log.info("create folder item called"); Session ses = null; @@ -131,7 +131,7 @@ public class ItemsCreator { ses.getWorkspace().getLockManager().lock(destination.getPath(), false, true, 0,login); Node newNode; try { - newNode = Utils.createFolderInternally(ses, destination, name, description, login, accountingHandler); + newNode = Utils.createFolderInternally(ses, destination, name, description, hidden, login, accountingHandler); ses.save(); } finally { ses.getWorkspace().getLockManager().unlock(destination.getPath()); @@ -320,7 +320,7 @@ public class ItemsCreator { Node parentDirectoryNode = null; try { - parentDirectoryNode = Utils.createFolderInternally(ses, destination, parentFolderName, "", login, accountingHandler); + parentDirectoryNode = Utils.createFolderInternally(ses, destination, parentFolderName, "", false, login, accountingHandler); Set fileNodes = new HashSet<>(); @@ -338,10 +338,10 @@ public class ItemsCreator { log.debug("creating directory with entire path {}, name {}, parentPath {} ", entirePath, name, parentPath); Node createdNode; if (parentPath.isEmpty()) { - createdNode = Utils.createFolderInternally(ses, parentDirectoryNode, name, "", login, accountingHandler); + createdNode = Utils.createFolderInternally(ses, parentDirectoryNode, name, "", false, login, accountingHandler); }else { Node parentNode = directoryNodeMap.get(parentPath); - createdNode = Utils.createFolderInternally(ses, parentNode, name, "", login, accountingHandler); + createdNode = Utils.createFolderInternally(ses, parentNode, name, "", false, login, accountingHandler); } directoryNodeMap.put(entirePath, createdNode); continue; diff --git a/src/main/java/org/gcube/data/access/storagehub/services/ItemsManager.java b/src/main/java/org/gcube/data/access/storagehub/services/ItemsManager.java index c6a150d..d6d3ee7 100644 --- a/src/main/java/org/gcube/data/access/storagehub/services/ItemsManager.java +++ b/src/main/java/org/gcube/data/access/storagehub/services/ItemsManager.java @@ -307,16 +307,14 @@ public class ItemsManager { ses = repository.getRepository().login(CredentialHandler.getAdminCredentials(context)); authChecker.checkReadAuthorizationControl(ses, id); Node currentNode =ses.getNodeByIdentifier(id); - Item currentItem = node2Item.getItem(currentNode, excludes); - - if (!currentItem.isShared()) - throw new InvalidItemException("this item is not shared"); log.trace("current node is {}",currentNode.getPath()); - while (!node2Item.checkNodeType(currentNode, SharedFolder.class)) - currentNode = currentNode.getParent(); - - sharedParent = node2Item.getItem(currentNode, excludes); + Node sharedParentNode = getSharedParentNode(currentNode); + + if (sharedParentNode==null) + throw new InvalidCallParameters("item is not shared"); + + sharedParent = node2Item.getItem(sharedParentNode, excludes); }catch(RepositoryException re ){ log.error("jcr error getting rootSharedFolder", re); @@ -331,6 +329,16 @@ public class ItemsManager { return new ItemWrapper(sharedParent); } + private Node getSharedParentNode(Node node) throws RepositoryException, BackendGenericError{ + Item currentItem = node2Item.getItem(node, Excludes.ALL); + if (!currentItem.isShared()) + return null; + Node currentNode = node; + while (!node2Item.checkNodeType(currentNode, SharedFolder.class)) + currentNode = currentNode.getParent(); + return currentNode; + } + @GET @Path("{id}/versions") @Produces(MediaType.APPLICATION_JSON) @@ -443,7 +451,7 @@ public class ItemsManager { log.trace("current node is {}",currentNode.getPath()); while (!(currentNode.getPath()+"/").equals(absolutePath.toPath())) { if (currentItem instanceof SharedFolder){ - Map users = ((SharedFolder) currentItem).getUsers().getValues(); + Map users = ((SharedFolder) currentItem).getUsers().getMap(); String[] user = ((String)users.get(login)).split("/"); String parentId = user[0]; currentNode = ses.getNodeByIdentifier(parentId); @@ -557,13 +565,14 @@ public class ItemsManager { @Path("{id}/move") public String move(@FormParam("destinationId") String destinationId){ InnerMethodName.instance.set("move"); - //TODO: check if identifier is The Workspace root, or the thras folder or the VREFolder root or if the item is thrashed + Session ses = null; try{ final String login = AuthorizationProvider.instance.get().getClient().getId(); ses = repository.getRepository().login(CredentialHandler.getAdminCredentials(context)); - + + authChecker.checkMoveOpsForProtectedFolders(ses, id); authChecker.checkWriteAuthorizationControl(ses, destinationId, true); authChecker.checkWriteAuthorizationControl(ses, id, false); @@ -576,21 +585,25 @@ public class ItemsManager { if (item instanceof SharedFolder) throw new InvalidItemException("shared folder cannot be moved"); - + + if (item instanceof FolderItem && Utils.hasSharedChildren(nodeToMove)) + throw new InvalidItemException("folder item with shared children cannot be moved"); + if (Constants.FOLDERS_TO_EXLUDE.contains(item.getTitle()) || Constants.FOLDERS_TO_EXLUDE.contains(destinationItem.getTitle())) throw new InvalidItemException("protected folder cannot be moved"); if (!(destinationItem instanceof FolderItem)) throw new InvalidItemException("destination item is not a folder"); + if (item.isShared() && (!destinationItem.isShared() || !getSharedParentNode(nodeToMove).getIdentifier().equals(getSharedParentNode(destination).getIdentifier()))) + throw new InvalidCallParameters("shared Item cannot be moved in a different shared folder or in a private folder"); + ses.getWorkspace().getLockManager().lock(destination.getPath(), false, true, 0,login); ses.getWorkspace().getLockManager().lock(nodeToMove.getPath(), true, true, 0,login); try { String uniqueName =(Utils.checkExistanceAndGetUniqueName(ses, destination, nodeToMove.getName())); String newPath = String.format("%s/%s",destination.getPath(), uniqueName); - if (item instanceof FolderItem && Utils.hasSharedChildren(nodeToMove)) - throw new InvalidItemException("folder item with shared children cannot be moved"); - + ses.getWorkspace().move(nodeToMove.getPath(), newPath); Utils.setPropertyOnChangeNode(ses.getNode(newPath), login, ItemAction.MOVED); @@ -695,14 +708,14 @@ public class ItemsManager { @Path("{id}/rename") public Response rename(@FormParam("newName") String newName){ InnerMethodName.instance.set("rename"); - //TODO: check if identifier is The Workspace root, or the trash folder or the VREFolder root or if the item is thrashed Session ses = null; try{ final String login = AuthorizationProvider.instance.get().getClient().getId(); ses = repository.getRepository().login(CredentialHandler.getAdminCredentials(context)); - + + authChecker.checkMoveOpsForProtectedFolders(ses, id); authChecker.checkWriteAuthorizationControl(ses, id, false); final Node nodeToMove = ses.getNodeByIdentifier(id); @@ -750,7 +763,7 @@ public class ItemsManager { @PUT @Consumes(MediaType.APPLICATION_JSON) @Path("/{id}/metadata") - public Response setProperties(org.gcube.common.storagehub.model.Metadata metadata){ + public Response setMetadata(org.gcube.common.storagehub.model.Metadata metadata){ InnerMethodName.instance.set("updateMetadata"); Session ses = null; @@ -767,7 +780,7 @@ public class ItemsManager { ses.getWorkspace().getLockManager().lock(nodeToUpdate.getPath(), false, true, 0,login); try { - item2Node.updateMetadataNode(ses, nodeToUpdate, metadata.getValues(), login); + item2Node.updateMetadataNode(ses, nodeToUpdate, metadata.getMap(), login); ses.save(); }finally { ses.getWorkspace().getLockManager().unlock(nodeToUpdate.getPath()); @@ -795,7 +808,7 @@ public class ItemsManager { @Path("{id}") public Response deleteItem(){ InnerMethodName.instance.set("deleteItem"); - //TODO: check if identifier is The Workspace root, or the trash folder or the VREFolder root + //TODO: check also that is not already trashed Session ses = null; try{ @@ -804,7 +817,7 @@ public class ItemsManager { //TODO check if it is possible to change all the ACL on a workspace ses = repository.getRepository().login(CredentialHandler.getAdminCredentials(context)); - + authChecker.checkMoveOpsForProtectedFolders(ses, id); authChecker.checkWriteAuthorizationControl(ses, id, false); final Node nodeToDelete = ses.getNodeByIdentifier(id); diff --git a/src/main/java/org/gcube/data/access/storagehub/services/UserManager.java b/src/main/java/org/gcube/data/access/storagehub/services/UserManager.java new file mode 100644 index 0000000..ded6afc --- /dev/null +++ b/src/main/java/org/gcube/data/access/storagehub/services/UserManager.java @@ -0,0 +1,141 @@ +package org.gcube.data.access.storagehub.services; + +import java.util.ArrayList; +import java.util.Iterator; +import java.util.List; + +import javax.inject.Inject; +import javax.jcr.Node; +import javax.jcr.Session; +import javax.servlet.ServletContext; +import javax.ws.rs.DELETE; +import javax.ws.rs.FormParam; +import javax.ws.rs.GET; +import javax.ws.rs.POST; +import javax.ws.rs.Path; +import javax.ws.rs.PathParam; +import javax.ws.rs.Produces; +import javax.ws.rs.core.Context; +import javax.ws.rs.core.MediaType; + +import org.apache.jackrabbit.api.JackrabbitSession; +import org.apache.jackrabbit.api.security.user.Authorizable; +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.gcube.common.authorization.library.annotations.AuthorizationControl; +import org.gcube.common.authorization.library.provider.AuthorizationProvider; +import org.gcube.common.gxrest.response.outbound.GXOutboundErrorResponse; +import org.gcube.common.storagehub.model.exceptions.BackendGenericError; +import org.gcube.data.access.storagehub.Constants; +import org.gcube.data.access.storagehub.Utils; +import org.gcube.data.access.storagehub.handlers.CredentialHandler; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; + +@Path("users") +public class UserManager { + + @Context ServletContext context; + + private static final Logger log = LoggerFactory.getLogger(UserManager.class); + + @Inject + RepositoryInitializer repository; + + @GET + @Path("") + @Produces(MediaType.APPLICATION_JSON) + @AuthorizationControl(allowed={"lucio.lelii"}) + public List getUsers(){ + + JackrabbitSession session = null; + List users= new ArrayList<>(); + try { + session = (JackrabbitSession) repository.getRepository().login(CredentialHandler.getAdminCredentials(context)); + + Iterator result = session.getUserManager().findAuthorizables(new Query() { + + @Override + public void build(QueryBuilder builder) { + builder.setSelector(User.class); + } + }); + + while (result.hasNext()) { + Authorizable user = result.next(); + log.info("user {} found",user.getPrincipal().getName()); + users.add(user.getPrincipal().getName()); + } + }catch(Exception e) { + log.error("jcr error getting users", e); + GXOutboundErrorResponse.throwException(new BackendGenericError(e)); + } finally { + if (session!=null) + session.logout(); + } + return users; + } + + @POST + @Path("") + @AuthorizationControl(allowed={"lucio.lelii"}) + public String createUser(@FormParam("user") String user, @FormParam("password") String password){ + + JackrabbitSession session = null; + String userId = null; + try { + session = (JackrabbitSession) repository.getRepository().login(CredentialHandler.getAdminCredentials(context)); + + 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"); + + Node workspaceFolder = Utils.createFolderInternally(session, userHome, Constants.WORKSPACE_ROOT_FOLDER_NAME, "workspace of "+user, false, user, null); + Node trashFolder = Utils.createFolderInternally(session, workspaceFolder, Constants.TRASH_ROOT_FOLDER_NAME, "trash of "+user, false, user, null); + Node specialFolder = Utils.createFolderInternally(session, workspaceFolder, Constants.VRE_FOLDER_PARENT_NAME, "special folder container of "+user, false, user, null); + + session.save(); + }catch(Exception e) { + log.error("jcr error getting users", e); + GXOutboundErrorResponse.throwException(new BackendGenericError(e)); + } finally { + if (session!=null) + session.logout(); + } + + return userId; + } + + @DELETE + @Path("{id}") + @AuthorizationControl(allowed={"lucio.lelii"}) + public String deleteUser(@PathParam("id") String id){ + + JackrabbitSession session = null; + String userId = null; + try { + session = (JackrabbitSession) repository.getRepository().login(CredentialHandler.getAdminCredentials(context)); + + org.apache.jackrabbit.api.security.user.UserManager usrManager = session.getUserManager(); + + Authorizable authorizable = usrManager.getAuthorizable(id); + if (!authorizable.isGroup()) + authorizable.remove(); + session.save(); + }catch(Exception e) { + log.error("jcr error getting users", e); + GXOutboundErrorResponse.throwException(new BackendGenericError(e)); + } finally { + if (session!=null) + session.logout(); + } + + return userId; + } + +} diff --git a/src/test/java/org/gcube/data/access/fs/Expressions.java b/src/test/java/org/gcube/data/access/fs/Expressions.java index aed9094..d71cc64 100644 --- a/src/test/java/org/gcube/data/access/fs/Expressions.java +++ b/src/test/java/org/gcube/data/access/fs/Expressions.java @@ -15,7 +15,7 @@ import org.junit.runner.RunWith; import org.slf4j.Logger; import org.slf4j.LoggerFactory; -@RunWith(WeldJunit4Runner.class) +//@RunWith(WeldJunit4Runner.class) public class Expressions { private static Logger log = LoggerFactory.getLogger(Expression.class); @@ -24,7 +24,7 @@ public class Expressions { Evaluators evaluators; - @Test + public void test() { evaluators.getEvaluators().forEach(s-> System.out.println(s.getType().toString())); diff --git a/src/test/java/org/gcube/data/access/fs/TestFields.java b/src/test/java/org/gcube/data/access/fs/TestFields.java index 745cb47..1591e06 100644 --- a/src/test/java/org/gcube/data/access/fs/TestFields.java +++ b/src/test/java/org/gcube/data/access/fs/TestFields.java @@ -24,7 +24,7 @@ public class TestFields { Logger logger = LoggerFactory.getLogger(TestFields.class); - @Test + //@Test public void iterateOverFields() throws Exception{ Property prop = mock(Property.class);