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.service.daemon;
35  
36  import java.sql.Timestamp;
37  import java.text.DateFormat;
38  import java.util.Date;
39  import java.util.HashMap;
40  import java.util.List;
41  import java.util.Map;
42  
43  import org.apache.commons.collections.CollectionUtils;
44  import org.apache.commons.lang3.StringUtils;
45  
46  import fr.paris.lutece.portal.business.user.AdminUser;
47  import fr.paris.lutece.portal.business.user.AdminUserHome;
48  import fr.paris.lutece.portal.business.user.parameter.DefaultUserParameterHome;
49  import fr.paris.lutece.portal.service.admin.AdminUserService;
50  import fr.paris.lutece.portal.service.mail.MailService;
51  import fr.paris.lutece.portal.service.template.AppTemplateService;
52  import fr.paris.lutece.portal.service.template.DatabaseTemplateService;
53  import fr.paris.lutece.portal.service.util.AppLogService;
54  import fr.paris.lutece.portal.service.util.AppPropertiesService;
55  import fr.paris.lutece.portal.web.l10n.LocaleService;
56  import fr.paris.lutece.util.date.DateUtil;
57  import fr.paris.lutece.util.html.HtmlTemplate;
58  
59  /**
60   * Daemon to anonymize admin users
61   */
62  public class AccountLifeTimeDaemon extends Daemon
63  {
64      private static final String MESSAGE_DAEMON_NAME = "AccountLifeTimeDaemon - ";
65      private static final String MESSAGE_LOG_DAEMON_NAME = "AccountLifeTimeDaemon - {}";
66      private static final String MESSAGE_NO_TEXT = "No next alert to send";
67      private static final String MESSAGE_EXPIRED = "No expired passwords";
68      private static final String MESSAGE_NO_NOTIF = "Expired passwords notification deactivated, skipping";
69      private static final String MESSAGE_EXPIRED_USER = "No expired admin user found";
70      private static final String PARAMETER_TIME_BEFORE_ALERT_ACCOUNT = "time_before_alert_account";
71      private static final String PARAMETER_NB_ALERT_ACCOUNT = "nb_alert_account";
72      private static final String PARAMETER_TIME_BETWEEN_ALERTS_ACCOUNT = "time_between_alerts_account";
73      private static final String PARAMETER_NOTIFY_USER_PASSWORD_EXPIRED = "notify_user_password_expired";
74      private static final String PARAMETER_EXPIRED_ALERT_MAIL_SENDER = "expired_alert_mail_sender";
75      private static final String PARAMETER_EXPIRED_ALERT_MAIL_SUBJECT = "expired_alert_mail_subject";
76      private static final String PARAMETER_FIRST_ALERT_MAIL_SENDER = "first_alert_mail_sender";
77      private static final String PARAMETER_FIRST_ALERT_MAIL_SUBJECT = "first_aleDesactivart_mail_subject";
78      private static final String PARAMETER_OTHER_ALERT_MAIL_SENDER = "other_alert_mail_sender";
79      private static final String PARAMETER_OTHER_ALERT_MAIL_SUBJECT = "other_alert_mail_subject";
80      private static final String PARAMETER_PASSWORD_EXPIRED_MAIL_SENDER = "password_expired_mail_sender";
81      private static final String PARAMETER_PASSWORD_EXPIRED_MAIL_SUBJECT = "password_expired_mail_subject";
82      private static final String PARAMETER_CORE_EXPIRATION_MAIL = "core_expiration_mail";
83      private static final String PARAMETER_CORE_FIRST_ALERT_MAIL = "core_first_alert_mail";
84      private static final String PARAMETER_CORE_OTHER_ALERT_MAIL = "core_other_alert_mail";
85      private static final String PARAMETER_CORE_PASSWORD_EXPIRED_ALERT_MAIL = "core_password_expired";
86      private static final String MARK_LAST_NAME = "last_name";
87      private static final String MARK_FIRST_NAME = "first_name";
88      private static final String MARK_DATE_VALID = "date_valid";
89      private static final String MARK_URL = "url";
90      private static final String PROPERTY_PROD_URL = "init.webapp.prod.url";
91      private static final String JSP_URL_REACTIVATE_ACCOUNT = "/jsp/admin/user/ReactivateAccount.jsp";
92  
93      /**
94       * {@inheritDoc}
95       */
96      @Override
97      public void run( )
98      {
99          StringBuilder sbResult = new StringBuilder( );
100         Timestamp currentTimestamp = new Timestamp( new java.util.Date( ).getTime( ) );
101 
102         // We first set as expirated user that have reached their life time limit
103         runSetExpiredUser( currentTimestamp, sbResult );
104 
105         // We send first alert to users
106         runExpiringUserAlert( currentTimestamp, sbResult );
107 
108         // We send other alert to users
109         runOtherUserAlert( currentTimestamp, sbResult );
110 
111         // We notify users with expired passwords
112         runExpiredPassword( currentTimestamp, sbResult );
113 
114         setLastRunLogs( sbResult.toString( ) );
115     }
116 
117     private void runSetExpiredUser( Timestamp currentTimestamp, StringBuilder sbResult )
118     {
119         List<Integer> accountsToSetAsExpired = AdminUserHome.getIdUsersWithExpiredLifeTimeList( currentTimestamp );
120         if ( CollectionUtils.isNotEmpty( accountsToSetAsExpired ) )
121         {
122             int nbAccountToExpire = accountsToSetAsExpired.size( );
123             String strBody = DatabaseTemplateService.getTemplateFromKey( PARAMETER_CORE_EXPIRATION_MAIL );
124 
125             String defaultUserParameter = DefaultUserParameterHome.findByKey( PARAMETER_EXPIRED_ALERT_MAIL_SENDER );
126             String strSender = ( defaultUserParameter == null ) ? StringUtils.EMPTY : defaultUserParameter;
127 
128             defaultUserParameter = DefaultUserParameterHome.findByKey( PARAMETER_EXPIRED_ALERT_MAIL_SUBJECT );
129 
130             String strSubject = ( defaultUserParameter == null ) ? StringUtils.EMPTY : defaultUserParameter;
131 
132             sendMailAlerts( accountsToSetAsExpired, "expiration", strBody, strSender, strSubject );
133 
134             AdminUserHome.updateUserStatus( accountsToSetAsExpired, AdminUser.EXPIRED_CODE );
135 
136             StringBuilder sbLogs = new StringBuilder( );
137             sbLogs.append( MESSAGE_DAEMON_NAME );
138             sbLogs.append( Integer.toString( nbAccountToExpire ) );
139             sbLogs.append( " account(s) have expired" );
140             AppLogService.info( "runSetExpiredUser: {}", sbLogs );
141             sbResult.append( sbLogs.toString( ) );
142             sbResult.append( "\n" );
143         }
144         else
145         {
146             AppLogService.info( MESSAGE_LOG_DAEMON_NAME, MESSAGE_EXPIRED_USER );
147             sbResult.append( MESSAGE_DAEMON_NAME + MESSAGE_EXPIRED_USER );
148         }
149     }
150 
151     private void runExpiringUserAlert( Timestamp currentTimestamp, StringBuilder sbResult )
152     {
153         long nbDaysBeforeFirstAlert = AdminUserService.getIntegerSecurityParameter( PARAMETER_TIME_BEFORE_ALERT_ACCOUNT );
154 
155         if ( nbDaysBeforeFirstAlert <= 0 )
156         {
157             AppLogService.info( MESSAGE_LOG_DAEMON_NAME, MESSAGE_NO_NOTIF );
158             sbResult.append( MESSAGE_DAEMON_NAME + MESSAGE_NO_NOTIF );
159         }
160         else
161         {
162             Timestamp firstAlertMaxDate = new Timestamp( currentTimestamp.getTime( ) + DateUtil.convertDaysInMiliseconds( nbDaysBeforeFirstAlert ) );
163             List<Integer> userIdListToSendFirstAlert = AdminUserHome.getIdUsersToSendFirstAlert( firstAlertMaxDate );
164 
165             if ( CollectionUtils.isNotEmpty( userIdListToSendFirstAlert ) )
166             {
167                 int nbFirstAlertSent = userIdListToSendFirstAlert.size( );
168                 String strBody = DatabaseTemplateService.getTemplateFromKey( PARAMETER_CORE_FIRST_ALERT_MAIL );
169 
170                 String defaultUserParameter = DefaultUserParameterHome.findByKey( PARAMETER_FIRST_ALERT_MAIL_SENDER );
171                 String strSender = ( defaultUserParameter == null ) ? StringUtils.EMPTY : defaultUserParameter;
172 
173                 defaultUserParameter = DefaultUserParameterHome.findByKey( PARAMETER_FIRST_ALERT_MAIL_SUBJECT );
174 
175                 String strSubject = ( defaultUserParameter == null ) ? StringUtils.EMPTY : defaultUserParameter;
176 
177                 sendMailAlerts( userIdListToSendFirstAlert, "first", strBody, strSender, strSubject );
178 
179                 AdminUserHome.updateNbAlert( userIdListToSendFirstAlert );
180 
181                 StringBuilder sbLogs = new StringBuilder( );
182                 sbLogs.append( MESSAGE_DAEMON_NAME );
183                 sbLogs.append( Integer.toString( nbFirstAlertSent ) );
184                 sbLogs.append( " first alert(s) have been sent" );
185                 AppLogService.info( sbLogs );
186                 sbResult.append( sbLogs.toString( ) );
187                 sbResult.append( "\n" );
188             }
189             else
190             {
191                 AppLogService.info( "AccountLifeTimeDaemon - No first alert to send" );
192                 sbResult.append( "AccountLifeTimeDaemon - No first alert to send\n" );
193             }
194         }
195     }
196 
197     private void runOtherUserAlert( Timestamp currentTimestamp, StringBuilder sbResult )
198     {
199         int maxNumberOfAlerts = AdminUserService.getIntegerSecurityParameter( PARAMETER_NB_ALERT_ACCOUNT );
200         int nbDaysBetweenAlerts = AdminUserService.getIntegerSecurityParameter( PARAMETER_TIME_BETWEEN_ALERTS_ACCOUNT );
201         long nbDaysBeforeFirstAlert = AdminUserService.getIntegerSecurityParameter( PARAMETER_TIME_BEFORE_ALERT_ACCOUNT );
202         Timestamp timeBetweenAlerts = new Timestamp( DateUtil.convertDaysInMiliseconds( nbDaysBetweenAlerts ) );
203 
204         if ( ( maxNumberOfAlerts <= 0 ) || ( nbDaysBetweenAlerts <= 0 ) )
205         {
206             AppLogService.info( "AccountLifeTimeDaemon - Other alerts deactivated, skipping" );
207             sbResult.append( "AccountLifeTimeDaemon - Other alerts deactivated, skipping\n" );
208         }
209         else
210         {
211             Timestamp firstAlertMaxDate = new Timestamp( currentTimestamp.getTime( ) + DateUtil.convertDaysInMiliseconds( nbDaysBeforeFirstAlert ) );
212             List<Integer> userIdListToSendNextAlert = AdminUserHome.getIdUsersToSendOtherAlert( firstAlertMaxDate, timeBetweenAlerts, maxNumberOfAlerts );
213 
214             if ( CollectionUtils.isNotEmpty( userIdListToSendNextAlert ) )
215             {
216                 int nbOtherAlertSent = userIdListToSendNextAlert.size( );
217                 String strBody = DatabaseTemplateService.getTemplateFromKey( PARAMETER_CORE_OTHER_ALERT_MAIL );
218 
219                 String defaultUserParameter = DefaultUserParameterHome.findByKey( PARAMETER_OTHER_ALERT_MAIL_SENDER );
220                 String strSender = ( defaultUserParameter == null ) ? StringUtils.EMPTY : defaultUserParameter;
221 
222                 defaultUserParameter = DefaultUserParameterHome.findByKey( PARAMETER_OTHER_ALERT_MAIL_SUBJECT );
223 
224                 String strSubject = ( defaultUserParameter == null ) ? StringUtils.EMPTY : defaultUserParameter;
225 
226                 sendMailAlerts( userIdListToSendNextAlert, "next", strBody, strSender, strSubject );
227 
228                 AdminUserHome.updateNbAlert( userIdListToSendNextAlert );
229 
230                 StringBuilder sbLogs = new StringBuilder( );
231                 sbLogs.append( MESSAGE_DAEMON_NAME );
232                 sbLogs.append( Integer.toString( nbOtherAlertSent ) );
233                 sbLogs.append( " next alert(s) have been sent" );
234                 AppLogService.info( sbLogs );
235                 sbResult.append( sbLogs.toString( ) );
236             }
237             else
238             {
239                 AppLogService.info( MESSAGE_LOG_DAEMON_NAME, MESSAGE_NO_TEXT );
240                 sbResult.append( MESSAGE_DAEMON_NAME + MESSAGE_NO_TEXT );
241             }
242         }
243     }
244 
245     private void runExpiredPassword( Timestamp currentTimestamp, StringBuilder sbResult )
246     {
247         if ( AdminUserService.getBooleanSecurityParameter( PARAMETER_NOTIFY_USER_PASSWORD_EXPIRED ) )
248         {
249             // We notify users with expired passwords
250             List<Integer> accountsWithPasswordsExpired = AdminUserHome.getIdUsersWithExpiredPasswordsList( currentTimestamp );
251 
252             if ( CollectionUtils.isNotEmpty( accountsWithPasswordsExpired ) )
253             {
254                 String strSender = AdminUserService.getSecurityParameter( PARAMETER_PASSWORD_EXPIRED_MAIL_SENDER );
255                 String strSubject = AdminUserService.getSecurityParameter( PARAMETER_PASSWORD_EXPIRED_MAIL_SUBJECT );
256                 String strBody = DatabaseTemplateService.getTemplateFromKey( PARAMETER_CORE_PASSWORD_EXPIRED_ALERT_MAIL );
257 
258                 if ( StringUtils.isNotBlank( strBody ) )
259                 {
260                     sendMailAlerts( accountsWithPasswordsExpired, "password expiration", strBody, strSender, strSubject );
261                 }
262 
263                 AdminUserHome.updateChangePassword( accountsWithPasswordsExpired );
264                 StringBuilder sbLogs = new StringBuilder( );
265                 sbLogs.append( MESSAGE_DAEMON_NAME );
266                 sbLogs.append( Integer.toString( accountsWithPasswordsExpired.size( ) ) );
267                 sbLogs.append( " user(s) have been notified their password has expired" );
268                 AppLogService.info( sbLogs );
269                 sbResult.append( sbLogs.toString( ) );
270                 sbResult.append( "\n" );
271             }
272             else
273             {
274                 AppLogService.info( MESSAGE_LOG_DAEMON_NAME, MESSAGE_EXPIRED );
275                 sbResult.append( MESSAGE_DAEMON_NAME + MESSAGE_EXPIRED );
276             }
277         }
278         else
279         {
280             AppLogService.info( MESSAGE_LOG_DAEMON_NAME, MESSAGE_NO_NOTIF );
281             sbResult.append( MESSAGE_DAEMON_NAME + MESSAGE_NO_NOTIF );
282         }
283     }
284 
285     private void sendMailAlerts( List<Integer> userIdList, String type, String strBody, String strSender, String strSubject )
286     {
287         for ( Integer nIdUser : userIdList )
288         {
289             try
290             {
291                 AdminUser user = AdminUserHome.findByPrimaryKey( nIdUser );
292                 String strUserMail = user.getEmail( );
293 
294                 if ( StringUtils.isNotBlank( strUserMail ) )
295                 {
296                     Map<String, String> model = new HashMap<>( );
297                     addParametersToModel( model, nIdUser );
298 
299                     HtmlTemplate template = AppTemplateService.getTemplateFromStringFtl( strBody, user.getLocale( ), model );
300                     MailService.sendMailHtml( strUserMail, strSender, strSender, strSubject, template.getHtml( ) );
301                 }
302             }
303             catch( Exception e )
304             {
305                 AppLogService.error( "AccountLifeTimeDaemon - Error sending {} alert to admin user : {}", type, e.getMessage( ), e );
306             }
307         }
308     }
309 
310     /**
311      * Adds the parameters to model.
312      *
313      * @param model
314      *            the model
315      * @param nIdUser
316      *            the n id user
317      */
318     protected void addParametersToModel( Map<String, String> model, Integer nIdUser )
319     {
320         AdminUser user = AdminUserHome.findByPrimaryKey( nIdUser );
321 
322         if ( user.getAccountMaxValidDate( ) != null )
323         {
324             DateFormat dateFormat = DateFormat.getDateInstance( DateFormat.SHORT, LocaleService.getDefault( ) );
325 
326             String accountMaxValidDate = dateFormat.format( new Date( user.getAccountMaxValidDate( ).getTime( ) ) );
327 
328             String activationURL = AppPropertiesService.getProperty( PROPERTY_PROD_URL ) + JSP_URL_REACTIVATE_ACCOUNT;
329 
330             model.put( MARK_DATE_VALID, accountMaxValidDate );
331             model.put( MARK_URL, activationURL );
332         }
333 
334         model.put( MARK_LAST_NAME, user.getLastName( ) );
335         model.put( MARK_FIRST_NAME, user.getFirstName( ) );
336     }
337 }