KickJava   Java API By Example, From Geeks To Geeks.

Java > Open Source Codes > org > jahia > services > usermanager > JahiaLDAPUser


1 //
2
// ____.
3
// __/\ ______| |__/\. _______
4
// __ .____| | \ | +----+ \
5
// _______| /--| | | - \ _ | : - \_________
6
// \\______: :---| : : | : | \________>
7
// |__\---\_____________:______: :____|____:_____\
8
// /_____|
9
//
10
// . . . i n j a h i a w e t r u s t . . .
11
//
12
//
13

14 package org.jahia.services.usermanager;
15
16 import org.jahia.exceptions.JahiaException;
17 import org.jahia.exceptions.database.JahiaDatabaseConnectionException;
18 import org.jahia.exceptions.database.JahiaDatabaseException;
19 import org.jahia.registries.ServicesRegistry;
20
21 import java.security.Principal JavaDoc;
22 import java.util.Enumeration JavaDoc;
23 import java.util.Properties JavaDoc;
24 import java.util.StringTokenizer JavaDoc;
25 import java.util.Vector JavaDoc;
26 import java.io.Serializable JavaDoc;
27 import java.util.Iterator JavaDoc;
28
29 /**
30  * A JahiaUser represents a physical person who is defined by a username and
31  * a password for authentification purpose. Every other property of a JahiaUser
32  * is stored in it's properties list, which hold key-value string pairs.
33  * For example email, firstname, lastname, ... information should be stored in
34  * this properties list.
35  *
36  * @author Serge Huber
37  * @version 1.0
38  */

39 public class JahiaLDAPUser implements JahiaUser, Serializable JavaDoc {
40     private static org.apache.log4j.Logger logger =
41             org.apache.log4j.Logger.getLogger (JahiaLDAPUser.class);
42
43     static final public String JavaDoc USERKEY_LDAP_PREFIX = "{ldap}";
44
45     /** User unique identification number in the database. */
46     private int mID;
47
48     /** User unique identification name */
49     private String JavaDoc mUsername;
50
51     /** User password */
52     private String JavaDoc mPassword;
53
54     /** Each user has an unique String identifier * */
55     private String JavaDoc mUserKey;
56
57     /** Site id , the owner of this user */
58     private int mSiteID = -1;
59
60     /** DN in ldap repository **/
61     private String JavaDoc mDn;
62
63     /** groups **/
64     private Vector JavaDoc mGroups;
65
66     /** User additional parameters. */
67     private UserProperties mProperties = new UserProperties ();
68
69     /** User home page property * */
70     private static final String JavaDoc mHOMEPAGE_PROP = "user_homepage";
71
72     // language property constants
73
private static final String JavaDoc mLANGUAGES_ORDER_PROP = "language_codes";
74     private static final String JavaDoc mLANGUAGES_ORDER_PROP_SEPARATOR = ",";
75     private static final String JavaDoc mLANGUAGES_MIX_PROP = "langage_mix";
76     private static final String JavaDoc mLANGUAGES_ONLYUSER_PROP = "language_onlyuser";
77
78     /**
79      * Create a new JahiaDBUser class instance. The passed in password must
80      * already be encrypted, no ecryption will be done. If the passed in
81      * properties is null, then the user will have no additional parameter than
82      * it's id, name and password.
83      *
84      * @param id User unique identification number.
85      * @param name User identification name.
86      * @param password User password.
87      * @param int siteID
88      * The site id
89      * @param properties User properties.
90      */

91     protected JahiaLDAPUser (int id, String JavaDoc name, String JavaDoc password,
92                              String JavaDoc userKey, int siteID,
93                            UserProperties properties, String JavaDoc dn)
94     {
95         mID = id;
96         mUsername = name;
97         mPassword = password;
98         mUserKey = USERKEY_LDAP_PREFIX + userKey;
99         mSiteID = siteID;
100         mDn = dn;
101         if (properties != null) {
102             mProperties = properties;
103         }
104     }
105
106
107     public boolean equals (Object JavaDoc another) {
108         if (another instanceof Principal JavaDoc) {
109             if (another != null) {
110                 if (mUsername == null) {
111                     logger.debug (
112                             "Username for user key [" + mUserKey + "] is null , please check your users.ldap.properties mapping file !");
113                     if (((Principal JavaDoc) another).getName () == null) {
114                         return true;
115                     } else {
116                         return false;
117                     }
118                 }
119                 return (getName ().equals (((Principal JavaDoc) another).getName ()));
120             }
121         }
122         return false;
123     }
124
125
126     /**
127      * Retrieve the user's unique database identification number.
128      *
129      * @return The user unique identification number.
130      */

131     public int getID () {
132         return mID;
133     }
134
135
136     public String JavaDoc getName () {
137         return getUserKey ();
138     }
139
140     public String JavaDoc getUsername () {
141         return mUsername;
142     }
143
144     public String JavaDoc getUserKey () {
145         return mUserKey;
146     }
147
148     public int getSiteID () {
149         return mSiteID;
150     }
151
152     public void setSiteID (int siteID) {
153         mSiteID = siteID;
154     }
155
156     public String JavaDoc getDN() {
157         return mDn;
158     }
159
160     /**
161      * @deprecated use getUserProperties() instead
162      * @return Properties the properties returned here should NEVER be modified,
163      * only modifications through setProperty() are supported and serialized.
164      */

165     public Properties JavaDoc getProperties () {
166         if (mProperties != null) {
167             return mProperties.getProperties();
168         } else {
169             return null;
170         }
171     }
172
173     /**
174      * The properties here should not be modified, as the modifications will
175      * not be serialized. Use the setProperty() method to modify a user's
176      * properties.
177      * @return UserProperties
178      */

179     public UserProperties getUserProperties() {
180         return mProperties;
181     }
182
183     //
184
public String JavaDoc getProperty (String JavaDoc key) {
185
186         if ((mProperties != null) && (key != null)) {
187             return mProperties.getProperty (key);
188         }
189         return null;
190     }
191
192     public UserProperty getUserProperty(String JavaDoc key) {
193         if ((mProperties != null) && (key != null)) {
194             return mProperties.getUserProperty (key);
195         }
196         return null;
197     }
198
199
200     /**
201      * Return a unique hashcode identifiying the user.
202      *
203      * @return Return a valid hashcode integer of the user, On failure, -1 is
204      * returned.
205      */

206     public int hashCode () {
207         return mID;
208     }
209
210
211     /**
212      * Remove the specified property from the properties list.
213      *
214      * @param key Property's name.
215      *
216      * @return Return true on success or false on any failure.
217      *
218      * @todo FIXME : not supported in this read-only implementation
219      */

220     public synchronized boolean removeProperty (String JavaDoc key) {
221         boolean result = false;
222         if (mProperties == null) {
223             return result;
224         }
225
226         if ((key != null) && (key.length () > 0) && (!mProperties.isReadOnly(key))) {
227             // Remove these lines if LDAP problem --------------------
228
JahiaUserDBUtils utils = JahiaUserDBUtils.getInstance ();
229             if (utils != null) {
230                 try {
231                     result = utils.removeProperty (key, -1, getProviderName (), getUserKey ());
232                 }
233                         // general database exeception
234
catch (JahiaDatabaseException ex) {
235                     // false will be returned automaticaly
236
}
237
238                         // database connection failure
239
catch (JahiaDatabaseConnectionException ex) {
240                     // false will be returned automaticaly
241
}
242
243                         // catch all the Jahia exceptions
244
catch (JahiaException ex) {
245                     // false will be returned automaticaly
246
}
247             }
248             // End remove --------------------
249
}
250         //Predrag
251
if (result) {
252             mProperties.removeUserProperty (key);
253         }
254         //Predrag
255
return result;
256     }
257
258     public synchronized boolean isPasswordReadOnly() {
259         return true;
260     }
261
262     /**
263      * Change the user's password.
264      *
265      * @param newPassword New user's password
266      *
267      * @return Return true id the old password is the same as the current one and
268      * the new password is valid. Return false on any failure.
269      *
270      * @todo FIXME : not supported in this read-only LDAP implementation
271      */

272     public synchronized boolean setPassword (String JavaDoc password) {
273         boolean result = false;
274
275         return result;
276     }
277
278
279     /**
280      * Add (or update if not already in the property list) a property key-value
281      * pair in the user's properties list.
282      *
283      * @param key Property's name.
284      * @param value Property's value.
285      *
286      * @return Return true on success or false on any failure.
287      *
288      * @todo FIXME : not supported in LDAP implementation, only sets internal
289      * values in memory.
290      * @todo FIXME : These following lines are a quick hack to permit to store
291      * user properties for readonly LDAP users. A better solution would be to
292      * create a service that is in charge of managing user properties.
293      */

294     public synchronized boolean setProperty (String JavaDoc key, String JavaDoc value) {
295         boolean result = false;
296         if (mProperties == null) {
297             return result;
298         }
299
300         if ((key != null) && (value != null) && (!mProperties.isReadOnly(key))) {
301             // Remove these lines if LDAP problem --------------------
302
JahiaUserDBUtils utils = JahiaUserDBUtils.getInstance ();
303             if (utils != null) {
304                 try {
305                     if (getProperty (key) == null) {
306                         result =
307                                 utils.addProperty (key, value, -1, getProviderName (),
308                                         getUserKey ());
309                     } else {
310                         result =
311                                 utils.updateProperty (key, value, -1, getProviderName (),
312                                         getUserKey ());
313                     }
314                 }
315                         // general database exeception
316
catch (JahiaDatabaseException ex) {
317                     // false will be returned automaticaly
318
logger.error("Error setting property " + key + " with value " + value + " for user " + getUserKey(), ex);
319                 }
320
321                         // database connection failure
322
catch (JahiaDatabaseConnectionException ex) {
323                     // false will be returned automaticaly
324
logger.error("Error setting property " + key + " with value " + value + " for user " + getUserKey(), ex);
325                 }
326
327                         // catch all the Jahia exceptions
328
catch (JahiaException ex) {
329                     // false will be returned automaticaly
330
}
331             }
332             // End remove --------------------
333
if (result) {
334                 try {
335                     mProperties.setProperty(key, value);
336                 } catch (UserPropertyReadOnlyException uproe) {
337                     logger.warn("Cannot set read-only property " + key);
338                 }
339                 ServicesRegistry.getInstance().getJahiaUserManagerService().updateCache(this);
340             }
341         }
342         return result;
343     }
344
345     //-------------------------------------------------------------------------
346
/**
347      * Returns the user's home page id.
348      * -1 : undefined
349      *
350      * @return int The user homepage id.
351      */

352     public int getHomepageID () {
353
354         if (mProperties != null) {
355
356             try {
357                 // Get the home page from the Jahia DB.
358
// By default an external user is represented with a -1 user ID.
359
String JavaDoc value = mProperties.getProperty (mHOMEPAGE_PROP);
360                 if (value == null) {
361                     return -1;
362                 }
363                 return Integer.parseInt (value);
364             } catch (Throwable JavaDoc t) {
365                 t.printStackTrace ();
366             }
367         }
368         return -1;
369     }
370
371     //-------------------------------------------------------------------------
372
/**
373      * Set the home page id.
374      *
375      * @param int The user homepage id.
376      *
377      * @return false on error
378      */

379     public boolean setHomepageID (int id) {
380
381         if (!removeProperty (mHOMEPAGE_PROP))
382             return false;
383         // Set the home page into the Jahia DB.
384
// By default an external user is represented with a -1 user ID.
385
return setProperty (mHOMEPAGE_PROP, String.valueOf (id));
386     }
387
388     public Vector JavaDoc getGroups() {
389         return mGroups;
390     }
391
392     public void setGroups(Vector JavaDoc mGroups) {
393         this.mGroups = mGroups;
394     }
395
396     public boolean verifyPassword(String JavaDoc password) {
397
398         if (password != null) {
399             boolean localLoginResult = false;
400
401             if (mPassword.length() > 0) {
402                 String JavaDoc test = JahiaUserManagerService.encryptPassword(password);
403                 localLoginResult = mPassword.equals(test);
404             }
405             // test the provided password with the internal memory encrypted
406
// password.
407
if (localLoginResult) {
408                 // both passwords match.
409
return true;
410             } else {
411                 // the local encrypted password does not match the one in
412
// parameter
413
// forward to the ldap authN in case of there was a ldap
414
// password change from the last user's visit.
415
boolean loginResult = JahiaUserManagerLDAPProvider.getInstance().login(mUserKey, password);
416                 if (loginResult) {
417                     /**
418                      * @todo here we must now update the properties of the user
419                      * since he has access to more of his attributes once
420                      * logged in
421                      */

422                     mPassword = JahiaUserManagerService.encryptPassword(password);
423                     return true;
424                 }
425                 /** @todo insert here LDAP connection check... */
426
427             }
428         }
429         return false;
430     }
431
432
433     /**
434      * Return a string representation of the user and it's internal state.
435      *
436      * @return A string representation of this user.
437      */

438     public String JavaDoc toString () {
439         StringBuffer JavaDoc output = new StringBuffer JavaDoc ("Detail of user [" + mUsername + "]\n");
440         output.append (" - ID [" + Integer.toString (mID) + "]");
441         output.append (" - password [" + mPassword + "]\n");
442
443         if (mProperties != null) {
444             output.append(" - properties :");
445
446             Iterator JavaDoc nameIter = mProperties.propertyNameIterator();
447             String JavaDoc name;
448             if (nameIter.hasNext()) {
449                 output.append("\n");
450                 while (nameIter.hasNext()) {
451                     name = (String JavaDoc) nameIter.next();
452                     output.append(
453                         " " + name + " -> [" +
454                         (String JavaDoc) mProperties.getProperty(name) + "]\n");
455                 }
456             } else {
457                 output.append(" -no properties-\n");
458             }
459         }
460         return output.toString ();
461     }
462
463
464     /**
465      * Test if the user is an admin member
466      *
467      * @return Return true if the user is an admin member
468      * false on any error.
469      */

470     public boolean isAdminMember (int siteID) {
471
472         return isMemberOfGroup (siteID, JahiaGroupManagerService.ADMINISTRATORS_GROUPNAME);
473     }
474
475     /**
476      * Test if the user is the root user
477      *
478      * @return Return true if the user is the root user
479      * false on any error.
480      */

481     public boolean isRoot () {
482         /** @todo FIXME in this implementation the super user is necessarily
483          * always in the jahia database implementation
484          */

485         return false;
486     }
487
488
489     //-------------------------------------------------------------------------
490
public boolean isMemberOfGroup (int siteID, String JavaDoc name) {
491         // Get the services registry
492
ServicesRegistry servicesRegistry = ServicesRegistry.getInstance ();
493         if (servicesRegistry != null) {
494
495             // get the group management service
496
JahiaGroupManagerService groupService =
497                     servicesRegistry.getJahiaGroupManagerService ();
498
499             // lookup the requested group
500
JahiaGroup group = groupService.lookupGroup (siteID, name);
501             if (group != null) {
502                 return group.isMember (this);
503             }
504         }
505         return false;
506     }
507
508     /**
509      * Retrieve a vector of language codes stored for this user. The order
510      * of these codes is important. The first language is the first choice, and
511      * as the list goes down so does the importance of the languages.
512      *
513      * @return a Vector containing String objects that contain language codes,
514      * the vector may be empty if this property was never set for the user.
515      */

516     public Vector JavaDoc getLanguageCodes () {
517         String JavaDoc encodedLanguagesCodes = getProperty (mLANGUAGES_ORDER_PROP);
518         Vector JavaDoc result = new Vector JavaDoc ();
519         if (encodedLanguagesCodes != null) {
520             StringTokenizer JavaDoc strTokens = new StringTokenizer JavaDoc (encodedLanguagesCodes,
521                     mLANGUAGES_ORDER_PROP_SEPARATOR);
522             while (strTokens.hasMoreTokens ()) {
523                 String JavaDoc curLanguageCode = strTokens.nextToken ();
524                 result.add (curLanguageCode);
525             }
526         }
527         return result;
528     }
529
530     /**
531      * Sets the language codes for a user. This Vector contains String object
532      * that contain language codes. The order of this list is defined so as that
533      * the most important language is first.
534      *
535      * @param userLanguages a Vector of String object containing the language
536      * codes. The order is from the most important language first to the least
537      * important one last.
538      */

539     public void setLanguageCodes (Vector JavaDoc userLanguages) {
540         StringBuffer JavaDoc encodedLanguageCodes = new StringBuffer JavaDoc ();
541         Enumeration JavaDoc userLanguagesEnum = userLanguages.elements ();
542         while (userLanguagesEnum.hasMoreElements ()) {
543             String JavaDoc curLanguage = (String JavaDoc) userLanguagesEnum.nextElement ();
544             if (curLanguage.indexOf (mLANGUAGES_ORDER_PROP_SEPARATOR) != 0) {
545                 // we found the separator character inside the string.
546
logger.debug ("Invalid " + mLANGUAGES_ORDER_PROP_SEPARATOR +
547                         " character in language code : " + curLanguage +
548                         ". Not storing this language code.");
549             } else {
550                 encodedLanguageCodes.append (curLanguage);
551                 encodedLanguageCodes.append (mLANGUAGES_ORDER_PROP_SEPARATOR);
552             }
553         }
554         String JavaDoc encodedLanguageCodeStr = encodedLanguageCodes.toString ();
555         // we must now remove the extra separator at the end of the encoded list
556
encodedLanguageCodeStr =
557                 encodedLanguageCodeStr.substring (0, encodedLanguageCodeStr.length () - 1);
558         setProperty (mLANGUAGES_ORDER_PROP, encodedLanguageCodeStr);
559     }
560
561     /**
562      * Returns true if this user has activated the language mixing function
563      * of Jahia. This means that the content that will be displayed on his
564      * page will content multiple languages based on language preference list.
565      *
566      * @return true if the property is active.
567      */

568     public boolean isMixLanguagesActive () {
569         String JavaDoc mixActiveStr = getProperty (mLANGUAGES_MIX_PROP);
570         if (mixActiveStr != null) {
571             Boolean JavaDoc mixActiveBool = Boolean.valueOf (mixActiveStr);
572             return mixActiveBool.booleanValue ();
573         } else {
574             logger.debug (mLANGUAGES_MIX_PROP +
575                     " property not found for user " +
576                     this.getUsername () +
577                     ". Defaulting to false.");
578             return false;
579         }
580     }
581
582     /**
583      * Sets the user property that indicates whether the user wants to see
584      * mixed language content in the pages he is browsing or not.
585      *
586      * @param mixLanguagesActive a boolean set to true to allow language mixing
587      */

588     public void setMixLanguagesActive (boolean mixLanguagesActive) {
589         setProperty (mLANGUAGES_MIX_PROP,
590                 new Boolean JavaDoc (mixLanguagesActive).toString ());
591     }
592
593     /**
594      * Returns true if the user has setup this property indicating that he
595      * doesn't want to default to any other languages than the ones he has
596      * setup in his users settings. This will shortcut defaulting to the
597      * browser and site settings.
598      *
599      * @return true if the user only wants to see the languages he has configured
600      * and never the ones configured in his browser or in the site settings.
601      */

602     public boolean isUserLanguagesOnlyActive () {
603         String JavaDoc userLanguagesOnlyStr = getProperty (mLANGUAGES_ONLYUSER_PROP);
604         if (userLanguagesOnlyStr != null) {
605             Boolean JavaDoc userLanguagesOnlyBool = Boolean.valueOf (userLanguagesOnlyStr);
606             return userLanguagesOnlyBool.booleanValue ();
607         } else {
608             logger.debug (mLANGUAGES_ONLYUSER_PROP +
609                     " property not found for user " +
610                     this.getUsername () +
611                     ". Defaulting to false.");
612             return false;
613         }
614
615     }
616
617     /**
618      * Sets the value indicating whether a user wants to fallback to browser
619      * or site setting languages. If set to true this means we are NOT falling
620      * back to the above mentioned settings.
621      *
622      * @param userLanguagesOnlyActive true means we are not falling back to
623      * browser or site settings.
624      */

625     public void setUserLanguagesOnlyActive (boolean userLanguagesOnlyActive) {
626         setProperty (mLANGUAGES_ONLYUSER_PROP,
627                 new Boolean JavaDoc (userLanguagesOnlyActive).toString ());
628
629     }
630
631     /**
632      * Get the name of the provider of this user.
633      *
634      * @return String representation of the name of the provider of this user
635      */

636     public String JavaDoc getProviderName () {
637         return JahiaUserManagerLDAPProvider.PROVIDER_NAME;
638     }
639
640 }
641
Popular Tags