AnsweredAssumed Answered

[Resolu] Donner le droit à un user d'executer du code admin?

Question asked by pierreb on Aug 28, 2008
Latest reply on Mar 24, 2009 by cviaud
Bonjour,

Je suis actuellement entrain d'écrire un Wizard Java qui effectue quelques tâches d'habitude réservées à l'administrateur lors de la création d'un nouvel espace.
En détail, il doit :
- créer un nouvel espace à partir d'un template existant
- définir des droits sur les espaces crées
- créer un un groupe Membre "nom de l'espace", et un groupe Admin "nom de l'espace"
- placer des utilisateurs dans ces groupes

Je vous fournis le code de ma classe complet en bas du post.
Mon problème est le suivant, la technique que j'ai employée fonctionne très bien quand l'Administrateur lance le wizard. Mais quand c'est un utilisateur normal qui le lance, une exception se produit (logique me direz vous il n'a pas les droits) :
Echec de création du nouveau Espace suite à l'erreur : Accès interdit. Vous n'avez pas la permission de réaliser cette opération.

Sur le code :
if(this.authorityService.authorityExists(this.authorityService.getName(AuthorityType.GROUP, CreateProject.companyGroup)) == false) { …

Ma question est donc, comment donner le droit (temporairement, seulement pendant l'exécution de mon wizard), à un utilisateur lambda d'exécuter n'importe quel code (ou alors d'exécuter mon code en tant qu'administrateur) ?

Voici la méthode finishImpl qui effectue les opérations citées en début de post :
   protected String finishImpl(FacesContext context, String outcome) throws Exception
   {  
      // Appelle le process de creation de dossier originel
       outcome = super.finishImpl(context, outcome);
      
       NodeRef espaceProjet = this.createdNode;
       NodeRef espaceTravail = nodeService.getChildByName(this.createdNode, ContentModel.ASSOC_CONTAINS, workSpaceName);
       NodeRef espaceCollab = nodeService.getChildByName(this.createdNode, ContentModel.ASSOC_CONTAINS, collaborativeSpaceName);
      
       // Récupère le nom du projet
       logger.debug("1");
       String nomEspace = (String)nodeService.getProperty(espaceProjet, ContentModel.PROP_NAME);
      
       // Génère les noms des groupes associés
       String memberGroup = "Membre " + nomEspace;
       String adminGroup = "Admin " + nomEspace;
      
       // Vérifie l'existence du groupe ATOS (parent)
       logger.debug("2");
       if(this.authorityService.authorityExists(this.authorityService.getName(AuthorityType.GROUP, CreateProject.companyGroup)) == false)
          throw new Exception("Impossible de trouver le groupe mère : " + CreateProject.companyGroup);
      
       // Crée les groupes fils
       logger.debug("3");
       String memberGroupName = this.authorityService.getName(AuthorityType.GROUP, memberGroup);
       logger.debug("4");
       if (this.authorityService.authorityExists(memberGroupName) == false)
       {
          logger.debug("Creation du groupe " + memberGroupName);
          this.authorityService.createAuthority(AuthorityType.GROUP, PermissionService.GROUP_PREFIX + CreateProject.companyGroup, memberGroup);
       }
       else
       {
          logger.warn("Le groupe " + memberGroup + "existe deja");
       }
      
       String adminGroupName = this.authorityService.getName(AuthorityType.GROUP, adminGroup);
       if (this.authorityService.authorityExists(adminGroupName) == false)
       {
          this.authorityService.createAuthority(AuthorityType.GROUP, memberGroupName, adminGroup);
          logger.debug("Creation du groupe " + adminGroupName);
       }
       else
       {
          logger.info("Le groupe " + memberGroup + "existe deja");
       }
      
       // Positionne les droits sur l'espace projet
       List<UserGroupRole> projetGroupRoles = new ArrayList<UserGroupRole>(8);
        addAuthorityWithRole(adminGroup, "Coordinator", projetGroupRoles);
        addAuthorityWithRole(memberGroup, "Collaborator", projetGroupRoles);
        addAuthorityWithRole(CreateProject.companyGroup, "Consumer", projetGroupRoles);
           /*
            * Parcourt les clients spécifiés dans l'interface web et
            * leur donne le droit de lecture
            */
           for(int i = 0; i < this.clientsGroupRoles.size(); i++)
           {
              UserGroupRole groupRole = this.clientsGroupRoles.get(i);
                 String client = groupRole.getAuthority().substring(permissionService.GROUP_PREFIX.length());
                 addAuthorityWithRole(client, "Consumer", projetGroupRoles);
           }
       
      processSpacePermissions(projetGroupRoles, espaceProjet);
      
       // Positionne les droits sur l'espace travail
       List<UserGroupRole> workGroupRoles = new ArrayList<UserGroupRole>(8);
        addAuthorityWithRole(adminGroup, "Coordinator", workGroupRoles);
        addAuthorityWithRole(memberGroup, "Collaborator", workGroupRoles);
        addAuthorityWithRole(CreateProject.companyGroup, "Consumer", workGroupRoles);
      processSpacePermissions(workGroupRoles, espaceTravail);
      
      // Postionne les droits sur l'espace collaboratif avec les clients séléctionnés dans l'interface web
      processSpacePermissions(this.clientsGroupRoles, espaceCollab);
         
      // Place le créateur (utilisateur courant) dans le Groupe Admin Projet
      try {
          String currentUserName = properties.getAuthenticationService().getCurrentUserName();
          StringBuilder label = new StringBuilder(48);

            // build a display label showing the user person name
            if (this.personService.personExists(currentUserName) == true)
            {
               // found a Person with a User authority
               NodeRef ref = this.personService.getPerson(currentUserName);
               String firstName = (String) this.nodeService.getProperty(ref, ContentModel.PROP_FIRSTNAME);
               String lastName = (String) this.nodeService.getProperty(ref, ContentModel.PROP_LASTNAME);

               // build a sensible label for display
               label.append(firstName).append(' ').append(lastName);

               // add a wrapper object with the details to the results list
               // for display
               UserAuthorityDetails userDetails = new UserAuthorityDetails(label.toString(), currentUserName);
                            
               logger.debug("Ajout de l'user " + label + "au groupe " + adminGroup);
               this.authorityService.addAuthority(adminGroupName, userDetails.getAuthority());
            }
      }
      catch(Exception e)
      {
         logger.warn("Impossible de placer l'utilisateur courant dans le groupe " + adminGroup);
         e.printStackTrace();
      }
       
       // Ajoute les membres sélectionnés au groupe Membres Projet
      for (UserAuthorityDetails membre : membresGroup)
        {
         logger.debug("Ajout de l'user " + membre.getAuthority() + "au groupe " + memberGroup);
         this.authorityService.addAuthority(memberGroupName, membre.getAuthority());
        }

       return outcome;
   }

Et voici le code de la classe complet (on sait jamais ça peut servir) :

/**
*  Assistant "Créer un Projet XXX…"
*  Crée un nouveau projet basé sur un modèle d'espace prédéfini,
*  propose le choix des groupes clients à inviter dans l'espace collaboration
*  et applique les droits sur les sous dossiers du projet.
*/
package xxxxxxxxx.wizard;

import java.text.MessageFormat;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.ResourceBundle;
import java.util.Set;

import javax.faces.component.UISelectOne;
import javax.faces.context.FacesContext;
import javax.faces.event.ActionEvent;
import javax.faces.model.DataModel;
import javax.faces.model.ListDataModel;
import javax.faces.model.SelectItem;
import javax.transaction.UserTransaction;

import org.alfresco.model.ContentModel;
import org.alfresco.service.cmr.repository.NodeRef;
import org.alfresco.service.cmr.search.ResultSet;
import org.alfresco.service.cmr.search.SearchService;
import org.alfresco.service.cmr.security.AuthorityService;
import org.alfresco.service.cmr.security.AuthorityType;
import org.alfresco.service.cmr.security.PermissionService;
import org.alfresco.service.cmr.security.PersonService;
import org.alfresco.service.namespace.NamespaceService;
import org.alfresco.web.app.Application;
import org.alfresco.web.bean.groups.GroupsDialog.UserAuthorityDetails;
import org.alfresco.web.bean.repository.Node;
import org.alfresco.web.bean.repository.Repository;
import org.alfresco.web.bean.spaces.CreateSpaceWizard;
import org.alfresco.web.bean.users.UsersBeanProperties;
import org.alfresco.web.bean.wizard.InviteUsersWizard.UserGroupRole;
import org.alfresco.web.ui.common.SortableSelectItem;
import org.alfresco.web.ui.common.Utils;
import org.alfresco.web.ui.common.component.UIGenericPicker;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;

/**
* @author Pierre Belin
* Inspiré de CreateSpaceWizard.java et InviteUsersWizard.java d'Alfresco
*/
public class CreateProject extends CreateSpaceWizard {
   
   protected static String enforcedTemplateName = "Xxxx_project";
   protected static String collaborativeSpaceName = "Espace Collaboratif";
   protected static String workSpaceName = "Espace de Travail";
   protected static String companyGroup = "xxxxx";
   
   /* I18N message strings */
   protected static final String MSG_USERROLES = "invite_users_summary";
   private static final String MSG_USERS  = "users";
   private static final String MSG_GROUPS = "groups";
   protected static final String STEP_NOTIFY = "notify";
     
   /* Beans */
   /** AuthenticationService bean reference */
   protected UsersBeanProperties properties;
   /** AuthorityService bean reference */
   protected AuthorityService authorityService;
   /** PermissionService bean reference */
   protected PermissionService permissionService;
   /** personService bean reference */
   protected PersonService personService;
     
   /* Clients - Externes */
     
   /** datamodel for table of roles for users */
   protected DataModel clientsRolesDataModel = null;
   /** liste des clients : user/group role wrapper objects */
   protected List<UserGroupRole> clientsGroupRoles = null;
     
   /* Membres */
     
   /** datamodel for table of roles for users */
   protected DataModel membresDataModel = null;
   /** liste des membres du projet */
   protected List<UserAuthorityDetails> membresGroup = null;
   
   /** True to allow duplicate authorities (with a different role) */
   protected boolean allowDuplicateAuthorities = true;
   
   private static Log logger = LogFactory.getLog(CreateProject.class);
   
   @Override
   public void init(Map<String, String> parameters)
   {
      super.init(parameters);
      
      // ==== PARTIE CREATION D'ESPACE ====

      // Override la step1 du wizard classique
      this.createFrom = "template";
   
      // Override la step2 du wizard classique
      this.getTemplateSpaces();
      Iterator<SelectItem> iterTemplates = this.templates.iterator();
      while(this.templateSpaceId == null && iterTemplates.hasNext())
      {
        SelectItem tpl = iterTemplates.next();
        if (tpl.getLabel().equals(enforcedTemplateName))
        {
           this.templateSpaceId = (String)tpl.getValue();
        }
      }
    
      // Simulation de l'appui sur 'suivant'
      this.next();
      
      // ==== PARTIE GESTION DES DROITS ====
      
      clientsGroupRoles = new ArrayList<UserGroupRole>(20);
      membresGroup =       new ArrayList<UserAuthorityDetails>(50);
   }
      
      /**
       * Returns the properties for current user-roles JSF DataModel
       *
       * @return JSF DataModel representing the current user-roles
       */
      public DataModel getClientsRolesDataModel()
      {
         if (this.clientsRolesDataModel == null)
         {
            this.clientsRolesDataModel = new ListDataModel();
         }
        
         this.clientsRolesDataModel.setWrappedData(this.clientsGroupRoles);
        
         return this.clientsRolesDataModel;
      }
     
      public DataModel getMembresDataModel()
      {
         if (this.membresDataModel == null)
         {
            this.membresDataModel = new ListDataModel();
         }
        
         this.membresDataModel.setWrappedData(this.membresGroup);
        
         return this.membresDataModel;
      }
     
      /**
       * @param properties the properties to set
       */
      public void setProperties(UsersBeanProperties properties)
      {
         this.properties = properties;
      }
     
      /**
       * @param namespaceService   The NamespaceService to set.
       */
      public void setNamespaceService(NamespaceService namespaceService)
      {
         this.namespaceService = namespaceService;
      }
     
      /**
       * @param permissionService   The PermissionService to set.
       */
      public void setPermissionService(PermissionService permissionService)
      {
         this.permissionService = permissionService;
      }
     
      /**
       * @param personService   The PersonService to set.
       */
      public void setPersonService(PersonService personService)
      {
         this.personService = personService;
      }
     
      /**
       * @param authorityService    The authorityService to set.
       */
      public void setAuthorityService(AuthorityService authorityService)
      {
         this.authorityService = authorityService;
      }
     
      /**
       * Property accessed by the Generic Picker component.
       *
       * @return the array of filter options to show in the users/groups picker
       */
      public SelectItem[] getClientsFilters()
      {
         ResourceBundle bundle = Application.getBundle(FacesContext.getCurrentInstance());
        
         return new SelectItem[] {
               //new SelectItem("0", bundle.getString(MSG_USERS)),
               //new SelectItem("1", bundle.getString(MSG_GROUPS)) };
               new SelectItem("0", bundle.getString(MSG_GROUPS)) };
      }
     
      public SelectItem[] getMembresFilters()
      {
         ResourceBundle bundle = Application.getBundle(FacesContext.getCurrentInstance());
        
         return new SelectItem[] {
               new SelectItem("0", bundle.getString(MSG_USERS)) };
      }
     
      /**
       * Query callback method executed by the Generic Picker component.
       * This method is part of the contract to the Generic Picker, it is up to the backing bean
       * to execute whatever query is appropriate and return the results.
       *
       * @param filterIndex        Index of the filter drop-down selection
       * @param contains           Text from the contains textbox
       *
       * @return An array of SelectItem objects containing the results to display in the picker.
       */
      public SelectItem[] clientsPickerCallback(int filterIndex, String contains)
      {
         FacesContext context = FacesContext.getCurrentInstance();
        
         SelectItem[] items;
        
         UserTransaction tx = null;
         try
         {
          tx = Repository.getUserTransaction(context, true);
          tx.begin();
         
             // groups - simple text based match on name
             Set<String> groups = authorityService.getAllAuthorities(AuthorityType.GROUP);
             groups.addAll(authorityService.getAllAuthorities(AuthorityType.EVERYONE));
            
             List<SelectItem> results = new ArrayList<SelectItem>(groups.size());
             String containsLower = contains.toLowerCase();
             int offset = PermissionService.GROUP_PREFIX.length();
             for (String group : groups)
             {
                if (group.toLowerCase().indexOf(containsLower, offset) != -1)
                {
                    // Cache les groupes "systemes"
                   if(!group.contains("Admin ") && !group.contains("Membre "))
                      results.add(new SortableSelectItem(group, group.substring(offset), group));
                }
             }
             items = new SelectItem[results.size()];
             results.toArray(items);
         
          Arrays.sort(items);
           
            // commit the transaction
            tx.commit();
         }
         catch (Throwable err)
         {
            Utils.addErrorMessage(MessageFormat.format(Application.getMessage(
                  FacesContext.getCurrentInstance(), Repository.ERROR_GENERIC), err.getMessage()), err );
            try { if (tx != null) {tx.rollback();} } catch (Exception tex) {}
           
            items = new SelectItem[0];
         }
        
         return items;
      }
     
      public SelectItem[] membresPickerCallback(int filterIndex, final String contains)
      {
            FacesContext context = FacesContext.getCurrentInstance();
           
            SelectItem[] items;
           
            UserTransaction tx = null;
            try
            {
               tx = Repository.getUserTransaction(context, true);
               tx.begin();
              
                  // build xpath to match available User/Person objects
                  NodeRef peopleRef = personService.getPeopleContainer();
                 
                  // Use lucene search to retrieve user details
                  String lucene = "@" + NamespaceService.CONTENT_MODEL_PREFIX + "\\:firstName:*" + contains + "* " +
                                  "@" + NamespaceService.CONTENT_MODEL_PREFIX + "\\:lastName:*" + contains + "* ";
                  ResultSet resultSet = searchService.query(peopleRef.getStoreRef(), SearchService.LANGUAGE_LUCENE, lucene);           
                  List<NodeRef> nodes = resultSet.getNodeRefs();           
                 
                  items = new SelectItem[nodes.size()];
                  for (int index=0; index<nodes.size(); index++)
                  {
                     NodeRef personRef = nodes.get(index);
                     String firstName = (String)this.nodeService.getProperty(personRef, ContentModel.PROP_FIRSTNAME);
                     String lastName = (String)this.nodeService.getProperty(personRef, ContentModel.PROP_LASTNAME);
                     String username = (String)this.nodeService.getProperty(personRef, ContentModel.PROP_USERNAME);
                     SelectItem item = new SortableSelectItem(username, firstName + " " + lastName + " [" + username + "]", lastName);
                     items[index] = item;
                  }
                            
               Arrays.sort(items);
              
               // commit the transaction
               tx.commit();
            }
            catch (Throwable err)
            {
               Utils.addErrorMessage(MessageFormat.format(Application.getMessage(
                     FacesContext.getCurrentInstance(), Repository.ERROR_GENERIC), err.getMessage()), err );
               try { if (tx != null) {tx.rollback();} } catch (Exception tex) {}
              
               items = new SelectItem[0];
            }
           
            return items;
      }
     
      /**
       * @return The list of available roles for the users/groups
       */
      public SelectItem[] getClientsRoles()
      {
         ResourceBundle bundle = Application.getBundle(FacesContext.getCurrentInstance());
        
         // get available roles (grouped permissions) from the permission service
         Set<String> perms = getPermissionsForType();
         SelectItem[] roles = new SelectItem[perms.size()];
         int index = 0;
         for (String permission : perms)
         {
            String displayLabel = bundle.getString(permission);
            roles[index++] = new SelectItem(permission, displayLabel);
         }
        
         return roles;
      }
     
      /**
       * Add an authority with the specified role to the list managed by this wizard.
       *
       * @param authority        Authority to add (cannot be null)
       * @param role             Role for the authorities (cannot be null)
       */
      public void addAuthorityWithRole(String authority, String role, List<UserGroupRole> userGroupList)
      {
         // only add if authority not already present in the list with same role
         boolean foundExisting = false;
         for (int n=0; n<userGroupList.size(); n++)
         {
            UserGroupRole wrapper = userGroupList.get(n);
            if (authority.equals(wrapper.getAuthority()) &&
                  (!this.allowDuplicateAuthorities || role.equals(wrapper.getRole())))
            {
               foundExisting = true;
               break;
            }
         }
        
         if (foundExisting == false)
         {
            StringBuilder label = new StringBuilder(64);
           
            // build a display label showing the user and their role for the space
            AuthorityType authType = AuthorityType.getAuthorityType(authority);
            if (authType == AuthorityType.GUEST || authType == AuthorityType.USER)
            {
               if (authType == AuthorityType.GUEST || this.personService.personExists(authority) == true)
               {
                  // found a User authority
                  label.append(buildLabelForUserAuthorityRole(authority, role));
               }
            }
            else
            {
               // found a group authority
               label.append(buildLabelForGroupAuthorityRole(authority, role));
            }
           
            userGroupList.add(new UserGroupRole(authority, role, label.toString()));
         }
      }
     
      /**
       * Helper to build a label of the form:
       *    Firstname Lastname (Role)
       */
      public String buildLabelForUserAuthorityRole(String authority, String role)
      {
         // found a User authority
         NodeRef ref = this.personService.getPerson(authority);
         String firstName = (String)this.nodeService.getProperty(ref, ContentModel.PROP_FIRSTNAME);
         String lastName = (String)this.nodeService.getProperty(ref, ContentModel.PROP_LASTNAME);
        
         StringBuilder buf = new StringBuilder(100);
         buf.append(firstName)
            .append(" ")
            .append(lastName != null ? lastName : "")
            .append(" (")
            .append(Application.getMessage(FacesContext.getCurrentInstance(), role))
            .append(")");
        
         return buf.toString();
      }
     
      /**
       * Helper to build a label for a Group authority of the form:
       *    Groupname (role)
       */
      public String buildLabelForGroupAuthorityRole(String authority, String role)
      {
         StringBuilder buf = new StringBuilder(100);
         buf.append(authority.substring(PermissionService.GROUP_PREFIX.length()))
            .append(" (")
            .append(Application.getMessage(FacesContext.getCurrentInstance(), role))
            .append(")");
        
         return buf.toString();
      }
     
      /**
       * Action handler called when the Add button is pressed to process the current selection
       */
      public void clientsAddSelection(ActionEvent event)
      {
         UIGenericPicker picker = (UIGenericPicker)event.getComponent().findComponent("picker");
         UISelectOne rolePicker = (UISelectOne)event.getComponent().findComponent("roles");
        
         String[] results = picker.getSelectedResults();
         if (results != null)
         {
            String role = (String)rolePicker.getValue();
            if (role != null)
            {
               for (int i=0; i<results.length; i++)
               {
                  addAuthorityWithRole(results[i], role, this.clientsGroupRoles);
               }
            }
         }
      }
     
      public void membresAddSelection(ActionEvent event)
      {
         UIGenericPicker picker = (UIGenericPicker) event.getComponent().findComponent("picker");
         String[] results = picker.getSelectedResults();
         if (results != null)
         {
            for (int i = 0; i < results.length; i++)
            {
               String authority = results[i];

               // check for same authority so not added twice
               boolean foundExisting = false;
               for (int n = 0; n < this.membresGroup.size(); n++)
               {
                  UserAuthorityDetails wrapper = this.membresGroup.get(n);
                  if (authority.equals(wrapper.getAuthority()))
                  {
                     foundExisting = true;
                     break;
                  }
               }

               if (foundExisting == false)
               {
                  StringBuilder label = new StringBuilder(48);

                  // build a display label showing the user person name
                  if (this.personService.personExists(authority) == true)
                  {
                     // found a Person with a User authority
                     NodeRef ref = this.personService.getPerson(authority);
                     String firstName = (String) this.nodeService.getProperty(ref, ContentModel.PROP_FIRSTNAME);
                     String lastName = (String) this.nodeService.getProperty(ref, ContentModel.PROP_LASTNAME);

                     // build a sensible label for display
                     label.append(firstName).append(' ').append(lastName);

                     // add a wrapper object with the details to the results list
                     // for display
                     UserAuthorityDetails userDetails = new UserAuthorityDetails(label.toString(), authority);
                     this.membresGroup.add(userDetails);
                  }
               }
            }
         }
      }
     
      /**
       * Action handler called when the Remove button is pressed to remove a user+role
       */
      public void clientsRemoveSelection(ActionEvent event)
      {
         UserGroupRole wrapper = (UserGroupRole)this.clientsRolesDataModel.getRowData();
         if (wrapper != null)
         {
            this.clientsGroupRoles.remove(wrapper);
         }
      }
     
      public void membresRemoveSelection(ActionEvent event)
      {
         UserAuthorityDetails wrapper = (UserAuthorityDetails) this.membresDataModel.getRowData();
         if (wrapper != null)
         {
            this.membresGroup.remove(wrapper);
         }
      }
     
      /**
       * Cache of available folder permissions
       * Modifié pour cacher les permissions : Coordinator
       * */
      Set<String> folderPermissions = null;
     
      protected Set<String> getPermissionsForType()
      {
         if (this.folderPermissions == null)
         {
            this.folderPermissions = this.permissionService.getSettablePermissions(ContentModel.TYPE_FOLDER);
           
            /* Modif Docks */
            this.folderPermissions.remove("Coordinator");
            /*
             * Bout de code utile pour lister les permissions existantes
             *
            logger.debug("Permissions possibles");
            Iterator<String> iterator = this.folderPermissions.iterator();
            while(iterator.hasNext())
            {
               logger.debug(iterator.next());
            }*/
         }
         
         return this.folderPermissions;
      }

      protected Node getNode()
      {
         return this.browseBean.getActionSpace();
      }
     
   /**
    * Code du wizard une fois qu'on clique sur Terminer (Docks)
    **/
   @Override
   protected String finishImpl(FacesContext context, String outcome) throws Exception
   {  
      // Appelle le process de creation de dossier originel
       outcome = super.finishImpl(context, outcome);
      
       NodeRef espaceProjet = this.createdNode;
       NodeRef espaceTravail = nodeService.getChildByName(this.createdNode, ContentModel.ASSOC_CONTAINS, workSpaceName);
       NodeRef espaceCollab = nodeService.getChildByName(this.createdNode, ContentModel.ASSOC_CONTAINS, collaborativeSpaceName);
      
       // Récupère le nom du projet
       logger.debug("1");
       String nomEspace = (String)nodeService.getProperty(espaceProjet, ContentModel.PROP_NAME);
      
       // Génère les noms des groupes associés
       String memberGroup = "Membre " + nomEspace;
       String adminGroup = "Admin " + nomEspace;
      
       // Vérifie l'existence du groupe ATOS (parent)
       logger.debug("2");
       if(this.authorityService.authorityExists(this.authorityService.getName(AuthorityType.GROUP, CreateProject.companyGroup)) == false)
          throw new Exception("Impossible de trouver le groupe mère : " + CreateProject.companyGroup);
      
       // Crée les groupes fils
       logger.debug("3");
       String memberGroupName = this.authorityService.getName(AuthorityType.GROUP, memberGroup);
       logger.debug("4");
       if (this.authorityService.authorityExists(memberGroupName) == false)
       {
          logger.debug("Creation du groupe " + memberGroupName);
          this.authorityService.createAuthority(AuthorityType.GROUP, PermissionService.GROUP_PREFIX + CreateProject.companyGroup, memberGroup);
       }
       else
       {
          logger.warn("Le groupe " + memberGroup + "existe deja");
       }
      
       String adminGroupName = this.authorityService.getName(AuthorityType.GROUP, adminGroup);
       if (this.authorityService.authorityExists(adminGroupName) == false)
       {
          this.authorityService.createAuthority(AuthorityType.GROUP, memberGroupName, adminGroup);
          logger.debug("Creation du groupe " + adminGroupName);
       }
       else
       {
          logger.info("Le groupe " + memberGroup + "existe deja");
       }
      
       // Positionne les droits sur l'espace projet
       List<UserGroupRole> projetGroupRoles = new ArrayList<UserGroupRole>(8);
        addAuthorityWithRole(adminGroup, "Coordinator", projetGroupRoles);
        addAuthorityWithRole(memberGroup, "Collaborator", projetGroupRoles);
        addAuthorityWithRole(CreateProject.companyGroup, "Consumer", projetGroupRoles);
           /*
            * Parcourt les clients spécifiés dans l'interface web et
            * leur donne le droit de lecture
            */
           for(int i = 0; i < this.clientsGroupRoles.size(); i++)
           {
              UserGroupRole groupRole = this.clientsGroupRoles.get(i);
                 String client = groupRole.getAuthority().substring(permissionService.GROUP_PREFIX.length());
                 addAuthorityWithRole(client, "Consumer", projetGroupRoles);
           }
       
      processSpacePermissions(projetGroupRoles, espaceProjet);
      
       // Positionne les droits sur l'espace travail
       List<UserGroupRole> workGroupRoles = new ArrayList<UserGroupRole>(8);
        addAuthorityWithRole(adminGroup, "Coordinator", workGroupRoles);
        addAuthorityWithRole(memberGroup, "Collaborator", workGroupRoles);
        addAuthorityWithRole(CreateProject.companyGroup, "Consumer", workGroupRoles);
      processSpacePermissions(workGroupRoles, espaceTravail);
      
      // Postionne les droits sur l'espace collaboratif avec les clients séléctionnés dans l'interface web
      processSpacePermissions(this.clientsGroupRoles, espaceCollab);
         
      // Place le créateur (utilisateur courant) dans le Groupe Admin Projet
      try {
          String currentUserName = properties.getAuthenticationService().getCurrentUserName();
          StringBuilder label = new StringBuilder(48);

            // build a display label showing the user person name
            if (this.personService.personExists(currentUserName) == true)
            {
               // found a Person with a User authority
               NodeRef ref = this.personService.getPerson(currentUserName);
               String firstName = (String) this.nodeService.getProperty(ref, ContentModel.PROP_FIRSTNAME);
               String lastName = (String) this.nodeService.getProperty(ref, ContentModel.PROP_LASTNAME);

               // build a sensible label for display
               label.append(firstName).append(' ').append(lastName);

               // add a wrapper object with the details to the results list
               // for display
               UserAuthorityDetails userDetails = new UserAuthorityDetails(label.toString(), currentUserName);
                            
               logger.debug("Ajout de l'user " + label + "au groupe " + adminGroup);
               this.authorityService.addAuthority(adminGroupName, userDetails.getAuthority());
            }
      }
      catch(Exception e)
      {
         logger.warn("Impossible de placer l'utilisateur courant dans le groupe " + adminGroup);
         e.printStackTrace();
      }
       
       // Ajoute les membres sélectionnés au groupe Membres Projet
      for (UserAuthorityDetails membre : membresGroup)
        {
         logger.debug("Ajout de l'user " + membre.getAuthority() + "au groupe " + memberGroup);
         this.authorityService.addAuthority(memberGroupName, membre.getAuthority());
        }

       return outcome;
   }
   
   /**
    * Positionne les permissions sur un espace
    * @param groupRoles
    * @param space
    */
   protected void processSpacePermissions(List<UserGroupRole> groupRoles, NodeRef space) {
      
      for (int i=0; i<groupRoles.size(); i++)
      {
         UserGroupRole groupRole = groupRoles.get(i);
         String authority = groupRole.getAuthority();
        
         // find the selected permission ref from it's name and apply for the specified user
         Set<String> perms = this.permissionService.getSettablePermissions(ContentModel.TYPE_FOLDER);
         for (String permission : perms)
         {
           if (groupRole.getRole().equals(permission))
            {
               this.permissionService.setPermission(
                    space,
                     authority,
                     permission,
                     true);
               logger.debug("Adding : Authority : "+authority+" Permission : "+permission+" Space: "+space.toString());
               break;
            }
         }
      }
       
   }
}

Merci !

Outcomes