001/*
002 *  Copyright 2016 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.administration.welcome;
017
018import java.util.List;
019import java.util.Set;
020
021import org.apache.avalon.framework.context.Context;
022import org.apache.avalon.framework.context.ContextException;
023import org.apache.avalon.framework.context.Contextualizable;
024import org.apache.avalon.framework.service.ServiceException;
025import org.apache.avalon.framework.service.ServiceManager;
026import org.apache.avalon.framework.service.Serviceable;
027import org.apache.cocoon.components.ContextHelper;
028import org.apache.cocoon.environment.Request;
029import org.slf4j.Logger;
030
031import org.ametys.core.right.AllowedUsers;
032import org.ametys.core.right.RightManager;
033import org.ametys.core.user.UserIdentity;
034import org.ametys.core.user.population.PopulationContextHelper;
035import org.ametys.runtime.plugin.component.LogEnabled;
036import org.ametys.web.repository.site.SiteManager;
037import org.ametys.web.site.SiteConfigurationExtensionPoint;
038
039/**
040 * This step indicates that there is at least one well configured site with a user who has right to give its rights.
041 */
042public class SiteWithUserStep extends AbstractWelcomeStep implements Serviceable, Contextualizable, LogEnabled
043{
044    private ServiceManager _manager;
045    private SiteManager _siteManager;
046    private SiteConfigurationExtensionPoint _siteConfiguration;
047    private RightManager _rightManager;
048    private PopulationContextHelper _populationContextHelper;
049    private Context _context;
050    private Logger _logger;
051    
052    @Override
053    public void contextualize(Context context) throws ContextException
054    {
055        _context = context;
056    }
057    
058    @Override
059    public void service(ServiceManager manager) throws ServiceException
060    {
061        _manager = manager;
062        _rightManager = (RightManager) manager.lookup(RightManager.ROLE);
063    }
064    
065    public void setLogger(Logger logger)
066    {
067        _logger = logger;
068    }
069    
070    private Logger getLogger()
071    {
072        return _logger;
073    }
074    
075    private SiteManager _getSiteManager()
076    {
077        if (_siteManager == null)
078        {
079            try
080            {
081                _siteManager = (SiteManager) _manager.lookup(SiteManager.ROLE);
082            }
083            catch (ServiceException e)
084            {
085                // The component cannot be looked up in safe mode
086            }
087        }
088        return _siteManager;
089    }
090    
091    private SiteConfigurationExtensionPoint _getSiteConfiguration()
092    {
093        if (_siteConfiguration == null)
094        {
095            try
096            {
097                _siteConfiguration = (SiteConfigurationExtensionPoint) _manager.lookup(SiteConfigurationExtensionPoint.ROLE);
098            }
099            catch (ServiceException e)
100            {
101                // The component cannot be looked up in safe mode
102            }
103        }
104        return _siteConfiguration;
105    }
106    
107    private PopulationContextHelper getPopulationContextHelper()
108    {
109        if (_populationContextHelper == null)
110        {
111            try
112            {
113                _populationContextHelper = (PopulationContextHelper) _manager.lookup(PopulationContextHelper.ROLE);
114            }
115            catch (ServiceException e)
116            {
117                // The component cannot be looked up in safe mode
118            }
119        }
120        return _populationContextHelper;
121    }
122    
123    @Override
124    public boolean isPerformed()
125    {
126        SiteManager siteManager = _getSiteManager();
127        if (siteManager == null)
128        {
129            return false;
130        }
131        
132        SiteConfigurationExtensionPoint siteConfiguration = _getSiteConfiguration();
133        if (siteConfiguration == null)
134        {
135            return false;
136        }
137        
138        long t0 = System.currentTimeMillis();
139        getLogger().debug("Starting isPerformed...");
140        int index = 0;
141
142        Request request = ContextHelper.getRequest(_context);
143        for (String siteName : _siteManager.getSiteNames())
144        {
145            long t1 = System.currentTimeMillis();
146            index++;
147            if (siteConfiguration.isValid(siteName))
148            {
149                getLogger().debug("Site {} is valid", siteName);
150                try
151                {
152                    request.setAttribute("siteName", siteName); // Setting temporarily this attribute to check user right on '/cms' on this site
153                    
154                    AllowedUsers allowedUsers = _rightManager.getAllowedUsers("CMS_Rights_Delegate_Rights", "/cms");
155                    Set<UserIdentity> resolveAllowedUsers = allowedUsers.resolveAllowedUsers(true);
156
157                    long t2 = System.currentTimeMillis();
158                    getLogger().debug("getUsersByContext done in {}ms for site {}", t2 - t1, siteName);
159                    
160                    if (_hasOneCorrectUser(siteName, resolveAllowedUsers))
161                    {
162                        long t3 = System.currentTimeMillis();
163                        getLogger().info("isPerformed 'true' done in {}ms. Tested {} site(s)", t3 - t0, index);
164                        return true;
165                    }
166                }
167                finally
168                {
169                    request.setAttribute("siteName", null);
170                }
171            }
172            else
173            {
174                getLogger().debug("Site {} is invalid", siteName);
175            }
176        }
177        
178        long t3 = System.currentTimeMillis();
179        getLogger().info("isPerformed 'false' done in {}ms. Tested {} site(s)", t3 - t0, index);
180        return false;
181    }
182
183    private boolean _hasOneCorrectUser(String siteName, Set<UserIdentity> resolveAllowedUsers)
184    {
185        List<String> userPopulationsOnContext = getPopulationContextHelper().getUserPopulationsOnContext("/sites/" + siteName, false);
186        if (userPopulationsOnContext.isEmpty())
187        {
188            return false;
189        }
190        
191        for (UserIdentity userIdentity : resolveAllowedUsers)
192        {
193            if (userPopulationsOnContext.contains(userIdentity.getPopulationId()))
194            {
195                return true;
196            }
197        }
198        
199        return false;
200    }
201}