View Javadoc
1   /*
2    * Copyright (c) 2002-2022, City of Paris
3    * All rights reserved.
4    *
5    * Redistribution and use in source and binary forms, with or without
6    * modification, are permitted provided that the following conditions
7    * are met:
8    *
9    *  1. Redistributions of source code must retain the above copyright notice
10   *     and the following disclaimer.
11   *
12   *  2. Redistributions in binary form must reproduce the above copyright notice
13   *     and the following disclaimer in the documentation and/or other materials
14   *     provided with the distribution.
15   *
16   *  3. Neither the name of 'Mairie de Paris' nor 'Lutece' nor the names of its
17   *     contributors may be used to endorse or promote products derived from
18   *     this software without specific prior written permission.
19   *
20   * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
21   * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
22   * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
23   * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDERS OR CONTRIBUTORS BE
24   * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
25   * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
26   * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
27   * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
28   * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
29   * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
30   * POSSIBILITY OF SUCH DAMAGE.
31   *
32   * License 1.0
33   */
34  package fr.paris.lutece.portal.business.user;
35  
36  import fr.paris.lutece.portal.business.rbac.RBACRole;
37  import fr.paris.lutece.portal.business.right.Right;
38  import fr.paris.lutece.portal.business.user.authentication.LuteceDefaultAdminUser;
39  import fr.paris.lutece.portal.service.spring.SpringContextService;
40  import fr.paris.lutece.portal.service.util.CryptoService;
41  import fr.paris.lutece.util.password.IPassword;
42  
43  import java.sql.Timestamp;
44  
45  import java.util.Collection;
46  import java.util.Date;
47  import java.util.List;
48  import java.util.Map;
49  
50  /**
51   * This class provides instances management methods (create, find, ...) for AdminUser objects
52   */
53  public final class AdminUserHome
54  {
55      // Static variable pointed at the DAO instance
56      private static IAdminUserDAO _dao = SpringContextService.getBean( "adminUserDAO" );
57  
58      /**
59       * Private constructor
60       */
61      private AdminUserHome( )
62      {
63      }
64  
65      /**
66       * Get the user infos from the access code.
67       * 
68       * @param strUserLogin
69       *            the login
70       * @return user info
71       */
72      public static AdminUser findUserByLogin( String strUserLogin )
73      {
74          return _dao.selectUserByAccessCode( strUserLogin );
75      }
76  
77      /**
78       * Get the user access code from its email.
79       * 
80       * @param strEmail
81       *            The email
82       * @return The access code of the user with the given email, or null if no user has been found
83       */
84      public static String findUserByEmail( String strEmail )
85      {
86          return _dao.selectUserByEmail( strEmail );
87      }
88  
89      /**
90       * Get the user infos from user id
91       * 
92       * @param nUserId
93       *            the user identifier
94       * @return The user
95       */
96      public static AdminUser findByPrimaryKey( int nUserId )
97      {
98          return _dao.load( nUserId );
99      }
100 
101     /**
102      * @return the user list
103      */
104     public static Collection<AdminUser> findUserList( )
105     {
106         return _dao.selectUserList( );
107     }
108 
109     /**
110      * @param user
111      *            The AdminUser
112      */
113     public static void create( AdminUser user )
114     {
115         _dao.insert( user );
116     }
117 
118     /**
119      * @param user
120      *            The AdminUser
121      */
122     public static void update( AdminUser user )
123     {
124         _dao.store( user );
125     }
126 
127     /**
128      * @param nUserId
129      *            the user identifier
130      */
131     public static void remove( int nUserId )
132     {
133         _dao.delete( nUserId );
134     }
135 
136     /**
137      * Get the right list associated to a given user id
138      * 
139      * @param nUserId
140      *            the id of the user to retrieve rights
141      * @return the right list
142      */
143     public static Map<String, Right> getRightsListForUser( int nUserId )
144     {
145         return _dao.selectRightsListForUser( nUserId );
146     }
147 
148     /**
149      * @param nUserId
150      *            The user identifier
151      * @param strRightId
152      *            The right identifier
153      */
154     public static void createRightForUser( int nUserId, String strRightId )
155     {
156         _dao.insertRightsListForUser( nUserId, strRightId );
157     }
158 
159     /**
160      * @param nUserId
161      *            The user identifier
162      */
163     public static void removeAllRightsForUser( int nUserId )
164     {
165         _dao.deleteAllRightsForUser( nUserId );
166     }
167 
168     /**
169      * @param user
170      *            The Admin User object
171      */
172     public static void removeAllDelegatedRightsForUser( AdminUser user )
173     {
174         _dao.deleteAllDelegatedRightsForUser( user.getUserId( ), user.getUserLevel( ) );
175     }
176 
177     /**
178      * @param user
179      *            The Admin User object
180      */
181     public static void removeAllOwnRightsForUser( AdminUser user )
182     {
183         _dao.deleteAllOwnRightsForUser( user.getUserId( ), user.getUserLevel( ) );
184     }
185 
186     /**
187      * Get the role list associated to a given user id
188      * 
189      * @param nUserId
190      *            the id of the user to retrieve rights
191      * @return the role list
192      */
193     public static Map<String, RBACRole> getRolesListForUser( int nUserId )
194     {
195         return _dao.selectRolesListForUser( nUserId );
196     }
197 
198     /**
199      * @param nUserId
200      *            the id of the user
201      * @param strRightId
202      *            the right identifier
203      */
204     public static void createRoleForUser( int nUserId, String strRightId )
205     {
206         _dao.insertRolesListForUser( nUserId, strRightId );
207     }
208 
209     /**
210      * @param nUserId
211      *            the user identifier
212      */
213     public static void removeAllRolesForUser( int nUserId )
214     {
215         _dao.deleteAllRolesForUser( nUserId );
216     }
217 
218     /**
219      * Checks wether the role is in use or not
220      * 
221      * @param strRoleKey
222      *            the role key to check
223      * @return true if the role is attributed, false otherwise
224      */
225     public static boolean checkRoleAttributed( String strRoleKey )
226     {
227         return _dao.checkRoleAttributed( strRoleKey );
228     }
229 
230     /**
231      * Checks if a given login is already in use
232      * 
233      * @param strAccessCode
234      *            The login
235      * @return user ID if the access code is already used by another user, -1 otherwise
236      */
237     public static int checkAccessCodeAlreadyInUse( String strAccessCode )
238     {
239         return _dao.checkAccessCodeAlreadyInUse( strAccessCode );
240     }
241 
242     /**
243      * Checks if a given email is already in use
244      * 
245      * @param strEmail
246      *            The email
247      * @return user ID if the email is already used by another user, -1 otherwise
248      */
249     public static int checkEmailAlreadyInUse( String strEmail )
250     {
251         return _dao.checkEmailAlreadyInUse( strEmail );
252     }
253 
254     /**
255      * Check if the user has the role
256      * 
257      * @param user
258      *            The AdminUser
259      * @param strRoleKey
260      *            The role Key
261      * @return true if the user has the role
262      */
263     public static boolean hasRole( AdminUser user, String strRoleKey )
264     {
265         return _dao.hasRole( user.getUserId( ), strRoleKey );
266     }
267 
268     /**
269      * Remove role for an user
270      * 
271      * @param nUserId
272      *            The ID of the user
273      * @param strRoleKey
274      *            The role key
275      */
276     public static void removeRoleForUser( int nUserId, String strRoleKey )
277     {
278         _dao.deleteRoleForUser( nUserId, strRoleKey );
279     }
280 
281     // ////////////////////////////////////////////////////////////////
282     // / for no-module mode
283 
284     /**
285      * @param user
286      *            the LuteceDefaultAdminUSer
287      */
288     public static void create( LuteceDefaultAdminUser user )
289     {
290         _dao.insert( user );
291     }
292 
293     /**
294      * @param user
295      *            the LuteceDefaultAdminUSer
296      */
297     public static void update( LuteceDefaultAdminUser user )
298     {
299         update( user, PasswordUpdateMode.UPDATE );
300     }
301 
302     /**
303      * @param user
304      *            the LuteceDefaultAdminUSer
305      * @param passwordMode
306      *            should the password be updated or not
307      */
308     public static void update( LuteceDefaultAdminUser user, PasswordUpdateMode passwordMode )
309     {
310         _dao.store( user, passwordMode );
311     }
312 
313     /**
314      * Get the user infos from user id
315      * 
316      * @param nUserId
317      *            the user identifier
318      * @return the delfault admin user
319      */
320     public static LuteceDefaultAdminUser findLuteceDefaultAdminUserByPrimaryKey( int nUserId )
321     {
322         return _dao.loadDefaultAdminUser( nUserId );
323     }
324 
325     /**
326      * Get all users having a given role
327      * 
328      * @param strRoleKey
329      *            The role key
330      * @return A collection of AdminUser
331      */
332     public static Collection<AdminUser> findByRole( String strRoleKey )
333     {
334         return _dao.selectUsersByRole( strRoleKey );
335     }
336 
337     /**
338      * Get all users having a given level
339      * 
340      * @param nIdLevel
341      *            The level
342      * @return A collection of AdminUser
343      */
344     public static Collection<AdminUser> findByLevel( int nIdLevel )
345     {
346         return _dao.selectUsersByLevel( nIdLevel );
347     }
348 
349     /**
350      * Update role key if role key name has change
351      * 
352      * @param strOldRoleKey
353      *            The old role key name
354      * @param role
355      *            The new role
356      */
357     public static void updateUsersRole( String strOldRoleKey, RBACRole role )
358     {
359         _dao.storeUsersRole( strOldRoleKey, role );
360     }
361 
362     /**
363      * Get all users by using a filter.
364      * 
365      * @param auFilter
366      *            The filter
367      * @return A collection of AdminUser
368      */
369     public static Collection<AdminUser> findUserByFilter( AdminUserFilter auFilter )
370     {
371         return _dao.selectUsersByFilter( auFilter );
372     }
373 
374     /**
375      * Get all users having a given right
376      * 
377      * @param strIdRight
378      *            The ID right
379      * @return A collection of AdminUser
380      */
381     public static Collection<AdminUser> findByRight( String strIdRight )
382     {
383         return _dao.selectUsersByRight( strIdRight );
384     }
385 
386     /**
387      * Check if the user has the given right
388      * 
389      * @param user
390      *            The Admin User
391      * @param strIdRight
392      *            The ID right
393      * @return true if the user has the right
394      */
395     public static boolean hasRight( AdminUser user, String strIdRight )
396     {
397         return _dao.hasRight( user.getUserId( ), strIdRight );
398     }
399 
400     /**
401      * Remove a right for an user
402      * 
403      * @param nUserId
404      *            The user ID
405      * @param strIdRight
406      *            The right ID
407      */
408     public static void removeRightForUser( int nUserId, String strIdRight )
409     {
410         _dao.deleteRightForUser( nUserId, strIdRight );
411     }
412 
413     /**
414      * Gets the history of password of the given user
415      * 
416      * @param nUserID
417      *            Id of the user
418      * @return The collection of recent passwords used by the user.
419      */
420     public static List<IPassword> selectUserPasswordHistory( int nUserID )
421     {
422         return _dao.selectUserPasswordHistory( nUserID );
423     }
424 
425     /**
426      * Get the number of password change done by a user since the given date.
427      * 
428      * @param minDate
429      *            Minimum date to consider.
430      * @param nUserId
431      *            Id of the user
432      * @return The number of password change done by the user since the given date.
433      */
434     public static int countUserPasswordHistoryFromDate( Timestamp minDate, int nUserId )
435     {
436         return _dao.countUserPasswordHistoryFromDate( minDate, nUserId );
437     }
438 
439     /**
440      * Log a password change in the password history
441      * 
442      * @param password
443      *            New password of the user
444      * @param nUserId
445      *            Id of the user
446      */
447     public static void insertNewPasswordInHistory( IPassword password, int nUserId )
448     {
449         _dao.insertNewPasswordInHistory( password, nUserId );
450     }
451 
452     /**
453      * Remove every password saved in the password history for a user.
454      * 
455      * @param nUserId
456      *            Id of the user
457      */
458     public static void removeAllPasswordHistoryForUser( int nUserId )
459     {
460         _dao.removeAllPasswordHistoryForUser( nUserId );
461     }
462 
463     /**
464      * Get a map of anonymization status of a user field.
465      * 
466      * @return A map containing the associations of user field name and a boolean describing whether the field should be anonymized.
467      */
468     public static Map<String, Boolean> getAnonymizationStatusUserStaticField( )
469     {
470         return _dao.selectAnonymizationStatusUserStaticField( );
471     }
472 
473     /**
474      * Update the anonymization status of a user field.
475      * 
476      * @param strFieldName
477      *            Name of the field to update
478      * @param bAnonymizeFiled
479      *            True if the field should be anonymize, false otherwise
480      */
481     public static void updateAnonymizationStatusUserStaticField( String strFieldName, boolean bAnonymizeFiled )
482     {
483         _dao.updateAnonymizationStatusUserStaticField( strFieldName, bAnonymizeFiled );
484     }
485 
486     /**
487      * Get the list of id of user with the expired status.
488      * 
489      * @return The list of if of user with the expired status.
490      */
491     public static List<Integer> findAllExpiredUserId( )
492     {
493         return _dao.findAllExpiredUserId( );
494     }
495 
496     /**
497      * Get the list of id of users that have an expired time life but not the expired status
498      * 
499      * @param currentTimestamp
500      *            Timestamp describing the current time.
501      * @return the list of id of users with expired time life
502      */
503     public static List<Integer> getIdUsersWithExpiredLifeTimeList( Timestamp currentTimestamp )
504     {
505         return _dao.getIdUsersWithExpiredLifeTimeList( currentTimestamp );
506     }
507 
508     /**
509      * Get the list of id of users that need to receive their first alert
510      * 
511      * @param firstAlertMaxDate
512      *            The maximum expiration date to send first alert.
513      * @return the list of id of users that need to receive their first alert
514      */
515     public static List<Integer> getIdUsersToSendFirstAlert( Timestamp firstAlertMaxDate )
516     {
517         return _dao.getIdUsersToSendFirstAlert( firstAlertMaxDate );
518     }
519 
520     /**
521      * Get the list of id of users that need to receive their first alert
522      * 
523      * @param alertMaxDate
524      *            The maximum date to send alerts.
525      * @param timeBetweenAlerts
526      *            Timestamp describing the time between two alerts.
527      * @param maxNumberAlerts
528      *            Maximum number of alerts to send to a user
529      * @return the list of id of users that need to receive their first alert
530      */
531     public static List<Integer> getIdUsersToSendOtherAlert( Timestamp alertMaxDate, Timestamp timeBetweenAlerts, int maxNumberAlerts )
532     {
533         return _dao.getIdUsersToSendOtherAlert( alertMaxDate, timeBetweenAlerts, maxNumberAlerts );
534     }
535 
536     /**
537      * Get the list of id of users that have an expired password but not the change password flag
538      * 
539      * @param currentTimestamp
540      *            Timestamp describing the current time.
541      * @return the list of id of users with expired passwords
542      */
543     public static List<Integer> getIdUsersWithExpiredPasswordsList( Timestamp currentTimestamp )
544     {
545         return _dao.getIdUsersWithExpiredPasswordsList( currentTimestamp );
546     }
547 
548     /**
549      * Update status of a list of user accounts
550      * 
551      * @param listIdUser
552      *            List of user accounts to update
553      * @param nNewStatus
554      *            New status of the user
555      */
556     public static void updateUserStatus( List<Integer> listIdUser, int nNewStatus )
557     {
558         _dao.updateUserStatus( listIdUser, nNewStatus );
559     }
560 
561     /**
562      * Increment the number of alert send to users by 1
563      * 
564      * @param listIdUser
565      *            The list of users to update
566      */
567     public static void updateNbAlert( List<Integer> listIdUser )
568     {
569         _dao.updateNbAlert( listIdUser );
570     }
571 
572     /**
573      * Set the "change password" flag of users to true
574      * 
575      * @param listIdUser
576      *            The list of users to update
577      */
578     public static void updateChangePassword( List<Integer> listIdUser )
579     {
580         _dao.updateChangePassword( listIdUser );
581     }
582 
583     /**
584      * Update the admin user expiration date with the new values. Also update his alert account to 0
585      * 
586      * @param nIdUser
587      *            Id of the admin user to update
588      * @param newExpirationDate
589      *            Id of the user to update
590      */
591     public static void updateUserExpirationDate( int nIdUser, Timestamp newExpirationDate )
592     {
593         _dao.updateUserExpirationDate( nIdUser, newExpirationDate );
594     }
595 
596     /**
597      * Update the admin user last login date.
598      * 
599      * @param nIdUser
600      *            Id of the admin user to update
601      * @param dateLastLogin
602      *            New last login date of the user
603      */
604     public static void updateDateLastLogin( int nIdUser, Timestamp dateLastLogin )
605     {
606         _dao.updateDateLastLogin( nIdUser, dateLastLogin );
607     }
608 
609     /**
610      * Construct a password reset token. Use the numerical userId as it does not change. Use the stored password, so that the token is invalidated if the
611      * password is changed. Use a timestamp to allow limiting the validity of the token in time. Optionally bind the token to the user session. Finally return
612      * an HMAC of this info using the application crypto key.
613      * 
614      * @param nIdUser
615      *            the user ID
616      * @param timestamp
617      *            the timestamp
618      * @param strSessionId
619      *            the session ID
620      * @return the password reset token
621      */
622     public static String getUserPasswordResetToken( int nIdUser, Date timestamp, String strSessionId )
623     {
624         LuteceDefaultAdminUser user = _dao.loadDefaultAdminUser( nIdUser );
625         StringBuilder builder = new StringBuilder( );
626         builder.append( "userId:" ).append( nIdUser );
627         IPassword password = user.getPassword( );
628         if ( password != null )
629         {
630             builder.append( ":password:" );
631             if ( password.isLegacy( ) )
632             {
633                 builder.append( "legacy" );
634             }
635             else
636             {
637                 builder.append( password.getStorableRepresentation( ) );
638             }
639         }
640         builder.append( ":timestamp:" ).append( timestamp.getTime( ) );
641         if ( strSessionId != null )
642         {
643             builder.append( ":sessionId:" ).append( strSessionId );
644         }
645         return CryptoService.hmacSHA256( builder.toString( ) );
646     }
647 }