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.site;
017
018import java.util.Collection;
019import java.util.Collections;
020import java.util.Map;
021
022import org.apache.avalon.framework.parameters.Parameters;
023import org.apache.cocoon.acting.Action;
024import org.apache.cocoon.environment.ObjectModelHelper;
025import org.apache.cocoon.environment.Redirector;
026import org.apache.cocoon.environment.Request;
027import org.apache.cocoon.environment.SourceResolver;
028
029import org.ametys.core.util.StringUtils;
030import org.ametys.runtime.authentication.AccessDeniedException;
031import org.ametys.runtime.config.Config;
032
033/**
034 * Action check if the request is from the backoffice.
035 */
036public class IsFromBackOfficeAction implements Action
037{
038    public Map act(Redirector redirector, SourceResolver resolver, Map objectModel, String source, Parameters parameters) throws Exception
039    {
040        Request request = ObjectModelHelper.getRequest(objectModel);
041        if ("true".equals(request.getHeader("X-Ametys-BO")))
042        {
043            // The request seems to come from an FO, verify the IP address
044            String conf = Config.getInstance().getValueAsString("org.ametys.site.back.ip");
045            Collection<String> ips = StringUtils.stringToCollection(conf);
046            
047            // The real client IP may have been put in the non-standard "X-Forwarded-For" request header, in case of reverse proxy
048            String xff = request.getHeader("X-Forwarded-For");
049            String ip = null;
050            
051            if (xff != null)
052            {
053                ip = xff.split(",")[0];
054            }
055            else
056            {
057                ip = request.getRemoteAddr();
058            }
059            
060            if (!ips.isEmpty() && !ips.contains(ip))
061            {
062                throw new AccessDeniedException("IP '" + ip + "' is not an authorized back-office IP (" + conf + ")");
063            }
064            
065            return Collections.EMPTY_MAP;
066        }
067        
068        return null;
069    }
070}