KickJava   Java API By Example, From Geeks To Geeks.

Java > Open Source Codes > com > ivata > groupware > admin > security > SecurityImpl


1 /*
2  * Copyright (c) 2001 - 2005 ivata limited.
3  * All rights reserved.
4  * -----------------------------------------------------------------------------
5  * ivata groupware may be redistributed under the GNU General Public
6  * License as published by the Free Software Foundation;
7  * version 2 of the License.
8  *
9  * These programs are free software; you can redistribute them and/or
10  * modify them under the terms of the GNU General Public License
11  * as published by the Free Software Foundation; version 2 of the License.
12  *
13  * These programs are distributed in the hope that they will be useful,
14  * but WITHOUT ANY WARRANTY; without even the implied warranty of
15  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
16  *
17  * See the GNU General Public License in the file LICENSE.txt for more
18  * details.
19  *
20  * If you would like a copy of the GNU General Public License write to
21  *
22  * Free Software Foundation, Inc.
23  * 59 Temple Place - Suite 330
24  * Boston, MA 02111-1307, USA.
25  *
26  *
27  * To arrange commercial support and licensing, contact ivata at
28  * http://www.ivata.com/contact.jsp
29  * -----------------------------------------------------------------------------
30  * $Log: SecurityImpl.java,v $
31  * Revision 1.3 2005/04/10 19:42:41 colinmacleod
32  * *** empty log message ***
33  *
34  * Revision 1.2 2005/04/09 17:19:56 colinmacleod
35  * Changed copyright text to GPL v2 explicitly.
36  *
37  * Revision 1.1.1.1 2005/03/10 17:51:40 colinmacleod
38  * Restructured ivata op around Hibernate/PicoContainer.
39  * Renamed ivata groupware.
40  *
41  * Revision 1.4 2004/11/12 18:16:07 colinmacleod
42  * Ordered imports.
43  *
44  * Revision 1.3 2004/11/12 15:57:18 colinmacleod
45  * Removed dependencies on SSLEXT.
46  * Moved Persistence classes to ivata masks.
47  *
48  * Revision 1.2 2004/11/03 16:07:19 colinmacleod
49  * Many bugfixes.
50  * Added new addUser method.
51  *
52  * Revision 1.1 2004/09/30 15:15:58 colinmacleod
53  * Split off addressbook elements into security subproject.
54  *
55  * Revision 1.2 2004/07/18 21:59:09 colinmacleod
56  * Removed Person from User - now you need to use addressbook/persistence
57  * manager to find the person (makes the app run faster.)
58  *
59  * Revision 1.1 2004/07/13 19:41:11 colinmacleod
60  * Moved project to POJOs from EJBs.
61  * Applied PicoContainer to services layer (replacing session EJBs).
62  * Applied Hibernate to persistence layer (replacing entity EJBs).
63  * -----------------------------------------------------------------------------
64  */

65 package com.ivata.groupware.admin.security;
66
67 import javax.ejb.EJBException JavaDoc;
68
69 import com.ivata.groupware.admin.security.server.SecurityServer;
70 import com.ivata.groupware.admin.security.server.SecuritySession;
71 import com.ivata.groupware.admin.security.user.UserDO;
72 import com.ivata.groupware.business.BusinessLogic;
73 import com.ivata.groupware.container.persistence.QueryPersistenceManager;
74 import com.ivata.mask.Mask;
75 import com.ivata.mask.MaskFactory;
76 import com.ivata.mask.persistence.FinderException;
77 import com.ivata.mask.persistence.PersistenceSession;
78 import com.ivata.mask.util.SystemException;
79 import com.ivata.mask.validation.ValidationError;
80 import com.ivata.mask.validation.ValidationException;
81
82
83 /**
84  * <p>The security bean is responsible for adding, removing and amending users
85  * to the system, and for logging in in the first place.</p>
86  *
87  * @since 2002-09-08
88  * @author Colin MacLeod
89  * <a HREF='mailto:colin.macleod@ivata.com'>colin.macleod@ivata.com</a>
90  * @version $Revision: 1.3 $
91  * TODO: finish user right implementation
92  */

93 public class SecurityImpl extends BusinessLogic implements Security {
94     private MaskFactory maskFactory;
95
96     /**
97      * Persistence manger used to store/retrieve data objects, or retrieve a
98      * new persistence session.
99      */

100     private QueryPersistenceManager persistenceManager;
101
102     /**
103      * Security server - used for logging in users.
104      */

105     private SecurityServer securityServer;
106
107     /**
108      * All security features are disabled in demo mode. This is determined
109      * by the site setting <code>demoVersion</code>.
110      */

111     private boolean demoVersion;
112
113     /**
114      * Construct and initialize the Security implementation.
115      *
116      * @param persistenceManager persistence manager used to store/retrieve data
117      * objects.
118      */

119     public SecurityImpl(final QueryPersistenceManager persistenceManager,
120             final SecurityServer securityServer,
121             final MaskFactory maskFactory,
122             final Boolean JavaDoc demoVersion) {
123         this.persistenceManager = persistenceManager;
124         this.securityServer = securityServer;
125         this.maskFactory = maskFactory;
126         this.demoVersion = demoVersion.booleanValue();
127     }
128     /**
129      * <p>Add a new user to the system.</p>
130      * <p>
131      * <strong>Note:</strong> if you are using an address book, do not use this method!!!
132      * Use <code>AddressBookSecurity.addUserToPerson</code> instead.
133      * </p>
134      *
135      * @param securitySession checks the current site user is allowed to perform
136      * the action
137      * @param user the user to be amended.
138      */

139     public UserDO addUser(final SecuritySession securitySession,
140             final UserDO user)
141                 throws SystemException {
142         // not in demo mode!
143
if (demoVersion) {
144             return user;
145         }
146
147         PersistenceSession persistenceSession = persistenceManager.openSession(securitySession);
148         Mask mask = maskFactory.getMask(UserDO.class);
149
150         // if the user is deleted, it is naturally also disabled!
151
if (user.isDeleted()) {
152             user.setEnabled(false);
153         }
154         // first check this user name is not already taken
155
if (isUser(securitySession, user.getName())) {
156             throw new ValidationException(
157                         new ValidationError(
158                                 "user",
159                                 Security.BUNDLE_PATH,
160                                 mask.getField("name"),
161                                 "errors.unique"
162                                         ));
163         }
164
165         try {
166             persistenceManager.add(persistenceSession, user);
167             // if the user is enabled, add it to the security server
168
if (user.isEnabled()) {
169                 securityServer.addUser(securitySession,
170                         user.getName(), getRealName(
171                         persistenceSession, user));
172             }
173         } catch (Exception JavaDoc e) {
174             persistenceSession.cancel();
175             throw new SystemException(e);
176         } finally {
177             persistenceSession.close();
178         }
179
180         return user;
181     }
182
183     /**
184      * <p>Amend a user in the system.</p>
185      *
186      * @param securitySession checks the current site user is allowed to perform
187      * the action
188      * @param user the user to be amended.
189      */

190     public void amendUser(final SecuritySession securitySession,
191             final UserDO user)
192                 throws SystemException {
193         if (demoVersion) {
194             return;
195         }
196         Mask mask = maskFactory.getMask(UserDO.class);
197         // check we have field values
198
PersistenceSession persistenceSession = persistenceManager.openSession(securitySession);
199         UserDO oldUser = null;
200
201         try {
202             oldUser = (UserDO) persistenceManager.findByPrimaryKey(persistenceSession,
203                     UserDO.class, user.getId());
204         } catch (Exception JavaDoc e) {
205             persistenceSession.cancel();
206             throw new SystemException(e);
207         } finally {
208             persistenceSession.close();
209         }
210         persistenceSession = persistenceManager.openSession(securitySession);
211         try {
212
213             // if the user is deleted, it is naturally also disabled!
214
if (user.isDeleted()) {
215                 user.setEnabled(false);
216             }
217
218             // remove the user name from the mail system -
219
// only if the old user is enabled
220
if (!user.isEnabled()) {
221                 if (oldUser.isEnabled()) {
222                     securityServer.removeUser(securitySession,
223                             oldUser.getName());
224                 }
225             } else {
226                 // likewise if the old user is disabled and it is now enabled,
227
// recreate the user
228
if (!oldUser.isEnabled()) {
229                     securityServer.addUser(securitySession,
230                             user.getName(), user.getDisplayName());
231                 }
232                 if(!oldUser.getName().equals(user.getName())) {
233                     try {
234                         UserDO sameNameUser =
235                             (UserDO) persistenceManager.findInstance(persistenceSession,
236                             "securityUserByName",
237                             new Object JavaDoc[] { user.getName() });
238                         throw new ValidationException(
239                                 new ValidationError(
240                                         "user",
241                                         Security.BUNDLE_PATH,
242                                         mask.getField("name"),
243                                         "errors.unique"
244                                         ));
245                     } catch (FinderException thatsGood) { // that's good!
246
persistenceManager.amend(persistenceSession, user);
247
248                         // if the name changed, there are special
249
// considerations...
250
onAmendUserName(securitySession, persistenceSession,
251                                 user, oldUser.getName());
252                     }
253                 } else {
254                     persistenceManager.amend(persistenceSession, user);
255                 }
256             }
257         } catch (Exception JavaDoc e) {
258             persistenceSession.cancel();
259             throw new SystemException(e);
260         } finally {
261             persistenceSession.close();
262         }
263     }
264     /**
265      * <p>Check a password is correct for a user.</p>
266      *
267      * @param userName
268      * @param password
269      * @throws InvalidFieldValueException if any of the parameters are
270      * <code>null</code>.
271      * @throws InvalidFieldValueException if any of the parameters are
272      * <code>null</code>.
273      */

274     public void checkPassword(final SecuritySession securitySession,
275             final String JavaDoc password)
276             throws SystemException {
277         if (demoVersion) {
278             return;
279         }
280         UserDO user = securitySession.getUser();
281
282         // check the password is correct
283
securityServer.checkPassword(securitySession,
284                 user.getName(), password);
285     }
286
287     /**
288      * <p>Enable/disable a user from logging into the system.</p>
289      *
290      * @param userName the name of the user who is changing the access of
291      * another user. <strong>This is the not the user to enable/disable!</strong>
292      * @param userNameEnable the name of the user to enable or disable.
293      * @param enable set to <code>true</code> if the user should be allowed to
294      * log into the system, otherwise <code>false</code>.
295      * @throws InvalidFieldValueException if any of the parameters are
296      * <code>null</code>.
297      */

298     public void enableUser(final SecuritySession securitySession,
299             final String JavaDoc userNameEnable,
300             final boolean enable)
301             throws SystemException {
302         if (demoVersion) {
303             return;
304         }
305         Mask mask = maskFactory.getMask(UserDO.class);
306         // check we have field values
307
PersistenceSession persistenceSession = persistenceManager.openSession(securitySession);
308         try {
309             if (userNameEnable == null) {
310                 throw new ValidationException(
311                         new ValidationError(
312                                 "user",
313                                 Security.BUNDLE_PATH,
314                                 mask.getField("name"),
315                                 "errors.required"));
316             }
317
318             // find the user
319
UserDO user = (UserDO) persistenceManager.findInstance(persistenceSession,
320                     "securityUserByName",
321                     new Object JavaDoc[] { userNameEnable });
322             user.setEnabled(enable);
323             amendUser(securitySession, user);
324         } catch (Exception JavaDoc e) {
325             persistenceSession.cancel();
326             throw new SystemException(e);
327         } finally {
328             persistenceSession.close();
329         } }
330
331     /**
332      * Find a user given the user name.
333      *
334      * @param securitySession valid security session.
335      * @param userName name of the user to find.
336      */

337     public UserDO findUserByName(final SecuritySession securitySession,
338             final String JavaDoc userName)
339             throws SystemException {
340         PersistenceSession persistenceSession = persistenceManager.openSession(securitySession);
341         try {
342             return (UserDO) persistenceManager.findInstance(persistenceSession,
343                     "securityUserByName", new Object JavaDoc[] {userName});
344         } catch (Exception JavaDoc e) {
345             persistenceSession.cancel();
346             if (e instanceof SystemException) {
347                 throw (SystemException) e;
348             } else {
349                 throw new SystemException(e);
350             }
351         } finally {
352             persistenceSession.close();
353         }
354     }
355
356     /**
357      * <p>
358      * Override this to provide a better string as the 'real' user name. This
359      * is usually a name such as "Paul Smith". The default implementation just
360      * returns the user name.
361      * </p>
362      *
363      * @param persistenceSession Valid persistence session.
364      * @param user The user for whom to return the name.
365      * @return Real-life name for this user.
366      * @throws SystemException
367      */

368     protected String JavaDoc getRealName(final PersistenceSession persistenceSession,
369             final UserDO user)
370             throws SystemException {
371         return user.getName();
372     }
373
374     /**
375      * <p>This method add prefix to username.</p>
376      *
377      * @param userName
378      * @return prefix_userName
379      */

380     public final String JavaDoc getSystemUserName(final SecuritySession securitySession,
381             final String JavaDoc userName) {
382         return securityServer.getSystemUserName(securitySession,
383                 userName);
384     }
385
386     /**
387      * <p>This method is converts the system username back into a plain old
388      * username, it's the opposite method to getSystemUserName.</p>
389      */

390     public final String JavaDoc getUserNameFromSystemUserName(
391             final SecuritySession securitySession,
392             final String JavaDoc systemUserName) {
393         return securityServer.getUserNameFromSystemUserName(securitySession,
394                 systemUserName);
395     }
396     /**
397      * @param userNameParam
398      * @return
399      * @throws SystemException
400      */

401     public boolean isUser(SecuritySession securitySession,
402             String JavaDoc userNameParam) throws SystemException {
403         return securityServer.isUser(securitySession,
404                 userNameParam);
405     }
406
407     /**
408      * <p>Find out if a user is currently enabled
409      * @param userName
410      * @throws InvalidFieldValueException if <code>userName</code> is
411      * <code>null</code>.
412      * @return <code>true</code> if the user is currently enabled, otherwise
413      * <code>false</code>.
414      */

415     public boolean isUserEnabled(final SecuritySession securitySession,
416             final String JavaDoc userName)
417             throws SystemException {
418         if (demoVersion) {
419             return false;
420         }
421         assert (userName != null);
422
423         // check we have field values
424
PersistenceSession persistenceSession = persistenceManager.openSession(securitySession);
425         try {
426
427             // find the user
428
UserDO user = (UserDO) persistenceManager.findInstance(persistenceSession,
429                     "securityUserByName",
430                     new Object JavaDoc[] { userName });
431
432             return user.isEnabled();
433         } catch (Exception JavaDoc e) {
434             persistenceSession.cancel();
435             throw new SystemException(e);
436         } finally {
437             persistenceSession.close();
438         }
439     }
440
441     /**
442      * <p>Login to the system. This method confirms the user name and password
443      * against system settings and logs the user into the mail server, if this
444      * is the desired form of authentication.</p>
445      *
446      * @param user user to log into the remote system.
447      * @param password the clear-text password to log into the remote system.
448      * @throws EJBException if the person cannot log in.
449      * @return the mail server used to access the mail system, or
450      * <code>null</code> if another form of authentication is being used.
451      */

452     public SecuritySession login(final UserDO user,
453             final String JavaDoc password) throws SystemException {
454         SecuritySession session;
455         session = securityServer.login(user, password);
456
457         return session;
458     }
459
460     /**
461      * <p>if userName emergency is trying login -> find first admin .</p>
462      * @param userName
463      * @return
464      */

465     public String JavaDoc loginAgain(final SecuritySession securitySession,
466             final String JavaDoc userName)
467             throws SystemException {
468         return "guest";
469     }
470
471     /**
472      * <p>Login as a guest to the system. </p>
473      *
474      * @throws EJBException if the person cannot log in.
475      * @return the mail server used to access the mail system, or
476      * <code>null</code> if another form of authentication is being used.
477      */

478     public SecuritySession loginGuest() throws SystemException {
479         SecuritySession session;
480
481         session = securityServer.loginGuest();
482
483         return session;
484     }
485
486     /**
487      * Called when the user name is changed, so it can be overridden to change
488      * address book groups accordingly.
489      * @param persistenceSession valid, open session for the current data store
490      * transaction.
491      * @param user user with the new name set.
492      * @param oldName user name before the change.
493      *
494      * @throws SystemException if the name cannot be changed for any reason
495      */

496     protected void onAmendUserName(
497             final SecuritySession securitySession,
498             final PersistenceSession persistenceSession,
499             final UserDO user,
500             final String JavaDoc oldName)
501             throws SystemException {
502         if (demoVersion) {
503             return;
504         }
505         Mask mask = maskFactory.getMask(UserDO.class);
506         // if the user names have changed, remove the old user
507
// from the system and add the new one
508
// find the user
509
// check the new username is not already taken
510
if (securityServer.isUser(securitySession, user.getName())) {
511             throw new ValidationException(
512                     new ValidationError(
513                             "user",
514                             Security.BUNDLE_PATH,
515                             mask.getField("name"),
516                             "errors.unique"));
517         }
518         securityServer.removeUser(securitySession, oldName);
519         securityServer.addUser(securitySession, user.getName(),
520                 getRealName(persistenceSession, user));
521     }
522
523     /**
524      * <p>Remove a user from the system. The user is marked as logically deleted.</p>
525      *
526      * @param userName the name of the user who is doing the removing. <strong>This
527      * is not the name of the user to be removed!</strong>
528      * @param userNameRemove the name of the user to be removed.
529      * @see #enableUser
530      * @throws InvalidFieldValueException if any of the parameters are
531      * <code>null</code>.
532      */

533     public void removeUser(final SecuritySession securitySession,
534             final String JavaDoc userNameRemove)
535             throws SystemException {
536         if (demoVersion) {
537             return;
538         }
539         // check we have field values
540
Mask mask = maskFactory.getMask(UserDO.class);
541         PersistenceSession persistenceSession = persistenceManager.openSession(securitySession);
542
543         try {
544             if (userNameRemove == null) {
545                 throw new ValidationException(
546                         new ValidationError(
547                                 "user",
548                                 Security.BUNDLE_PATH,
549                                 mask.getField("name"),
550                                 "errors.required"));
551             }
552
553             // find the user
554
UserDO user = (UserDO) persistenceManager.findInstance(persistenceSession,
555                     "securityUserByName",
556                     new Object JavaDoc[] { userNameRemove });
557             // now mark the entity as deleted
558
user.setDeleted(true);
559             amendUser(securitySession, user);
560         } catch (Exception JavaDoc e) {
561             persistenceSession.cancel();
562             throw new SystemException(e);
563         } finally {
564             persistenceSession.close();
565         }
566     }
567
568     /**
569      * <p>Restore a deleted user.</p>
570      * @param userName who is doing this operation
571      * @param restoreUserName who is going to be restored
572      */

573     public void restoreUser(final SecuritySession securitySession,
574             final String JavaDoc restoreUserName) throws SystemException {
575         if (demoVersion) {
576             return;
577         }
578         assert (restoreUserName != null);
579         PersistenceSession persistenceSession = persistenceManager.openSession(securitySession);
580         try {
581             // find the user
582
UserDO user = (UserDO) persistenceManager.findInstance(persistenceSession,
583                 "securityUserByName",
584                 new Object JavaDoc[] { restoreUserName });
585             user.setDeleted(false);
586             amendUser(securitySession, user);
587         } catch (Exception JavaDoc e) {
588             persistenceSession.cancel();
589             throw new SystemException(e);
590         } finally {
591             persistenceSession.close();
592         }
593     }
594
595     /**
596      * <p>Set the password of a user.</p>
597      *
598      * @param userName the name of the user who is changing the password in the
599      * system. <strong>This is not be the user name whose password is to be
600      * changed!</strong>
601      * @param userNamePassword the name of the user for whom to change the
602      * password.
603      * @param password the new value of the password (unencrypted) for the user.
604      * @throws InvalidFieldValueException if any of the parameters are
605      * <code>null</code>.
606      */

607     public final void setPassword(final SecuritySession securitySession,
608             final String JavaDoc userNamePassword,
609             final String JavaDoc password)
610             throws SystemException {
611         if (demoVersion) {
612             return;
613         }
614         // check we have field values
615
Mask mask = maskFactory.getMask(UserDO.class);
616         PersistenceSession persistenceSession = persistenceManager.openSession(securitySession);
617         try {
618             if (userNamePassword == null) {
619                 throw new ValidationException(
620                         new ValidationError(
621                                 "user",
622                                 Security.BUNDLE_PATH,
623                                 mask.getField("name"),
624                                 "errors.required"));
625             }
626
627             // find the user
628
UserDO user = (UserDO) persistenceManager.findInstance(persistenceSession,
629                     "securityUserByName",
630                     new Object JavaDoc[] { userNamePassword });
631
632             // set password on mailserver
633
securityServer.setPassword(securitySession,
634                     user.getName(), password);
635         } catch (Exception JavaDoc e) {
636             persistenceSession.cancel();
637             throw new SystemException(e);
638         } finally {
639             persistenceSession.close();
640         }
641     }
642     /**
643      * @return Returns the demoVersion.
644      */

645     protected boolean isDemoVersion() {
646         return demoVersion;
647     }
648 }
649
Popular Tags