View Javadoc
1   /*
2    * Copyright (c) 2002-2024, 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.plugins.identitystore.service;
35  
36  import static fr.paris.lutece.plugins.identitystore.service.identity.IdentityService.UPDATE_IDENTITY_EVENT_CODE;
37  
38  import java.sql.Timestamp;
39  import java.time.Instant;
40  import java.time.ZoneId;
41  import java.time.ZonedDateTime;
42  import java.util.ArrayList;
43  import java.util.Collections;
44  import java.util.List;
45  
46  import org.apache.commons.lang3.StringUtils;
47  
48  import fr.paris.lutece.plugins.grubusiness.business.demand.DemandType;
49  import fr.paris.lutece.plugins.grubusiness.business.web.rs.DemandDisplay;
50  import fr.paris.lutece.plugins.grubusiness.business.web.rs.DemandResult;
51  import fr.paris.lutece.plugins.grubusiness.business.web.rs.EnumGenericStatus;
52  import fr.paris.lutece.plugins.identitystore.business.identity.Identity;
53  import fr.paris.lutece.plugins.identitystore.business.identity.IdentityHome;
54  import fr.paris.lutece.plugins.identitystore.service.contract.ServiceContractService;
55  import fr.paris.lutece.plugins.identitystore.service.identity.IdentityService;
56  import fr.paris.lutece.plugins.identitystore.service.listeners.IdentityStoreNotifyListenerService;
57  import fr.paris.lutece.plugins.identitystore.service.user.InternalUserService;
58  import fr.paris.lutece.plugins.identitystore.v3.web.rs.dto.common.RequestAuthor;
59  import fr.paris.lutece.plugins.identitystore.v3.web.rs.dto.history.IdentityChangeType;
60  import fr.paris.lutece.plugins.notificationstore.v1.web.service.NotificationStoreService;
61  import fr.paris.lutece.portal.service.security.AccessLogService;
62  import fr.paris.lutece.portal.service.security.AccessLoggerConstants;
63  import fr.paris.lutece.portal.service.spring.SpringContextService;
64  import fr.paris.lutece.portal.service.util.AppPropertiesService;
65  
66  public final class PurgeIdentityService
67  {
68      private static PurgeIdentityService _instance;
69  
70      private final NotificationStoreService _notificationStoreService = SpringContextService.getBean( "notificationStore.notificationStoreService" );
71     
72      public static PurgeIdentityService getInstance( )
73      {
74          if ( _instance == null )
75          {
76              _instance = new PurgeIdentityService( );
77          }
78          return _instance;
79      }
80  
81      /**
82       * purge identities
83       *
84       * @return log {@link StringBuilder}
85       */
86      public String purge( final RequestAuthor daemonAuthor, final String daemonClientCode, final List<String> excludedAppCodes, final int batchLimit )
87      {
88          final StringBuilder msg = new StringBuilder( );
89  
90          // search identities with a passed peremption date, not merged to a primary identity, and not associated to a MonParis account
91          final List<Identity> expiredIdentities = IdentityHome.findExpiredNotMergedAndNotConnectedIdentities( 
92          	batchLimit, AppPropertiesService.getPropertyBoolean ( "daemon.purgeIdentityDaemon.withGuidOnly", true) );
93          final Timestamp now = Timestamp.from( Instant.now( ) );
94  
95          msg.append( expiredIdentities.size( ) ).append( " expired identities found" ).append( "\n" );
96  
97          for ( final Identity expiredIdentity : expiredIdentities )
98          {
99              try
100             {
101                 final List<Identity> mergedIdentities = IdentityHome.findMergedIdentities( expiredIdentity.getId( ) );
102                 // - check if exists recent Demands associated to each identity or its merged ones
103                 // >> if true, calculate the new expiration date (date of demand last update + CGUs term)
104                 DemandResult demandResult = _notificationStoreService.getListDemand( expiredIdentity.getCustomerId( ), null, null, null, null );
105                 final List<DemandDisplay> demandDisplayList = demandResult.getListDemandDisplay() == null ? new ArrayList<>() : new ArrayList<>(demandResult.getListDemandDisplay());
106                 for ( final Identity mergedIdentity : mergedIdentities )
107                 {
108                     demandDisplayList
109                             .addAll( _notificationStoreService.getListDemand( mergedIdentity.getCustomerId( ), null, null, null, null ).getListDemandDisplay( ) );
110                 }
111 
112                 Timestamp demandExpirationDateMAX = expiredIdentity.getExpirationDate( );
113                 for ( final DemandDisplay demand : demandDisplayList )
114                 {
115                     if (demand.getDemand().getStatusId() == EnumGenericStatus.CANCELED.getStatusId()) {
116                         continue;
117                     }
118                     final String appCode = getAppCodeFromDemandTypeId( demand.getDemand( ).getTypeId( ) );
119                     if ( !excludedAppCodes.contains( appCode ) )
120                     {
121                         final List<String> clientCodeList = ServiceContractService.instance( ).getClientCodesFromAppCode( appCode );
122 
123                         int nbMonthsCGUsMAX = 0;
124                         for ( final String clientCode : clientCodeList )
125                         {
126                             // if there is more than one client code for the app_code, keep the max value of cgus
127                             int nbMonthsCGUs = ServiceContractService.instance( ).getDataRetentionPeriodInMonths( clientCode );
128                             if ( nbMonthsCGUs > nbMonthsCGUsMAX )
129                             {
130                                 nbMonthsCGUsMAX = nbMonthsCGUs;
131                             }
132                         }
133 
134                         final ZonedDateTime demandDate = ZonedDateTime.ofInstant( Instant.ofEpochMilli( demand.getDemand( ).getModifyDate( ) ),
135                                 ZoneId.systemDefault( ) );
136                         final Timestamp expirationDateFromDemand = Timestamp.from( demandDate.plusMonths( nbMonthsCGUsMAX ).toInstant( ) );
137 
138                         // keep the max expiration date
139                         if ( demandExpirationDateMAX.before( expirationDateFromDemand ) )
140                         {
141                             demandExpirationDateMAX = expirationDateFromDemand;
142                         }
143                     }
144                 }
145 
146                 // check if expiredIdentity should be preserved or can be deleted
147                 if ( demandExpirationDateMAX.after( now ) )
148                 {
149                     // expiration date calculated from most recent demand is later than today
150                     // => update the expiration date of expiredIdentity : it will be deleted later
151                     expiredIdentity.setExpirationDate( demandExpirationDateMAX );
152                     IdentityHome.update( expiredIdentity );
153 
154                     // re-index and add history
155                     IdentityStoreNotifyListenerService.instance( ).notifyListenersIdentityChange( IdentityChangeType.UPDATE, expiredIdentity,
156                             "EXPIRATION_POSTPONED", StringUtils.EMPTY, daemonAuthor, daemonClientCode, Collections.emptyMap( ) );
157                     AccessLogService.getInstance( ).info( AccessLoggerConstants.EVENT_TYPE_MODIFY, UPDATE_IDENTITY_EVENT_CODE,
158                             InternalUserService.getInstance( ).getApiUser( daemonAuthor, daemonClientCode ), null, "PURGE_DAEMON" );
159 
160                     msg.append( "Identity expiration date updated : [" ).append( expiredIdentity.getCustomerId( ) ).append( "]" ).append( "\n" );
161                 }
162                 else
163                 {
164                     // if the peremption date still passed, delete the identity (and children as merged identities,
165                     // suspicious, attributes and attributes history, etc ...) EXCEPT the identity history
166                     IdentityService.instance( ).delete( expiredIdentity.getCustomerId( ) );
167                     msg.append( "Identity deleted for [" ).append( expiredIdentity.getCustomerId( ) ).append( "]" ).append( "\n" );
168 
169                     // delete notifications
170                     _notificationStoreService.deleteNotificationByCuid( expiredIdentity.getCustomerId( ) );
171                     msg.append( "Notifications deleted for main identity [" ).append( expiredIdentity.getCustomerId( ) ).append( "]" ).append( "\n" );
172                     for ( final Identity mergedIdentity : mergedIdentities )
173                     {
174                         _notificationStoreService.deleteNotificationByCuid( mergedIdentity.getCustomerId( ) );
175                         msg.append( "Notifications deleted for merged identity [" ).append( mergedIdentity.getCustomerId( ) ).append( "]" ).append( "\n" );
176                     }
177                 }
178             }
179             catch( final Exception e )
180             {
181                 msg.append( "Daemon execution error for identity : " ).append( expiredIdentity.getCustomerId( ) ).append( " :: " ).append( e.getMessage( ) )
182                         .append( "\n" );
183                 return msg.toString( );
184             }
185         }
186 
187         // return message for daemons
188         return msg.toString( );
189     }
190 
191     /**
192      * get app code
193      *
194      * @param strTypeId
195      *            the type id
196      * @return the app code
197      */
198     private String getAppCodeFromDemandTypeId( final String strTypeId )
199     {
200         DemandType demandType = _notificationStoreService.getDemandType( strTypeId );
201 
202         if ( demandType != null )
203         {
204             return demandType.getAppCode( );
205         }
206         
207         return null;
208     }
209 
210 }