KickJava   Java API By Example, From Geeks To Geeks.

Java > Open Source Codes > com > sslexplorer > security > actions > ShowRoleDispatchAction


1 /*
2  * SSL-Explorer
3  *
4  * Copyright (C) 2003-2006 3SP LTD. All Rights Reserved
5  *
6  * This program is free software; you can redistribute it and/or
7  * modify it under the terms of the GNU General Public License
8  * as published by the Free Software Foundation; either version 2 of
9  * the License, or (at your option) any later version.
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. See the
13  * GNU General Public License for more details.
14  *
15  * You should have received a copy of the GNU General Public
16  * License along with this program; if not, write to the Free Software
17  * Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA.
18  */

19             
20 package com.sslexplorer.security.actions;
21
22 import java.util.ArrayList JavaDoc;
23 import java.util.Arrays JavaDoc;
24 import java.util.Collection JavaDoc;
25 import java.util.Iterator JavaDoc;
26 import java.util.List JavaDoc;
27 import java.util.TreeSet JavaDoc;
28
29 import javax.servlet.http.HttpServletRequest JavaDoc;
30 import javax.servlet.http.HttpServletResponse JavaDoc;
31
32 import org.apache.struts.action.ActionForm;
33 import org.apache.struts.action.ActionForward;
34 import org.apache.struts.action.ActionMapping;
35
36 import com.sslexplorer.core.CoreAttributeConstants;
37 import com.sslexplorer.core.CoreEvent;
38 import com.sslexplorer.core.CoreEventConstants;
39 import com.sslexplorer.core.CoreServlet;
40 import com.sslexplorer.core.CoreUtil;
41 import com.sslexplorer.core.UserDatabaseManager;
42 import com.sslexplorer.core.actions.AuthenticatedDispatchAction;
43 import com.sslexplorer.policyframework.Permission;
44 import com.sslexplorer.policyframework.PolicyConstants;
45 import com.sslexplorer.policyframework.PolicyUtil;
46 import com.sslexplorer.realms.Realm;
47 import com.sslexplorer.security.Constants;
48 import com.sslexplorer.security.GroupsRequiredForUserException;
49 import com.sslexplorer.security.LogonControllerFactory;
50 import com.sslexplorer.security.Role;
51 import com.sslexplorer.security.SessionInfo;
52 import com.sslexplorer.security.User;
53 import com.sslexplorer.security.UserDatabase;
54 import com.sslexplorer.security.forms.RoleForm;
55
56 /**
57  * Implementation of an {@link AuthenticatedDispatchAction} that allows an
58  * administrator to create or edit a <i>Group</i> (previously known as a
59  * <i>Role</i>).
60  *
61  * @author Brett Smith <a HREF="mailto: brett@3sp.com">&lt;brett@3sp.com&gt;</a>
62  */

63 public class ShowRoleDispatchAction extends AuthenticatedDispatchAction {
64
65     /**
66      * Constructor.
67      */

68     public ShowRoleDispatchAction() {
69         super(PolicyConstants.ACCOUNTS_AND_GROUPS_RESOURCE_TYPE, new Permission[] { PolicyConstants.PERM_CREATE_EDIT_AND_ASSIGN });
70     }
71
72     /*
73      * (non-Javadoc)
74      *
75      * @see org.apache.struts.actions.DispatchAction#unspecified(org.apache.struts.action.ActionMapping,
76      * org.apache.struts.action.ActionForm,
77      * javax.servlet.http.HttpServletRequest,
78      * javax.servlet.http.HttpServletResponse)
79      */

80     public ActionForward unspecified(ActionMapping mapping, ActionForm form, HttpServletRequest JavaDoc request,
81                                      HttpServletResponse JavaDoc response) throws Exception JavaDoc {
82         return mapping.findForward("display");
83     }
84
85     /**
86      * Create a new role.
87      *
88      * @param mapping mapping
89      * @param form form
90      * @param request request
91      * @param response response
92      * @return forward
93      * @throws Exception on any error
94      */

95     public ActionForward create(ActionMapping mapping, ActionForm form, HttpServletRequest JavaDoc request, HttpServletResponse JavaDoc response)
96                     throws Exception JavaDoc {
97         UserDatabase udb = UserDatabaseManager.getInstance().getUserDatabase(getSessionInfo(request).getUser().getRealm());
98         if (!udb.supportsAccountCreation()) {
99             throw new Exception JavaDoc("The underlying user database does not support role creation.");
100         }
101         PolicyUtil.checkPermission(PolicyConstants.ACCOUNTS_AND_GROUPS_RESOURCE_TYPE, PolicyConstants.PERM_CREATE_EDIT_AND_ASSIGN, request);
102         ((RoleForm) form).initialize(new ArrayList JavaDoc());
103         ((RoleForm) form).setReferer(CoreUtil.getReferer(request));
104         CoreUtil.addRequiredFieldMessage(this, request);
105         return mapping.findForward("display");
106     }
107
108     /**
109      * Edit an existing role. The role to edit must be placed in the request
110      * attribute
111      *
112      * @param mapping mapping
113      * @param form form
114      * @param request request
115      * @param response response
116      * @return forward
117      * @throws Exception on any error
118      */

119     public ActionForward edit(ActionMapping mapping, ActionForm form, HttpServletRequest JavaDoc request, HttpServletResponse JavaDoc response)
120                     throws Exception JavaDoc {
121         PolicyUtil.checkPermission(PolicyConstants.ACCOUNTS_AND_GROUPS_RESOURCE_TYPE, PolicyConstants.PERM_CREATE_EDIT_AND_ASSIGN, request);
122         Role r = (Role) request.getAttribute(Constants.EDITING_ITEM);
123         if (r == null) {
124             throw new Exception JavaDoc("No role configured for editing.");
125         }
126         UserDatabase udb = UserDatabaseManager.getInstance().getUserDatabase(getSessionInfo(request).getUser().getRealm());
127         ((RoleForm) form).initialize(Arrays.asList(udb.getUsersInRole(r)));
128         ((RoleForm) form).setRolename(r.getPrincipalName());
129         ((RoleForm) form).setReferer(CoreUtil.getReferer(request));
130         ((RoleForm) form).setEditing();
131         CoreUtil.addRequiredFieldMessage(this, request);
132         return mapping.findForward("display");
133     }
134
135     /**
136      * Save the new role or update the existing one depending on whether the
137      * role is being edited or created.
138      *
139      * @param mapping mappng
140      * @param form form
141      * @param request request
142      * @param response response
143      * @return forward forward
144      * @throws Exception on any error
145      */

146     public ActionForward commit(ActionMapping mapping, ActionForm form, HttpServletRequest JavaDoc request, HttpServletResponse JavaDoc response)
147                     throws Exception JavaDoc {
148         PolicyUtil.checkPermission(PolicyConstants.ACCOUNTS_AND_GROUPS_RESOURCE_TYPE, PolicyConstants.PERM_CREATE_EDIT_AND_ASSIGN, request);
149         RoleForm roleForm = (RoleForm) form;
150         UserDatabase udb = UserDatabaseManager.getInstance().getUserDatabase(getSessionInfo(request).getUser().getRealm());
151         if (roleForm.getEditing()) {
152             try {
153                 Role r = udb.getRole(
154                                 roleForm.getRolename());
155                 List JavaDoc selectedUsers = roleForm.getUserList();
156                 String JavaDoc[] usersNotRemoved = updateUserRoles(r, selectedUsers, udb.getRealm());
157                 CoreEvent coreEvent = new CoreEvent(this, CoreEventConstants.GROUP_UPDATED, r, getSessionInfo(request)).addAttribute(
158                         CoreAttributeConstants.EVENT_ATTR_PRINCIPAL_ID, r.getPrincipalName());
159                 
160                 int j = 0;
161                 if(!selectedUsers.isEmpty()) {
162                     for(Iterator JavaDoc i = selectedUsers.iterator(); i.hasNext(); ) {
163                         j++;
164                         coreEvent.addAttribute(CoreAttributeConstants.EVENT_ATTR_ACCOUNT + Integer.toString(j),(String JavaDoc)i.next());
165                     }
166                 }
167                 CoreServlet.getServlet().fireCoreEvent(coreEvent);
168                 saveMessage(request, "availableRoles.roleCreated", roleForm.getRolename());
169                 
170                 if (usersNotRemoved.length != 0) {
171                     saveError(request, "availableRoles.error.groupsRequired", formatString(usersNotRemoved));
172                 }
173             } catch (Exception JavaDoc ex) {
174                 CoreServlet.getServlet().fireCoreEvent(
175                     new CoreEvent(this, CoreEventConstants.GROUP_UPDATED, null, getSessionInfo(request), ex)
176                                     .addAttribute(CoreAttributeConstants.EVENT_ATTR_PRINCIPAL_ID, roleForm.getRolename()));
177                 throw ex;
178             }
179
180         } else {
181             try {
182                 Role r = udb.createRole(roleForm.getRolename());
183                 List JavaDoc selectedUsers = roleForm.getUserList();
184                 updateUserRoles(r, selectedUsers, udb.getRealm());
185
186                 CoreEvent coreEvent = new CoreEvent(this, CoreEventConstants.GROUP_CREATED, r, getSessionInfo(request)).addAttribute(
187                         CoreAttributeConstants.EVENT_ATTR_PRINCIPAL_ID, r.getPrincipalName());
188                 
189                 int j = 0;
190                 if(!selectedUsers.isEmpty()) {
191                     for(Iterator JavaDoc i = selectedUsers.iterator(); i.hasNext(); ) {
192                         j++;
193                         coreEvent.addAttribute(CoreAttributeConstants.EVENT_ATTR_ACCOUNT + Integer.toString(j),(String JavaDoc)i.next());
194                     }
195                 }
196                 CoreServlet.getServlet().fireCoreEvent(coreEvent);
197                 saveMessage(request, "availableRoles.roleCreated", roleForm.getRolename());
198             } catch (Exception JavaDoc ex) {
199                 CoreServlet.getServlet().fireCoreEvent(
200                     new CoreEvent(this, CoreEventConstants.GROUP_CREATED, null, getSessionInfo(request), ex)
201                                     .addAttribute(CoreAttributeConstants.EVENT_ATTR_PRINCIPAL_ID, roleForm.getRolename()));
202                 throw ex;
203             }
204         }
205         // we need to reset the menu items as they could have changed here.
206
LogonControllerFactory.getInstance().applyMenuItemChanges(request);
207         return cancel(mapping, form, request, response);
208     }
209     
210     private static String JavaDoc formatString(String JavaDoc[] values) {
211         if(values.length == 0) {
212             return "";
213         }
214         
215         StringBuffer JavaDoc buffer = new StringBuffer JavaDoc();
216         for (String JavaDoc value : values) {
217             buffer.append(value).append(", ");
218         }
219         return buffer.substring(0, buffer.length() - 2);
220     }
221     
222     private String JavaDoc[] updateUserRoles(Role r, List JavaDoc selectedUsers, Realm realm) throws Exception JavaDoc {
223
224         /*
225          * TODO
226          *
227          * This could be a lot more efficient. The user database currently
228          * provides no way of setting roles for users, so we have to jump
229          * through hoops by iterating over all users and user updateAccount()
230          */

231         
232         UserDatabase udb = UserDatabaseManager.getInstance().getUserDatabase(realm);
233         User[] u = udb.listAllUsers("*");
234         Collection JavaDoc<String JavaDoc> usersNotRemoved = new TreeSet JavaDoc<String JavaDoc>();
235         for (int i = 0; i < u.length; i++) {
236             Role[] roles = u[i].getRoles();
237             
238             // Get if the current has the role we are editing
239

240             int found = -1;
241             for (int j = 0; j < roles.length && found == -1; j++) {
242                 if (roles[j].getPrincipalName().equals(r.getPrincipalName())) {
243                     found = j;
244                 }
245             }
246             
247             //
248
if(found != -1) {
249                 if (selectedUsers.contains(u[i].getPrincipalName())) {
250                     // Selected so leave alone
251
} else {
252                     // Not selected, remove from role
253
Role[] r2 = new Role[roles.length - 1];
254                     System.arraycopy(roles, 0, r2, 0, found);
255                     System.arraycopy(roles, found + 1, r2, found, r2.length - found);
256                     try {
257                         udb.updateAccount(u[i], u[i].getEmail(), u[i].getFullname(), r2);
258                     } catch (GroupsRequiredForUserException e) {
259                         usersNotRemoved.add(u[i].getPrincipalName());
260                     }
261                 }
262             }
263             else {
264                 // User is not currently in role
265
if (selectedUsers.contains(u[i].getPrincipalName())) {
266                     // Selected so add
267
Role[] r2 = new Role[roles.length + 1];
268                     System.arraycopy(roles, 0, r2, 0, roles.length);
269                     r2[roles.length] = r;
270                     udb.updateAccount(u[i], u[i].getEmail(), u[i].getFullname(), r2);
271                 }
272                 
273             }
274         }
275         return usersNotRemoved.toArray(new String JavaDoc[usersNotRemoved.size()]);
276     }
277
278     /*
279      * (non-Javadoc)
280      *
281      * @see com.sslexplorer.core.actions.CoreAction#getNavigationContext(org.apache.struts.action.ActionMapping,
282      * org.apache.struts.action.ActionForm,
283      * javax.servlet.http.HttpServletRequest,
284      * javax.servlet.http.HttpServletResponse)
285      */

286     public int getNavigationContext(ActionMapping mapping, ActionForm form, HttpServletRequest JavaDoc request, HttpServletResponse JavaDoc response) {
287         return SessionInfo.MANAGEMENT_CONSOLE_CONTEXT;
288     }
289 }
Popular Tags