View Javadoc

1   /**
2    * Copyright 2005-2006 the original author or authors.
3    *
4    * Licensed under the Gnu General Pubic License, Version 2.0 (the
5    * "License"); you may not use this file except in compliance with
6    * the License. You may obtain a copy of the License at
7    *
8    *      http://www.opensource.org/licenses/gpl-license.php
9    *
10   * This program is distributed in the hope that it will be useful,
11   * but WITHOUT ANY WARRANTY; without even the implied warranty of
12   * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
13   * See the Gnu General Public License for more details.
14   */
15  package org.figure8.join.control.action;
16  
17  import org.figure8.join.control.JoinAction;
18  import org.figure8.join.control.form.PermissionForm;
19  import org.figure8.join.core.DuplicateEntityException;
20  import org.figure8.join.businessobjects.security.User;
21  import org.figure8.join.businessobjects.security.Role;
22  import org.figure8.join.businessobjects.security.Permission;
23  import org.figure8.join.businessfacades.security.UserManager;
24  import org.figure8.join.businessfacades.security.PermissionManager;
25  import org.figure8.join.util.LogUtil;
26  
27  import org.apache.commons.logging.Log;
28  import org.apache.commons.beanutils.PropertyUtils;
29  import org.apache.struts.action.ActionForm;
30  import org.apache.struts.action.ActionForward;
31  import org.apache.struts.action.ActionMapping;
32  
33  import javax.servlet.http.HttpServletRequest;
34  import javax.servlet.http.HttpServletResponse;
35  import javax.servlet.http.HttpSession;
36  
37  import java.util.List;
38  import java.util.Iterator;
39  /**
40   * Struts action set used for creating, saving and retrieving security roles
41   * and permissions through Join application.
42   * @author <a href="mailto:laurent.broudoux@free.fr">Laurent Broudoux</a>
43   * @version $Revision: 1.1 $
44   *
45   * @struts.action path="/permission" name="permissionForm"
46   *                scope="request" parameter="op" validate="true"
47   *                input="/pages/mainpage.jsp?body=/jsp/permissions.jsp"
48   * @struts.action-forward name="Roles" path="/jsp/user/roles.jsp"
49   * @struts.action-forward name="Users" path="/action/user?op=search"
50   * @struts.action-forward name="Permissions" path="/jsp/user/permissions.jsp"
51   */
52  public class PermissionActions extends JoinAction{
53  
54     // Static -------------------------------------------------------------------
55  
56     /** Get a commons logger. */
57     private static final Log log = LogUtil.getLog(PermissionActions.class);
58  
59     /** Operation code for loading a specific security Role. */
60     public static final String LOAD_ROLE_OP = "loadRole";
61     /** Operation code for saving a security Role (create or update). */
62     public static final String SAVE_ROLE_OP = "saveRole";
63  
64     /** Operation code for loading a specific user security Permission. */
65     public static final String LOAD_PERMISSIONS_OP = "loadPermissions";
66     /** Operation code for saving security Permissions for a user. */
67     public static final String SAVE_PERMISSIONS_OP = "savePermissions";
68  
69     /**
70      * The session scope attribute under which the Role object currently
71      * selected by our logged-in User is stored.
72      */
73     public static final String ROLE_KEY = "role";
74     /**
75      * The request scope attribute under which is stored the Role that
76      * has raised a DuplicateEntityException during save of another one.
77      */
78     public static final String DUPLICATE_ROLE_KEY = "duplicate";
79  
80  
81     // Attributes ---------------------------------------------------------------
82  
83     /** Join user manager to use. */
84     private UserManager userManager = null;
85     /** Join permission manager to use. */
86     private PermissionManager permissionManager = null;
87  
88  
89     // Constructors -------------------------------------------------------------
90  
91     /** Creates a new instance of PermissionActions. */
92     public PermissionActions(){
93     }
94  
95  
96     // Public -------------------------------------------------------------------
97  
98     /** @param manager <code>UserManager</code> implementation instance */
99     public void setUserManager(UserManager manager){
100       this.userManager = manager;
101    }
102    /** @param manager <code>PermissionManager</code> implementation instance */
103    public void setPermissionManager(PermissionManager manager){
104       this.permissionManager = manager;
105    }
106 
107 
108    // Implementation of JoinAction ---------------------------------------------
109 
110    /**
111     *
112     * @param operation String representing the operation to invoke on Action
113     * @param mapping Mapping between forwards name and path for this action
114     * @param form The form object containing request parameters
115     * @param request The servlet container request wrapper
116     * @param response The servlet container response wrapper
117     * @return A forward to the next view to render and display
118     */
119    public ActionForward doExecute(String operation, ActionMapping mapping, ActionForm form, HttpServletRequest request, HttpServletResponse response)
120            throws Exception{
121       // Trace operation to execute.
122       log.debug("doExecute() called for '" + operation + "' operation");
123 
124       if (LOAD_ROLE_OP.equals(operation)){
125          return loadRole(mapping, form, request, response);
126       }
127       else if (SAVE_ROLE_OP.equals(operation)){
128          return saveRole(mapping, form, request, response);
129       }
130       else if (LOAD_PERMISSIONS_OP.equals(operation)){
131          return loadPermissions(mapping, form, request, response);
132       }
133       else if (SAVE_PERMISSIONS_OP.equals(operation)){
134          return savePermissions(mapping, form, request, response);
135       }
136       else{
137          // Default : empty roles management page.
138          request.getSession().removeAttribute(ROLE_KEY);
139          return mapping.findForward("Roles");
140       }
141    }
142 
143 
144    // Protected ----------------------------------------------------------------
145 
146    /**
147     * Load a specified role from datastore and fill form with it.
148     * @return A forward to the next view to render and display
149     */
150    protected ActionForward loadRole(ActionMapping mapping, ActionForm form, HttpServletRequest request, HttpServletResponse response)
151       throws Exception{
152 
153       if (form instanceof PermissionForm){
154          // Get the requested role from manager.
155          PermissionForm pForm = (PermissionForm)form;
156          Role role = permissionManager.getRole(pForm.getId());
157 
158          // Store release within session.
159          HttpSession session = request.getSession();
160          session.setAttribute(ROLE_KEY, role);
161          // Copy into form the role properties.
162          PropertyUtils.copyProperties(pForm, role);
163 
164          // Forward.
165          return mapping.findForward("Roles");
166       }
167       // This should not happen...
168       return null;
169    }
170 
171    /**
172     * Save a role into datastore. The Role may be an already existing one
173     * or a new one (this is indeed a create or update method).
174     * @return A forward to the next view to render and display
175     */
176    protected ActionForward saveRole(ActionMapping mapping, ActionForm form, HttpServletRequest request, HttpServletResponse response)
177       throws Exception{
178 
179       if (form instanceof PermissionForm){
180          // Get the correct form.
181          PermissionForm pForm = (PermissionForm)form;
182 
183          // Is there's a role to update in session ?
184          HttpSession session = request.getSession();
185          Role role = (Role)session.getAttribute(ROLE_KEY);
186 
187          // Create a new Role or populate existing with form.
188          if (role == null){
189             log.info("Creation of a new Role with name: " + pForm.getName());
190             role = new Role(pForm.getName(), pForm.getDescription());
191             // Add permission resource resolver if specified.
192             if (pForm.getPermissionResourceResolverClass() != null)
193                role.setPermissionResourceResolverClass(pForm.getPermissionResourceResolverClass());
194          }
195          else{
196             log.info("Update of existing Role having name: " + role.getName());
197             PropertyUtils.copyProperties(role, pForm);
198          }
199 
200          // Save role using manager.
201          try {permissionManager.saveRole(role);}
202          catch (DuplicateEntityException dee){
203             // Store exception within request.
204             request.setAttribute(DUPLICATE_ROLE_KEY, dee.getOriginalEntity());
205             return mapping.findForward("Roles");
206          }
207 
208          // Forward depending on user presence.
209          User user = (User)session.getAttribute(UserActions.USER_KEY);
210          if (user != null){
211             return loadPermissions(mapping, form, request, response);
212          }
213          
214          // Remove form and session attribute if present.
215          session.removeAttribute(ROLE_KEY);
216          removeObsoleteForm(mapping, request);
217 
218          return mapping.findForward("Roles");
219       }
220       // This should not happen...
221       return null;
222    }
223 
224    /**
225     * Load security permissions from datastore for a specified user and fill form with them.
226     * @return A forward to the next view to render and display
227     */
228    protected ActionForward loadPermissions(ActionMapping mapping, ActionForm form, HttpServletRequest request, HttpServletResponse response)
229       throws Exception{
230 
231       if (form instanceof PermissionForm){
232          // Get the correct form.
233          PermissionForm pForm = (PermissionForm)form;
234 
235          // First, look if user is in session.
236          HttpSession session = request.getSession();
237          User user = (User)session.getAttribute(UserActions.USER_KEY);
238          // If not in session, retrieve its id from form.
239          if (user == null){
240             user = userManager.getUser(pForm.getUserId());
241             session.setAttribute(UserActions.USER_KEY, user);
242          }
243 
244          // Retrieve user's permissions and fill form.
245          List permissions = permissionManager.getUserPermissions(user);
246          for (int i=0; i < permissions.size(); i++)
247             pForm.addPermission((Permission)permissions.get(i));
248 
249          // Forward.
250          return mapping.findForward("Permissions");
251       }
252       // This should not happen...
253       return null;
254    }
255 
256    /**
257     * Save security permissions for a specified user. This consists in removing all
258     * its already existing permissions and creating new ones according to form data.
259     * @return A forward to the next view to render and display
260     */
261    protected ActionForward savePermissions(ActionMapping mapping, ActionForm form, HttpServletRequest request, HttpServletResponse response)
262       throws Exception{
263 
264       if (form instanceof PermissionForm){
265          // Get the correct form.
266          PermissionForm pForm = (PermissionForm)form;
267 
268          // First, look if user is in session.
269          HttpSession session = request.getSession();
270          User user = (User)session.getAttribute(UserActions.USER_KEY);
271          // If not in session, forward to error page.
272          if (user == null)
273             return mapping.findForward("NoUserInSession");
274 
275          // Remove all user's permissions.
276          permissionManager.removeAllUserPermissions(user);
277 
278          // Browse permissions assigned to user and create them.
279          Iterator roles = pForm.getRoles().keySet().iterator();
280          while (roles.hasNext()){
281             // Get corresponding role domain object.
282             String roleStr = (String)roles.next();
283             Role role = permissionManager.getRole(roleStr);
284 
285             if (role != null){
286                if ("on".equals(pForm.getMappedRole(roleStr))){
287                   // Create a permission for raw role.
288                   Permission rolePermission = new Permission(role, user.getLogin());
289                   permissionManager.savePermission(rolePermission);
290 
291                   // Create permissions for each assigned resource.
292                   String[] perms = pForm.getMappedResourcesAsStrings(roleStr);
293                   if (perms != null && perms.length > 0){
294                      for (int i=0; i<perms.length; i++){
295                         String resourceId = (String)perms[i];
296                         Permission resPermission = new Permission(role, user.getLogin(), resourceId);
297                         permissionManager.savePermission(resPermission);
298                      }
299                   }
300                }
301             }
302          }
303 
304          // Remove form if present.
305          removeObsoleteForm(mapping, request);
306 
307          // Forward to page displaying users.
308          return mapping.findForward("Users");
309       }
310       // This should not happen...
311       return null;
312    }
313 }