View Javadoc

1   package org.apache.turbine.services.security.ldap;
2   
3   
4   /*
5    * Copyright 2001-2004 The Apache Software Foundation.
6    *
7    * Licensed under the Apache License, Version 2.0 (the "License")
8    * you may not use this file except in compliance with the License.
9    * You may obtain a copy of the License at
10   *
11   *     http://www.apache.org/licenses/LICENSE-2.0
12   *
13   * Unless required by applicable law or agreed to in writing, software
14   * distributed under the License is distributed on an "AS IS" BASIS,
15   * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
16   * See the License for the specific language governing permissions and
17   * limitations under the License.
18   */
19  
20  
21  import java.io.ByteArrayOutputStream;
22  import java.io.PrintWriter;
23  import java.sql.Connection;
24  import java.util.Hashtable;
25  
26  import javax.naming.NamingException;
27  import javax.naming.directory.Attribute;
28  import javax.naming.directory.Attributes;
29  import javax.naming.directory.BasicAttribute;
30  import javax.naming.directory.BasicAttributes;
31  import javax.servlet.http.HttpSessionBindingEvent;
32  
33  import org.apache.commons.logging.Log;
34  import org.apache.commons.logging.LogFactory;
35  import org.apache.turbine.om.security.User;
36  import org.apache.turbine.services.security.TurbineSecurity;
37  
38  /***
39   * LDAPUser implements User and provides access to a user who accesses the
40   * system via LDAP.
41   *
42   * @author <a href="mailto:cberry@gluecode.com">Craig D. Berry</a>
43   * @author <a href="mailto:tadewunmi@gluecode.com">Tracy M. Adewunmi</a>
44   * @author <a href="mailto:lflournoy@gluecode.com">Leonard J. Flournoy </a>
45   * @author <a href="mailto:dlr@finemaltcoding.com">Daniel Rall</a>
46   * @author <a href="mailto:hhernandez@itweb.com.mx">Humberto Hernandez</a>
47   */
48  public class LDAPUser implements User
49  {
50  
51      /*** Logging */
52      private static Log log = LogFactory.getLog(LDAPUser.class);
53  
54      /* A few attributes common to a User. */
55  
56      /*** Date when the user was created */
57      private java.util.Date createDate = null;
58  
59      /*** Date when the user was last accessed */
60      private java.util.Date lastAccessDate = null;
61  
62      /*** timeout */
63      private int timeout = 15;
64  
65      /*** This is data that will survive a servlet engine restart. */
66      private Hashtable permStorage = null;
67  
68      /*** This is data that will not survive a servlet engine restart. */
69      private Hashtable tempStorage = null;
70  
71      /***
72       * Constructor.
73       * Create a new User and set the createDate.
74       */
75      public LDAPUser()
76      {
77          createDate = new java.util.Date();
78          tempStorage = new Hashtable(10);
79          permStorage = new Hashtable(10);
80          setHasLoggedIn(new Boolean(false));
81      }
82  
83      /***
84       * Populates the user with values obtained from the LDAP Service.
85       * This method could be redefined in subclasses.
86       * @param attribs The attributes obtained from LDAP.
87       * @throws NamingException if there was an error with JNDI.
88       */
89      public void setLDAPAttributes(Attributes attribs)
90              throws NamingException
91      {
92  
93          Attribute attr;
94          String attrName;
95  
96          // Set the User id.
97          attrName = LDAPSecurityConstants.getUserIdAttribute();
98          if (attrName != null)
99          {
100             attr = attribs.get(attrName);
101             if (attr != null && attr.get() != null)
102             {
103                 try
104                 {
105                     //setPrimaryKey(attr.get().toString());
106                 }
107                 catch (Exception ex)
108                 {
109                     log.error("Exception caught:", ex);
110                 }
111             }
112         }
113 
114         // Set the Username.
115         attrName = LDAPSecurityConstants.getNameAttribute();
116         if (attrName != null)
117         {
118             attr = attribs.get(attrName);
119             if (attr != null && attr.get() != null)
120             {
121                 setName(attr.get().toString());
122             }
123         }
124         else
125         {
126             log.error("There is no LDAP attribute for the username.");
127         }
128 
129         // Set the Firstname.
130         attrName = LDAPSecurityConstants.getFirstNameAttribute();
131         if (attrName != null)
132         {
133             attr = attribs.get(attrName);
134             if (attr != null && attr.get() != null)
135             {
136                 setFirstName(attr.get().toString());
137             }
138         }
139 
140         // Set the Lastname.
141         attrName = LDAPSecurityConstants.getLastNameAttribute();
142         if (attrName != null)
143         {
144             attr = attribs.get(attrName);
145             if (attr != null && attr.get() != null)
146             {
147                 setLastName(attr.get().toString());
148             }
149         }
150 
151         // Set the E-Mail
152         attrName = LDAPSecurityConstants.getEmailAttribute();
153         if (attrName != null)
154         {
155             attr = attribs.get(attrName);
156             if (attr != null && attr.get() != null)
157             {
158                 setEmail(attr.get().toString());
159             }
160         }
161     }
162 
163     /***
164      * Get the JNDI Attributes used to store the user in LDAP.
165      * This method could be redefined in a subclass.
166      *
167      * @throws NamingException if there is a JNDI error.
168      * @return The JNDI attributes of the user.
169      */
170     public Attributes getLDAPAttributes()
171             throws NamingException
172     {
173         Attributes attribs = new BasicAttributes();
174         String attrName;
175 
176         // Set the objectClass
177         attrName = "objectClass";
178         if (attrName != null)
179         {
180             Object value = "turbineUser";
181 
182             if (value != null)
183             {
184                 Attribute attr = new BasicAttribute(attrName, value);
185 
186                 attribs.put(attr);
187             }
188         }
189 
190         // Set the User id.
191         attrName = LDAPSecurityConstants.getUserIdAttribute();
192         if (attrName != null)
193         {
194             Object value = this.getIdAsObj();
195 
196             if (value != null)
197             {
198                 Attribute attr = new BasicAttribute(attrName, value);
199 
200                 attribs.put(attr);
201             }
202         }
203 
204         // Set the Username.
205         attrName = LDAPSecurityConstants.getNameAttribute();
206         if (attrName != null)
207         {
208             Object value = getName();
209 
210             if (value != null)
211             {
212                 Attribute attr = new BasicAttribute(attrName, value);
213 
214                 attribs.put(attr);
215             }
216         }
217 
218         // Set the Firstname.
219         attrName = LDAPSecurityConstants.getFirstNameAttribute();
220         if (attrName != null)
221         {
222             Object value = getFirstName();
223 
224             if (value != null)
225             {
226                 Attribute attr = new BasicAttribute(attrName, value);
227 
228                 attribs.put(attr);
229             }
230         }
231 
232         // Set the Lastname.
233         attrName = LDAPSecurityConstants.getLastNameAttribute();
234         if (attrName != null)
235         {
236             Object value = getLastName();
237 
238             if (value != null)
239             {
240                 Attribute attr = new BasicAttribute(attrName, value);
241 
242                 attribs.put(attr);
243             }
244         }
245 
246         // Set the E-Mail.
247         attrName = LDAPSecurityConstants.getEmailAttribute();
248         if (attrName != null)
249         {
250             Object value = getEmail();
251 
252             if (value != null)
253             {
254                 Attribute attr = new BasicAttribute(attrName, value);
255 
256                 attribs.put(attr);
257             }
258         }
259 
260         // Set the Password
261         attrName = LDAPSecurityConstants.getPasswordAttribute();
262         if (attrName != null)
263         {
264             Object value = getPassword();
265 
266             if (value != null)
267             {
268                 Attribute attr = new BasicAttribute(attrName, value);
269 
270                 attribs.put(attr);
271             }
272         }
273 
274         return attribs;
275     }
276 
277     /***
278      * Gets the distinguished name (DN) of the User.
279      * This method could be redefined in a subclass.
280      * @return The Distinguished Name of the user.
281      */
282     public String getDN()
283     {
284         String filterAttribute = LDAPSecurityConstants.getNameAttribute();
285         String userBaseSearch = LDAPSecurityConstants.getBaseSearch();
286         String userName = getName();
287 
288         String dn = filterAttribute + "=" + userName + "," + userBaseSearch;
289 
290         return dn;
291     }
292 
293     /***
294      * Gets the access counter for a user during a session.
295      *
296      * @return The access counter for the user for the session.
297      */
298     public int getAccessCounterForSession()
299     {
300         try
301         {
302             return ((Integer) getTemp(User.SESSION_ACCESS_COUNTER)).intValue();
303         }
304         catch (Exception e)
305         {
306             return 0;
307         }
308     }
309 
310     /***
311      * Gets the access counter for a user from perm storage.
312      *
313      * @return The access counter for the user.
314      */
315     public int getAccessCounter()
316     {
317         try
318         {
319             return ((Integer) getPerm(User.ACCESS_COUNTER)).intValue();
320         }
321         catch (Exception e)
322         {
323             return 0;
324         }
325     }
326 
327     /***
328      * Gets the create date for this User.  This is the time at which
329      * the user object was created.
330      *
331      * @return A Java Date with the date of creation for the user.
332      */
333     public java.util.Date getCreateDate()
334     {
335         return createDate;
336     }
337 
338     /***
339      * Returns the value of Confirmed variable
340      * @return the confirm value.
341      */
342     public String getConfirmed()
343     {
344         String tmp = null;
345 
346         tmp = (String) getPerm(User.CONFIRM_VALUE);
347         if (tmp != null && tmp.length() == 0)
348         {
349             tmp = null;
350         }
351         return tmp;
352     }
353 
354     /***
355      * Returns the Email for this user.  If this is defined, then
356      * the user is considered logged in.
357      *
358      * @return A String with the user's Email.
359      */
360     public String getEmail()
361     {
362         String tmp = null;
363 
364         tmp = (String) getPerm(User.EMAIL);
365         if (tmp != null && tmp.length() == 0)
366         {
367             tmp = null;
368         }
369         return tmp;
370     }
371 
372     /***
373      * Gets the last access date for this User.  This is the last time
374      * that the user object was referenced.
375      *
376      * @return A Java Date with the last access date for the user.
377      */
378     public java.util.Date getLastAccessDate()
379     {
380         if (lastAccessDate == null)
381         {
382             setLastAccessDate();
383         }
384         return lastAccessDate;
385     }
386 
387     /***
388      * Get last login date/time for this user.
389      *
390      * @return A Java Date with the last login date for the user.
391      */
392     public java.util.Date getLastLogin()
393     {
394         return (java.util.Date) getPerm(User.LAST_LOGIN);
395     }
396 
397     /***
398      * Get password for this user.
399      *
400      * @return A String with the password for the user.
401      */
402     public String getPassword()
403     {
404         return (String) getPerm(User.PASSWORD);
405     }
406 
407     /***
408      * Get an object from permanent storage.
409      * @param name The object's name.
410      * @return An Object with the given name.
411      */
412     public Object getPerm(String name)
413     {
414         return permStorage.get(name);
415     }
416 
417     /***
418      * Get an object from permanent storage; return default if value
419      * is null.
420      *
421      * @param name The object's name.
422      * @param def A default value to return.
423      * @return An Object with the given name.
424      */
425     public Object getPerm(String name, Object def)
426     {
427         try
428         {
429             Object val = permStorage.get(name);
430 
431             if (val == null)
432             {
433                 return def;
434             }
435             return val;
436         }
437         catch (Exception e)
438         {
439             return def;
440         }
441     }
442 
443     /***
444      * This should only be used in the case where we want to save the
445      * data to the database.
446      *
447      * @return A Hashtable.
448      */
449     public Hashtable getPermStorage()
450     {
451         if (this.permStorage == null)
452         {
453             this.permStorage = new Hashtable();
454         }
455         return this.permStorage;
456     }
457 
458     /***
459      * Get an object from temporary storage.
460      *
461      * @param name The object's name.
462      * @return An Object with the given name.
463      */
464     public Object getTemp(String name)
465     {
466         return tempStorage.get(name);
467     }
468 
469     /***
470      * Get an object from temporary storage; return default if value
471      * is null.
472      *
473      * @param name The object's name.
474      * @param def A default value to return.
475      * @return An Object with the given name.
476      */
477     public Object getTemp(String name, Object def)
478     {
479         Object val;
480 
481         try
482         {
483             val = tempStorage.get(name);
484             if (val == null)
485             {
486                 val = def;
487             }
488         }
489         catch (Exception e)
490         {
491             val = def;
492         }
493         return val;
494     }
495 
496     /***
497      * A User object can have a variable Timeout, which is defined in
498      * minutes.  If the user has been timed out, then the
499      * hasLoggedIn() value will return false.
500      *
501      * @return An int specifying the timeout.
502      */
503     public int getTimeout()
504     {
505         return this.timeout;
506     }
507 
508 
509     /***
510      * Returns the first name for this user.  If this is defined, then
511      * the user is considered logged in.
512      *
513      * @return A String with the user's first name.
514      */
515     public String getFirstName()
516     {
517         String tmp = null;
518 
519         tmp = (String) getPerm(User.FIRST_NAME);
520         if (tmp != null && tmp.length() == 0)
521         {
522             tmp = null;
523         }
524         return tmp;
525     }
526 
527     /***
528      * Returns the last name for this user.  If this is defined, then
529      * the user is considered logged in.
530      *
531      * @return A String with the user's last name.
532      */
533     public String getLastName()
534     {
535         String tmp = null;
536 
537         tmp = (String) getPerm(User.LAST_NAME);
538         if (tmp != null && tmp.length() == 0)
539         {
540             tmp = null;
541         }
542         return tmp;
543     }
544 
545     /***
546      * The user is considered logged in if they have not timed out.
547      *
548      * @return True if the user has logged in.
549      */
550     public boolean hasLoggedIn()
551     {
552         Boolean tmp = getHasLoggedIn();
553 
554         if (tmp != null && tmp.booleanValue())
555         {
556             return true;
557         }
558         else
559         {
560             return false;
561         }
562     }
563 
564     /***
565      * This method reports whether or not the user has been confirmed
566      * in the system by checking the <code>CONFIRM_VALUE</code>
567      * column to see if it is equal to <code>CONFIRM_DATA</code>.
568      *
569      * @return True if the user has been confirmed.
570      */
571     public boolean isConfirmed()
572     {
573         return ((String) getTemp(CONFIRM_VALUE, "")).equals(CONFIRM_DATA);
574     }
575 
576     /***
577      * Increments the permanent hit counter for the user.
578      */
579     public void incrementAccessCounter()
580     {
581         setAccessCounter(getAccessCounter() + 1);
582     }
583 
584     /***
585      * Increments the session hit counter for the user.
586      */
587     public void incrementAccessCounterForSession()
588     {
589         setAccessCounterForSession(getAccessCounterForSession() + 1);
590     }
591 
592     /***
593      * Remove an object from temporary storage and return the object.
594      *
595      * @param name The name of the object to remove.
596      * @return An Object.
597      */
598     public Object removeTemp(String name)
599     {
600         return tempStorage.remove(name);
601     }
602 
603     /***
604      * Sets the access counter for a user, saved in perm storage.
605      *
606      * @param cnt The new count.
607      */
608     public void setAccessCounter(int cnt)
609     {
610         setPerm(User.ACCESS_COUNTER, new Integer(cnt));
611     }
612 
613     /***
614      * Sets the session access counter for a user, saved in temp
615      * storage.
616      *
617      * @param cnt The new count.
618      */
619     public void setAccessCounterForSession(int cnt)
620     {
621         setTemp(User.SESSION_ACCESS_COUNTER, new Integer(cnt));
622     }
623 
624     /***
625      * Set the users confirmed variable
626      *
627      * @param confirm The new confim value.
628      */
629     public void setConfirmed(String confirm)
630     {
631         getPerm(User.CONFIRM_VALUE, confirm);
632     }
633 
634     /***
635      * Sets the last access date for this User. This is the last time
636      * that the user object was referenced.
637      */
638     public void setLastAccessDate()
639     {
640         lastAccessDate = new java.util.Date();
641     }
642 
643     /***
644      * Sets the create date for this User. This is the time at which
645      * the user object was created.
646      *
647      * @param date The create date.
648      */
649     public void setCreateDate(java.util.Date date)
650     {
651         createDate = date;
652     }
653 
654     /***
655      * Set the users Email
656      *
657      * @param email The new email.
658      */
659     public void setEmail(String email)
660     {
661         setPerm(User.EMAIL, email);
662     }
663 
664     /***
665      * Set the users First Name
666      *
667      * @param fname The new firstname.
668      */
669     public void setFirstName(String fname)
670     {
671         setPerm(User.FIRST_NAME, fname);
672     }
673 
674     /***
675      * Set last login date/time.
676      *
677      * @param date The last login date.
678      */
679     public void setLastLogin(java.util.Date date)
680     {
681         setPerm(User.LAST_LOGIN, date);
682     }
683 
684     /***
685      * Set the users Last Name
686      * Sets the last name for this user.
687      *
688      * @param lname The new lastname.
689      */
690     public void setLastName(String lname)
691     {
692         setPerm(User.LAST_NAME, lname);
693     }
694 
695     /***
696      * Set password.
697      *
698      * @param password The new password.
699      */
700     public void setPassword(String password)
701     {
702         setPerm(User.PASSWORD, password);
703     }
704 
705     /***
706      * Put an object into permanent storage.
707      *
708      * @param name The object's name.
709      * @param value The object.
710      */
711     public void setPerm(String name, Object value)
712     {
713         permStorage.put(name, value);
714     }
715 
716     /***
717      * This should only be used in the case where we want to save the
718      * data to the database.
719      *
720      * @param stuff A Hashtable.
721      */
722     public void setPermStorage(Hashtable stuff)
723     {
724         this.permStorage = stuff;
725     }
726 
727     /***
728      * This should only be used in the case where we want to save the
729      * data to the database.
730      *
731      * @return A Hashtable.
732      */
733     public Hashtable getTempStorage()
734     {
735         if (this.tempStorage == null)
736         {
737             this.tempStorage = new Hashtable();
738         }
739         return this.tempStorage;
740     }
741 
742     /***
743      * This should only be used in the case where we want to save the
744      * data to the database.
745      *
746      * @param storage A Hashtable.
747      */
748     public void setTempStorage(Hashtable storage)
749     {
750         this.tempStorage = storage;
751     }
752 
753     /***
754      * This gets whether or not someone has logged in.  hasLoggedIn()
755      * returns this value as a boolean.  This is private because you
756      * should use hasLoggedIn() instead.
757      *
758      * @return True if someone has logged in.
759      */
760     private Boolean getHasLoggedIn()
761     {
762         return (Boolean) getTemp(User.HAS_LOGGED_IN);
763     }
764 
765     /***
766      * This sets whether or not someone has logged in.  hasLoggedIn()
767      * returns this value.
768      *
769      * @param value Whether someone has logged in or not.
770      */
771     public void setHasLoggedIn(Boolean value)
772     {
773         setTemp(User.HAS_LOGGED_IN, value);
774     }
775 
776     /***
777      * Put an object into temporary storage.
778      *
779      * @param name The object's name.
780      * @param value The object.
781      */
782     public void setTemp(String name, Object value)
783     {
784         tempStorage.put(name, value);
785     }
786 
787     /***
788      * A User object can have a variable Timeout which is defined in
789      * minutes.  If the user has been timed out, then the
790      * hasLoggedIn() value will return false.
791      *
792      * @param time The user's timeout.
793      */
794     public void setTimeout(int time)
795     {
796         this.timeout = time;
797     }
798 
799 
800 
801     /***
802      * Updates the last login date in the database.
803      *
804      * @exception Exception a generic exception.
805      */
806     public void updateLastLogin() throws Exception
807     {
808         setPerm(User.LAST_LOGIN, new java.util.Date());
809     }
810 
811     /***
812      * Implement this method if you wish to be notified when the User
813      * has been Bound to the session.
814      *
815      * @param hsbe The HttpSessionBindingEvent.
816      */
817     public void valueBound(HttpSessionBindingEvent hsbe)
818     {
819         // Do not currently need this method.
820     }
821 
822     /***
823      * Implement this method if you wish to be notified when the User
824      * has been Unbound from the session.
825      *
826      * @param hsbe The HttpSessionBindingEvent.
827      */
828     public void valueUnbound(HttpSessionBindingEvent hsbe)
829     {
830         try
831         {
832             if (hasLoggedIn())
833             {
834                 TurbineSecurity.saveUser(this);
835             }
836         }
837         catch (Exception e)
838         {
839             log.error("BaseUser.valueUnbobund(): "
840                     + e.getMessage());
841             log.error(e);
842 
843             // To prevent messages being lost in case the logging system
844             // goes away before sessions get unbound on servlet container
845             // shutdown, print the stcktrace to the container's console.
846             ByteArrayOutputStream ostr = new ByteArrayOutputStream();
847 
848             e.printStackTrace(new PrintWriter(ostr, true));
849             String stackTrace = ostr.toString();
850 
851             System.out.println(stackTrace);
852         }
853     }
854 
855     /***
856      * Returns the username for this user.  If this is defined, then
857      * the user is considered logged in.
858      *
859      * @return A String with the username.
860      */
861     public String getName()
862     {
863         String tmp = null;
864 
865         tmp = (String) getPerm(User.USERNAME);
866         if (tmp != null && tmp.length() == 0)
867         {
868             tmp = null;
869         }
870         return tmp;
871     }
872 
873     /***
874      * Set the users name.
875      * @param name the name of the User.
876      */
877     public void setName(String name)
878     {
879 		setPerm(User.USERNAME, name);
880     }
881 
882     /***
883      * Not implemented.
884      * @return 0
885      */
886     public int getId()
887     {
888         return 0;
889     }
890             
891     /***
892      * Not implemented.
893      * @return null
894      */
895     public Integer getIdAsObj()
896     {
897         return new Integer(0);
898     }
899 
900     /***
901      * Not implemented.
902      *
903      * @param id The id of the User.
904      */
905     public void setId(int id)
906     {
907     }
908 
909     /***
910      * Saves this object to the data store.
911      * @throws Exception if it cannot be saved
912      */
913     public void save()
914             throws Exception
915     {
916         if (TurbineSecurity.accountExists(this))
917         {
918             TurbineSecurity.saveUser(this);
919         }
920         else
921         {
922             TurbineSecurity.addUser(this, getPassword());
923         }
924     }
925 
926     /***
927      * not implemented
928      *
929      * @param conn the database connection
930      * @throws Exception if there is an error
931      */
932     public void save(Connection conn) throws Exception
933     {
934         throw new Exception("not implemented");
935     }
936 
937     /***
938      * not implemented
939      *
940      * @param dbname the database name
941      * @throws Exception if there is an error
942      */
943     public void save(String dbname) throws Exception
944     {
945         throw new Exception("not implemented");
946     }
947 
948 }