KickJava   Java API By Example, From Geeks To Geeks.

Java > Open Source Codes > com > sslexplorer > security > forms > UserAccountForm


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.forms;
21
22 import java.util.ArrayList JavaDoc;
23 import java.util.Collections JavaDoc;
24 import java.util.Iterator JavaDoc;
25 import java.util.List JavaDoc;
26
27 import javax.servlet.http.HttpServletRequest JavaDoc;
28
29 import org.apache.commons.logging.Log;
30 import org.apache.commons.logging.LogFactory;
31 import org.apache.struts.Globals;
32 import org.apache.struts.action.ActionErrors;
33 import org.apache.struts.action.ActionMapping;
34 import org.apache.struts.action.ActionMessage;
35 import org.apache.struts.util.MessageResources;
36
37 import com.sslexplorer.boot.CodedException;
38 import com.sslexplorer.boot.ContextHolder;
39 import com.sslexplorer.boot.PropertyClass;
40 import com.sslexplorer.boot.PropertyClassManager;
41 import com.sslexplorer.boot.PropertyDefinition;
42 import com.sslexplorer.boot.PropertyList;
43 import com.sslexplorer.core.CoreException;
44 import com.sslexplorer.core.CoreUtil;
45 import com.sslexplorer.core.UserDatabaseManager;
46 import com.sslexplorer.core.forms.CoreForm;
47 import com.sslexplorer.policyframework.PolicyUtil;
48 import com.sslexplorer.properties.Property;
49 import com.sslexplorer.properties.attributes.AttributeDefinition;
50 import com.sslexplorer.properties.attributes.AttributeValueItem;
51 import com.sslexplorer.properties.impl.userattributes.UserAttributeKey;
52 import com.sslexplorer.properties.impl.userattributes.UserAttributes;
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.tabs.TabModel;
59
60 /**
61  * Implementation of a tabbed {@link com.sslexplorer.core.forms.CoreForm} that
62  * allows an administrator to edit account details.
63  * <p>
64  * The amount of editable details will depend on whether the underlying user
65  * database supports account creation / editing.
66  * <p>
67  * Editing of user attributes and the enabled flag will always be available, the
68  * rest such as name, fullname, email etc will only be available when an
69  * appropriate user database is used.
70  *
71  * @author Brett Smith <a HREF="mailto: brett@3sp.com">&lt;brett@3sp.com&gt;</a>
72  */

73 public class UserAccountForm extends CoreForm implements TabModel {
74     static Log log = LogFactory.getLog(UserAccountForm.class);
75
76     // Private instance variables
77

78     private String JavaDoc username;
79     private String JavaDoc email;
80     private String JavaDoc fullname;
81     private boolean setPassword;
82     private boolean enabled;
83     private PropertyList roles;
84     private List JavaDoc userAttributeValueItems;
85     private String JavaDoc selectedTab = "details";
86     private List JavaDoc categoryIds;
87     private List JavaDoc categoryTitles;
88     private PropertyClass propertyClass;
89     private String JavaDoc realmName;
90     
91     public UserAccountForm() {
92         propertyClass = PropertyClassManager.getInstance().getPropertyClass(UserAttributes.NAME);
93     }
94     
95     /**
96      * @return String
97      */

98     public String JavaDoc getRealmName() {
99         return realmName;
100     }
101
102     /**
103      * @param realmName
104      */

105     public void setRealmName(String JavaDoc realmName) {
106         this.realmName = realmName;
107     }
108
109     /**
110      * Get the username
111      *
112      * @return username
113      */

114     public String JavaDoc getUsername() {
115         return username;
116     }
117
118     /**
119      * Set the username
120      *
121      * @param username username
122      */

123     public void setUsername(String JavaDoc username) {
124         this.username = username.trim();
125     }
126
127     /**
128      * Get the full name
129      *
130      * @return full name
131      */

132     public String JavaDoc getFullname() {
133         return fullname;
134     }
135
136     /**
137      * Set the full name
138      *
139      * @param fullname full name
140      */

141     public void setFullname(String JavaDoc fullname) {
142         this.fullname = fullname.trim();
143     }
144
145     /**
146      * Get whether this account should be enabled or not.
147      *
148      * @return enabled
149      */

150     public boolean isEnabled() {
151         return enabled;
152     }
153
154     /**
155      * Set whether this account should be enabled or not.
156      *
157      * @param enabled
158      */

159     public void setEnabled(boolean enabled) {
160         this.enabled = enabled;
161     }
162
163     /**
164      * Get the email address
165      *
166      * @return email address
167      */

168     public String JavaDoc getEmail() {
169         return email;
170     }
171
172     /**
173      * Set the email address
174      *
175      * @param email email address
176      */

177     public void setEmail(String JavaDoc email) {
178         this.email = email.trim();
179     }
180
181     /**
182      * Set whether the password should be set when this form is commited.
183      *
184      * @param setPassword set password when commited
185      */

186     public void setSetPassword(boolean setPassword) {
187         this.setPassword = setPassword;
188     }
189
190     /**
191      * Get whether the password should be set when this form is commited.
192      *
193      * @return set password when commited
194      */

195     public boolean isSetPassword() {
196         return setPassword;
197     }
198
199     /**
200      * Initialise the form
201      *
202      * @param user account to edit
203      * @param editing editing
204      * @param request request
205      * @throws Exception on any error
206      */

207     public void initialize(User user, boolean editing, HttpServletRequest JavaDoc request) throws Exception JavaDoc {
208                 
209         username = user == null ? "" : user.getPrincipalName();
210         realmName = user == null ? "" : user.getRealm().getResourceName();
211         email = user == null ? "" : user.getEmail();
212         fullname = user == null ? "" : user.getFullname();
213         try {
214             enabled = user == null ? true : PolicyUtil.isEnabled(user);
215         } catch (Exception JavaDoc e) {
216             log.warn("Failed to determine if user is enabled, defaulting to disabled.");
217             enabled = false;
218         }
219         setActionTarget("commit");
220         setPassword = false;
221         this.editing = editing;
222         roles = new PropertyList();
223         Role[] allRoles = user == null ? new Role[0] : user.getRoles();
224         for (int i = 0; i < allRoles.length; i++) {
225             roles.add(allRoles[i].getPrincipalName());
226         }
227
228         /*
229          * Get all of the user attribute definitions and wrap them in item
230          * objects
231          */

232
233         userAttributeValueItems = new ArrayList JavaDoc();
234         for (PropertyDefinition d : propertyClass.getDefinitions()) {
235             AttributeDefinition def = (AttributeDefinition)d;
236             if (!def.isHidden()) {
237                 if (def.getVisibility() != AttributeDefinition.USER_CONFIDENTIAL_ATTRIBUTE) {
238                     String JavaDoc value = def.getDefaultValue();
239                     if (user != null) {
240                         value = Property.getProperty(new UserAttributeKey(user, def.getName()));
241                     }
242                     AttributeValueItem item = new AttributeValueItem(def, request, value);
243                     userAttributeValueItems.add(item);
244                 }
245             }
246         }
247
248         /*
249          * Sort the list of items and build up the list of categories
250          */

251
252         Collections.sort(userAttributeValueItems);
253         categoryIds = new ArrayList JavaDoc();
254         categoryTitles = new ArrayList JavaDoc();
255         for (Iterator JavaDoc i = userAttributeValueItems.iterator(); i.hasNext();) {
256             AttributeValueItem item = (AttributeValueItem) i.next();
257             int idx = categoryIds.indexOf(item.getCategoryId());
258             if (idx == -1) {
259                 categoryIds.add(item.getCategoryId());
260                 categoryTitles.add(item.getCategoryLabel());
261             }
262         }
263     }
264
265     /**
266      * Get a list of the category ids
267      *
268      * @return category ids
269      */

270     public List JavaDoc getCategoryIds() {
271         return categoryIds;
272     }
273
274     /**
275      * Get the list of user attribute value items
276      *
277      * @return user attribute value items
278      */

279     public List JavaDoc getAttributeValueItems() {
280         return userAttributeValueItems;
281     }
282
283     /*
284      * (non-Javadoc)
285      *
286      * @see org.apache.struts.action.ActionForm#reset(org.apache.struts.action.ActionMapping,
287      * javax.servlet.http.HttpServletRequest)
288      */

289     public void reset(ActionMapping mapping, javax.servlet.http.HttpServletRequest JavaDoc request) {
290         // super.reset(mapping, request);
291
// username = "";
292
// email = "";
293
// fullname = "";
294
// attributes = new Properties();
295
enabled = false;
296         // if (roles != null) {
297
// roles.clear();
298
// }
299
if (userAttributeValueItems != null) {
300             for (Iterator JavaDoc i = userAttributeValueItems.iterator(); i.hasNext();) {
301                 AttributeValueItem item = (AttributeValueItem) i.next();
302                 if (item.getDefinition().getType() == PropertyDefinition.TYPE_BOOLEAN) {
303                     item.setSelected(false);
304                 }
305             }
306         }
307     }
308
309     /**
310      * Get whether the username is disabled or not
311      *
312      * TODO is this required, can't editing be used?
313      *
314      * @return username disabled
315      */

316     public String JavaDoc getUsernameDisabled() {
317         return String.valueOf(getEditing());
318     }
319
320     /*
321      * (non-Javadoc)
322      *
323      * @see org.apache.struts.action.ActionForm#validate(org.apache.struts.action.ActionMapping,
324      * javax.servlet.http.HttpServletRequest)
325      */

326     public ActionErrors validate(ActionMapping mapping, HttpServletRequest JavaDoc request) {
327         ActionErrors errors = new ActionErrors();
328         if (isCommiting()) {
329             UserDatabase udb;
330             try {
331                 udb = UserDatabaseManager.getInstance().getUserDatabase(LogonControllerFactory.getInstance().getUser(request).getRealm());
332             } catch (Exception JavaDoc e1) {
333                 errors.add(Globals.ERROR_KEY, new ActionMessage("availableRoles.noUserDatabase"));
334                 return errors;
335             }
336             if (username == null || username.length() == 0) {
337                 errors.add(Globals.ERROR_KEY, new ActionMessage("createAccount.error.noUsername"));
338             }
339             if (username.length() > 32) {
340                 errors.add(Globals.ERROR_KEY, new ActionMessage("createAccount.error.usernameExceeds32Chars"));
341             }
342             if (udb.supportsAccountCreation()) {
343                 if (fullname == null || fullname.length() == 0) {
344                     errors.add(Globals.ERROR_KEY, new ActionMessage("createAccount.error.noFullName"));
345                 }
346                 if (fullname.length() > 32) {
347                     errors.add(Globals.ERROR_KEY, new ActionMessage("createAccount.error.fullNameExceeds32Chars"));
348                 }
349             }
350             User currentUser;
351             try {
352                 currentUser = ContextHolder.getContext().isSetupMode() ? null : LogonControllerFactory.getInstance()
353                                 .getUser(request);
354                 if (currentUser != null && getEditing() && currentUser.getPrincipalName().equals(getUsername())) {
355                     // Make sure there is at least one enabled account
356
if (!isEnabled()) {
357                         errors.add(Globals.ERROR_KEY, new ActionMessage("createAccount.error.cantDisableYourself"));
358                     }
359                 }
360                 if (!editing) {
361                     try {
362                         udb.getAccount(username);
363                         errors.add(Globals.ERROR_KEY, new ActionMessage("createAccount.error.userAlreadyExists", username));
364                     } catch (Exception JavaDoc e) {
365                     }
366                 }
367                 for (Iterator JavaDoc i = userAttributeValueItems.iterator(); i.hasNext();) {
368                     AttributeValueItem item = (AttributeValueItem) i.next();
369                     PropertyDefinition def = item.getDefinition();
370                     try {
371                         def.validate(item.getValue().toString(), getClass().getClassLoader());
372                     } catch (CoreException ce) {
373                         ce.getBundleActionMessage().setArg3(item.getLabel());
374                         errors.add(Globals.ERROR_KEY, ce.getBundleActionMessage());
375                     } catch (CodedException ce) {
376                         errors.add(Globals.ERROR_KEY, new ActionMessage("[Err:" + ce.getCode() + "] " + ce.getMessage()));
377                     }
378                 }
379                 
380                 // Validate selected groups
381
for (String JavaDoc role : getRolesList()) {
382                     try {
383                         UserDatabaseManager.getInstance().getDefaultUserDatabase().getRole(role);
384                     } catch (Exception JavaDoc e) {
385                         errors.add(Globals.ERROR_KEY, new ActionMessage("createAccount.error.invalidRole", role));
386                     }
387                 }
388             } catch (Exception JavaDoc e) {
389                 log.warn("Failed to validate user form.", e);
390                 e.printStackTrace();
391             }
392         }
393         return errors;
394     }
395
396     /**
397      * Get the list of roles this account is attached (as strings)
398      *
399      * @return roles
400      */

401     public PropertyList getRolesList() {
402         return roles;
403     }
404
405     /**
406      * Get a list of selected roles as a list in <i>Text Field Text</i> format.
407      *
408      * @return list of roles
409      */

410     public String JavaDoc getSelectedRoles() {
411         return roles.getAsTextFieldText();
412     }
413
414     /**
415      * Set a list of selected roles as a list in <i>Text Field Text</i> format.
416      *
417      * @param selectedRoles selected roles
418      */

419     public void setSelectedRoles(String JavaDoc selectedRoles) {
420         roles.setAsTextFieldText(selectedRoles);
421     }
422
423     /*
424      * (non-Javadoc)
425      *
426      * @see com.sslexplorer.tabs.TabModel#getTabCount()
427      */

428     public int getTabCount() {
429         return 1 + (categoryIds.size());
430     }
431
432     /*
433      * (non-Javadoc)
434      *
435      * @see com.sslexplorer.tabs.TabModel#getTabName(int)
436      */

437     public String JavaDoc getTabName(int idx) {
438         switch (idx) {
439             case 0:
440                 return "details";
441             default:
442                 return (String JavaDoc) categoryIds.get(idx - 1);
443         }
444     }
445
446     /*
447      * (non-Javadoc)
448      *
449      * @see com.sslexplorer.tabs.TabModel#getSelectedTab()
450      */

451     public String JavaDoc getSelectedTab() {
452         return selectedTab;
453     }
454
455     /*
456      * (non-Javadoc)
457      *
458      * @see com.sslexplorer.tabs.TabModel#setSelectedTab(java.lang.String)
459      */

460     public void setSelectedTab(String JavaDoc selectedTab) {
461         this.selectedTab = selectedTab;
462     }
463
464     /*
465      * (non-Javadoc)
466      *
467      * @see com.sslexplorer.tabs.TabModel#getTabTitle(int)
468      */

469     public String JavaDoc getTabTitle(int idx) {
470         switch (idx) {
471             case 0:
472                 return null;
473             default:
474                 return (String JavaDoc) categoryTitles.get(idx - 1);
475         }
476     }
477
478     /* (non-Javadoc)
479      * @see com.sslexplorer.tabs.TabModel#getTabBundle(int)
480      */

481     public String JavaDoc getTabBundle(int idx) {
482         return null;
483     }
484 }
485
Popular Tags