001/*
002 *  Copyright 2021 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.plugins.site.proxy;
017
018import java.util.ArrayList;
019import java.util.List;
020
021import org.apache.avalon.framework.configuration.Configurable;
022import org.apache.avalon.framework.configuration.Configuration;
023import org.apache.avalon.framework.configuration.ConfigurationException;
024import org.apache.cocoon.environment.Request;
025import org.apache.cocoon.environment.Response;
026import org.apache.cocoon.environment.Session;
027import org.apache.http.HttpResponse;
028import org.apache.http.client.methods.HttpUriRequest;
029
030/**
031 * Proxies a session attribute to the back-office, under the form of a request header prefixed by "X-Ametys-Session-".
032 */
033public class SessionAttributeRequestProxy implements BackOfficeRequestProxy, Configurable
034{
035    /** The header prefix */
036    public static final String HEADER_PREFIX = "X-Ametys-Session-";
037    
038    /** The list of session attribute to proxy */
039    protected List<String> _attributes = new ArrayList<>();
040    
041    public void configure(Configuration configuration) throws ConfigurationException
042    {
043        for (Configuration attributeConfig : configuration.getChildren("attribute"))
044        {
045            _attributes.add(attributeConfig.getValue());
046        }
047    }
048    
049    public void prepareBackOfficeRequest(Request request, HttpUriRequest backOfficeRequest)
050    {
051        Session session = request.getSession(false);
052        if (session != null)
053        {
054            for (String attributeName : _attributes)
055            {
056                Object attribute = session.getAttribute(attributeName);
057                if (attribute != null)
058                {
059                    backOfficeRequest.addHeader(HEADER_PREFIX + attributeName, attribute.toString());
060                }
061            }
062        }
063    }
064
065    public void handleBackOfficeResponse(Response response, HttpResponse backOfficeResponse)
066    {
067        // nothing to do
068    }
069}