KickJava   Java API By Example, From Geeks To Geeks.

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


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.Iterator JavaDoc;
23 import java.util.Map JavaDoc;
24
25 import javax.servlet.http.HttpServletRequest JavaDoc;
26 import javax.servlet.http.HttpServletResponse JavaDoc;
27
28 import org.apache.struts.Globals;
29 import org.apache.struts.action.ActionForm;
30 import org.apache.struts.action.ActionForward;
31 import org.apache.struts.action.ActionMapping;
32 import org.apache.struts.action.ActionMessage;
33 import org.apache.struts.action.ActionMessages;
34
35 import com.sslexplorer.boot.PropertyList;
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.RedirectWithMessages;
42 import com.sslexplorer.core.UserDatabaseManager;
43 import com.sslexplorer.core.actions.AuthenticatedDispatchAction;
44 import com.sslexplorer.policyframework.Permission;
45 import com.sslexplorer.policyframework.PolicyConstants;
46 import com.sslexplorer.policyframework.PolicyUtil;
47 import com.sslexplorer.properties.Property;
48 import com.sslexplorer.properties.attributes.AttributeDefinition;
49 import com.sslexplorer.properties.attributes.AttributeValueItem;
50 import com.sslexplorer.properties.impl.userattributes.UserAttributeKey;
51 import com.sslexplorer.security.Constants;
52 import com.sslexplorer.security.GroupsRequiredForUserException;
53 import com.sslexplorer.security.LogonControllerFactory;
54 import com.sslexplorer.security.Role;
55 import com.sslexplorer.security.SessionInfo;
56 import com.sslexplorer.security.User;
57 import com.sslexplorer.security.UserDatabase;
58 import com.sslexplorer.security.UserDatabaseException;
59 import com.sslexplorer.security.forms.UserAccountForm;
60
61
62 /**
63  * Implementation of {@link com.sslexplorer.core.actions.AuthenticatedDispatchAction}
64  * that allows an administrator to create or edit a user account.
65  * <p>
66  * If the current <i>User Database</i> does not support account creation then
67  * editing of the basic details is not allowed. The generic details such as
68  * 'enabled' and the user attributes may be changed.
69  *
70  * @author Brett Smith <a HREF="mailto: brett@3sp.com">&lt;brett@3sp.com&gt;</a>
71  */

72 public class ShowAccountAction extends AuthenticatedDispatchAction {
73     /**
74      * Constructor.
75      */

76     public ShowAccountAction() {
77         super(PolicyConstants.ACCOUNTS_AND_GROUPS_RESOURCE_TYPE, new Permission[] {
78                         PolicyConstants.PERM_CREATE_EDIT_AND_ASSIGN,
79                         PolicyConstants.PERM_DELETE
80         });
81     }
82
83     /* (non-Javadoc)
84      * @see org.apache.struts.actions.DispatchAction#unspecified(org.apache.struts.action.ActionMapping, org.apache.struts.action.ActionForm, javax.servlet.http.HttpServletRequest, javax.servlet.http.HttpServletResponse)
85      */

86     public ActionForward unspecified(ActionMapping mapping, ActionForm form, HttpServletRequest JavaDoc request,
87                     HttpServletResponse JavaDoc response) throws Exception JavaDoc {
88         request.getSession().removeAttribute(Constants.EDITING_ITEM);
89         return mapping.findForward("display");
90     }
91
92
93     /**
94      * Set the password.
95      *
96      * @param mapping mapping
97      * @param form form
98      * @param request request
99      * @param response response
100      * @return forward
101      * @throws Exception on any error
102      */

103     public ActionForward setPassword(ActionMapping mapping, ActionForm form,
104             HttpServletRequest JavaDoc request, HttpServletResponse JavaDoc response)
105             throws Exception JavaDoc {
106         UserDatabase udb = UserDatabaseManager.getInstance().getUserDatabase(getSessionInfo(request).getUser().getRealm());
107         User user = udb.getAccount(((UserAccountForm) form).getUsername());
108         request.getSession().setAttribute("setPassword.user", user);
109         return mapping.findForward("setPassword");
110     }
111     
112     /**
113      * Create a new account.
114      *
115      * @param mapping mapping
116      * @param form form
117      * @param request request
118      * @param response response
119      * @return forward
120      * @throws Exception on any error
121      */

122     public ActionForward create(ActionMapping mapping, ActionForm form, HttpServletRequest JavaDoc request, HttpServletResponse JavaDoc response)
123                     throws Exception JavaDoc {
124         PolicyUtil.checkPermission(PolicyConstants.ACCOUNTS_AND_GROUPS_RESOURCE_TYPE, PolicyConstants.PERM_CREATE_EDIT_AND_ASSIGN, request);
125         ((UserAccountForm) form).initialize(null, false, request);
126         ((UserAccountForm) form).setReferer(CoreUtil.getReferer(request));
127         CoreUtil.addRequiredFieldMessage(this, request);
128         return mapping.findForward("refresh");
129     }
130
131     /**
132      * Edit an existing account.
133      *
134      * @param mapping mapping
135      * @param form form
136      * @param request request
137      * @param response response
138      * @return forward
139      * @throws Exception on any error
140      */

141     public ActionForward edit(ActionMapping mapping, ActionForm form, HttpServletRequest JavaDoc request, HttpServletResponse JavaDoc response)
142                     throws Exception JavaDoc {
143         PolicyUtil.checkPermission(PolicyConstants.ACCOUNTS_AND_GROUPS_RESOURCE_TYPE, PolicyConstants.PERM_CREATE_EDIT_AND_ASSIGN, request);
144         String JavaDoc username = request.getParameter("username");
145         UserDatabase udb = UserDatabaseManager.getInstance().getUserDatabase(getSessionInfo(request).getUser().getRealm());
146         User user = udb.getAccount(username);
147         ((UserAccountForm) form).initialize(user, true, request);
148         ((UserAccountForm) form).setReferer(CoreUtil.getReferer(request));
149         return mapping.findForward("display");
150     }
151     
152     /**
153      * @param mapping
154      * @param form
155      * @param request
156      * @param response
157      * @return ActionForward
158      * @throws Exception
159      */

160     public ActionForward refresh(ActionMapping mapping, ActionForm form, HttpServletRequest JavaDoc request, HttpServletResponse JavaDoc response)
161     throws Exception JavaDoc {
162         CoreUtil.addRequiredFieldMessage(this, request);
163         return mapping.findForward("display");
164     }
165
166     /**
167      * Commit the details to the user database.
168      *
169      * @param mapping mapping
170      * @param form form
171      * @param request request
172      * @param response response
173      * @return forward
174      * @throws Exception on any error
175      */

176     public ActionForward commit(ActionMapping mapping, ActionForm form, HttpServletRequest JavaDoc request, HttpServletResponse JavaDoc response)
177                     throws Exception JavaDoc {
178         UserAccountForm account = (UserAccountForm) form;
179         PolicyUtil.checkPermission(PolicyConstants.ACCOUNTS_AND_GROUPS_RESOURCE_TYPE, PolicyConstants.PERM_CREATE_EDIT_AND_ASSIGN, request);
180         SessionInfo info = this.getSessionInfo(request);
181         UserDatabase udb = UserDatabaseManager.getInstance().getUserDatabase(getSessionInfo(request).getUser().getRealm());
182         User user = null;
183         if(udb.supportsAccountCreation()) {
184             PropertyList roleList = account.getRolesList();
185             int idx = 0;
186             Role[] roles = new Role[roleList.size()];
187             for(Iterator JavaDoc i = roleList.iterator(); i.hasNext(); ) {
188                 roles[idx++] = udb.getRole((String JavaDoc)i.next());
189             }
190
191             if (account.getEditing()) {
192                 user = udb.getAccount(account.getUsername());
193                 try {
194                     udb.updateAccount(user, account.getEmail(), account.getFullname(), roles);
195                     CoreEvent coreEvent = new CoreEvent(this, CoreEventConstants.USER_EDITED, user, info)
196                         .addAttribute(CoreAttributeConstants.EVENT_ATTR_PRINCIPAL_ID, user.getPrincipalName())
197                         .addAttribute(CoreAttributeConstants.EVENT_ATTR_FULL_NAME, user.getFullname())
198                         .addAttribute(CoreAttributeConstants.EVENT_ATTR_ACCOUNT_EMAIL, user.getEmail());
199
200                     if(roles.length != 0) {
201                         for(int i = 0; i < roles.length; i++ ) {
202                             coreEvent.addAttribute(CoreAttributeConstants.EVENT_ATTR_GROUP + Integer.toString(i+1), roles[i].getPrincipalName());
203                         }
204                     }
205                     CoreServlet.getServlet().fireCoreEvent(coreEvent);
206                 } catch (GroupsRequiredForUserException e) {
207                     saveError(request, "createAccount.error.groupsRequired");
208                     return mapping.findForward("display");
209                 } catch (UserDatabaseException e) {
210                     if(UserDatabaseException.INTERNAL_ERROR == e.getCode()) {
211                         handleException(CoreEventConstants.USER_CREATED, account, info, roles, e);
212                         throw e;
213                     } else {
214                         saveError(request, e.getBundleActionMessage());
215                         return mapping.findForward("display");
216                     }
217                 } catch (Exception JavaDoc e) {
218                     handleException(CoreEventConstants.USER_EDITED, account, info, roles, e);
219                     throw e;
220                 }
221             } else {
222                 try {
223                     user = udb.createAccount(account.getUsername(), String.valueOf((int) (Math.random() * 100000)),
224                     // Set a random password
225
account.getEmail(), account.getFullname(), roles);
226                     CoreEvent coreEvent = new CoreEvent(this, CoreEventConstants.USER_CREATED, null, info, CoreEvent.STATE_SUCCESSFUL)
227                     .addAttribute(CoreAttributeConstants.EVENT_ATTR_PRINCIPAL_ID, account.getUsername())
228                     .addAttribute(CoreAttributeConstants.EVENT_ATTR_FULL_NAME, account.getFullname())
229                     .addAttribute(CoreAttributeConstants.EVENT_ATTR_ACCOUNT_EMAIL, account.getEmail());
230
231                     if(roles.length != 0) {
232                         for(int i = 0; i < roles.length; i++ ) {
233                             coreEvent.addAttribute(CoreAttributeConstants.EVENT_ATTR_GROUP + Integer.toString(i+1), roles[i].getPrincipalName());
234                         }
235                     }
236                     CoreServlet.getServlet().fireCoreEvent(coreEvent);
237                 } catch (GroupsRequiredForUserException e) {
238                     saveError(request, "createAccount.error.groupsRequired");
239                     return mapping.findForward("display");
240                 } catch (UserDatabaseException e) {
241                     if(UserDatabaseException.INTERNAL_ERROR == e.getCode()) {
242                         handleException(CoreEventConstants.USER_CREATED, account, info, roles, e);
243                         throw e;
244                     } else {
245                         saveError(request, e.getBundleActionMessage());
246                         return mapping.findForward("display");
247                     }
248                 } catch (Exception JavaDoc e) {
249                     handleException(CoreEventConstants.USER_CREATED, account, info, roles, e);
250                     throw e;
251                 }
252             }
253         }
254         else {
255             user = udb.getAccount(account.getUsername());
256         }
257
258         // Update the attributes
259
for(Iterator JavaDoc i = account.getAttributeValueItems().iterator(); i.hasNext(); ) {
260            AttributeValueItem v = (AttributeValueItem)i.next();
261            if(v.getDefinition().getVisibility() != AttributeDefinition.USER_CONFIDENTIAL_ATTRIBUTE) {
262                Property.setProperty(new UserAttributeKey(user, v.getDefinition().getName()), v.getDefinition().formatAttributeValue(v.getValue()), info);
263            }
264         }
265         // XXX HACK to ensure user attributes in memory are the same as persisted
266
for(Iterator JavaDoc j = LogonControllerFactory.getInstance().getActiveSessions().entrySet().iterator(); j.hasNext(); ) {
267             Map.Entry JavaDoc e = (Map.Entry JavaDoc)j.next();
268             SessionInfo sinfo = (SessionInfo)e.getValue();
269             if(sinfo.getUser().getPrincipalName().equals(user.getPrincipalName())) {
270                 sinfo.setUser(user);
271             }
272         }
273
274         // Reset the enabled state if it is different
275
if (PolicyUtil.isEnabled(user) != account.isEnabled()) {
276             PolicyUtil.setEnabled(user, account.isEnabled(), null, null);
277         }
278
279         // we need to reset the menu items as they could have changed here.
280
LogonControllerFactory.getInstance().applyMenuItemChanges(request);
281
282         // Go to the set password page if this is a new account and set password was selected
283
if (udb.supportsPasswordChange() && (account.isSetPassword() || !account.getEditing())) {
284             request.getSession().setAttribute("setPassword.user", user);
285             ActionMessages msgs = new ActionMessages();
286             msgs.add(Globals.MESSAGE_KEY, new ActionMessage("createAccount.message.accountSaved"));
287             saveMessages(request, msgs);
288             return mapping.findForward("setPassword");
289         } else {
290             return new RedirectWithMessages(mapping.findForward("success"), request);
291         }
292     }
293
294     private void handleException(int eventId, UserAccountForm account, SessionInfo info, Role[] roles, Exception JavaDoc e) {
295         CoreEvent coreEvent = new CoreEvent(this, eventId, null, info, e)
296             .addAttribute(CoreAttributeConstants.EVENT_ATTR_PRINCIPAL_ID, account.getUsername())
297             .addAttribute(CoreAttributeConstants.EVENT_ATTR_FULL_NAME, account.getFullname())
298             .addAttribute(CoreAttributeConstants.EVENT_ATTR_ACCOUNT_EMAIL, account.getEmail());
299
300         if(roles.length != 0) {
301             for(int i = 0; i < roles.length; i++ ) {
302                 coreEvent.addAttribute(CoreAttributeConstants.EVENT_ATTR_GROUP + Integer.toString(i+1), roles[i].getPrincipalName());
303             }
304         }
305         CoreServlet.getServlet().fireCoreEvent(coreEvent);
306     }
307
308     /**
309      * @param mapping
310      * @param form
311      * @param request
312      * @param response
313      * @return ActionForward
314      * @throws Exception
315      */

316     public ActionForward cancel(ActionMapping mapping, ActionForm form, HttpServletRequest JavaDoc request, HttpServletResponse JavaDoc response)
317                     throws Exception JavaDoc {
318         return new RedirectWithMessages(mapping.findForward("cancel"), request);
319     }
320     
321     /* (non-Javadoc)
322      * @see com.sslexplorer.core.actions.CoreAction#getNavigationContext(org.apache.struts.action.ActionMapping, org.apache.struts.action.ActionForm, javax.servlet.http.HttpServletRequest, javax.servlet.http.HttpServletResponse)
323      */

324     public int getNavigationContext(ActionMapping mapping, ActionForm form, HttpServletRequest JavaDoc request, HttpServletResponse JavaDoc response) {
325         return SessionInfo.MANAGEMENT_CONSOLE_CONTEXT;
326     }
327
328     /**
329      * Reset all user attributes.
330      *
331      * @param mapping
332      * @param form
333      * @param request
334      * @param response
335      * @return forward
336      * @throws Exception
337      */

338     public ActionForward resetUserAttributes(ActionMapping mapping, ActionForm form, HttpServletRequest JavaDoc request, HttpServletResponse JavaDoc response)
339                     throws Exception JavaDoc {
340         UserAccountForm account = (UserAccountForm) form;
341         PolicyUtil.checkPermission(PolicyConstants.ACCOUNTS_AND_GROUPS_RESOURCE_TYPE, PolicyConstants.PERM_CREATE_EDIT_AND_ASSIGN, request);
342         for(Iterator JavaDoc i = account.getAttributeValueItems().iterator(); i.hasNext(); ) {
343             AttributeValueItem v = (AttributeValueItem)i.next();
344             v.setValue(v.getDefinition().parseValue(v.getDefinition().getDefaultValue()));
345         }
346         return mapping.findForward("display");
347     }
348 }
Popular Tags