001/*
002 *  Copyright 2025 Anyware Services
003 *
004 *  Licensed under the Apache License, Version 2.0 (the "License");
005 *  you may not use this file except in compliance with the License.
006 *  You may obtain a copy of the License at
007 *
008 *      http://www.apache.org/licenses/LICENSE-2.0
009 *
010 *  Unless required by applicable law or agreed to in writing, software
011 *  distributed under the License is distributed on an "AS IS" BASIS,
012 *  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
013 *  See the License for the specific language governing permissions and
014 *  limitations under the License.
015 */
016package org.ametys.web.usermanagement.observer;
017
018import java.util.List;
019import java.util.Map;
020
021import org.apache.avalon.framework.service.ServiceException;
022import org.apache.avalon.framework.service.ServiceManager;
023import org.apache.avalon.framework.service.Serviceable;
024import org.apache.commons.lang3.tuple.Pair;
025
026import org.ametys.core.ObservationConstants;
027import org.ametys.core.observation.AsyncObserver;
028import org.ametys.core.observation.Event;
029import org.ametys.core.user.UserIdentity;
030import org.ametys.web.cache.FOCommHelper;
031
032/**
033 * Observer to propagate user event to the site applications
034 */
035public class InvalidateUserCacheObserver implements AsyncObserver, Serviceable
036{
037    private FOCommHelper _foCommHelper;
038    
039    public void service(ServiceManager manager) throws ServiceException
040    {
041        _foCommHelper = (FOCommHelper) manager.lookup(FOCommHelper.ROLE);
042    }
043    
044    public int getPriority()
045    {
046        return Integer.MAX_VALUE;
047    }
048
049    public boolean supports(Event event)
050    {
051        String id = event.getId();
052        return ObservationConstants.EVENT_USER_DELETED.equals(id)
053            || ObservationConstants.EVENT_USER_UPDATED.equals(id);
054    }
055
056    public void observe(Event event, Map<String, Object> transientVars) throws Exception
057    {
058        List<Pair<String, String>> params = List.of(
059                Pair.of("id", event.getId()),
060                Pair.of("issuer", UserIdentity.userIdentityToString(event.getIssuer())),
061                Pair.of("args." + ObservationConstants.ARGS_USER, UserIdentity.userIdentityToString((UserIdentity) event.getArguments().get(ObservationConstants.ARGS_USER)))
062        );
063        
064        _foCommHelper.testWS("/_invalidate-user-directory-cache", params);
065    }
066}