001/*
002 *  Copyright 2017 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.cms.rights;
017
018import java.util.Collection;
019import java.util.Map;
020
021import org.apache.avalon.framework.parameters.Parameters;
022import org.apache.cocoon.acting.ServiceableAction;
023import org.apache.cocoon.environment.ObjectModelHelper;
024import org.apache.cocoon.environment.Redirector;
025import org.apache.cocoon.environment.Request;
026import org.apache.cocoon.environment.SourceResolver;
027import org.apache.commons.collections.CollectionUtils;
028
029import org.ametys.core.util.StringUtils;
030import org.ametys.runtime.authentication.AccessDeniedException;
031
032/**
033 * Action called to check client ip is allowed.
034 */
035public class CheckIpAction extends ServiceableAction
036{
037    @Override
038    public Map act(Redirector redirector, SourceResolver resolver, Map objectModel, String source, Parameters parameters) throws Exception
039    {
040        Request request = ObjectModelHelper.getRequest(objectModel);
041        
042        // Verify the IP address
043        String allowedIpsAsString = parameters.getParameter("allowedIps", "");
044        Collection<String> allowedIps = StringUtils.stringToCollection(allowedIpsAsString);
045        
046        // The real client IP may have been put in the non-standard "X-Forwarded-For" request header, in case of reverse proxy
047        String xff = request.getHeader("X-Forwarded-For");
048        Collection<String> remoteIps = StringUtils.stringToCollection(xff);
049        remoteIps.add(request.getRemoteAddr());
050        
051        if (!allowedIps.isEmpty() && !CollectionUtils.containsAny(allowedIps, remoteIps))
052        {
053            throw new AccessDeniedException("IP '" + org.apache.commons.lang3.StringUtils.join(remoteIps, ", ") + "' is not an authorized IP (" + allowedIpsAsString + ")");
054        }
055        
056        return EMPTY_MAP;
057    }
058}