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.hc.core5.http.HttpRequest;
028import org.apache.hc.core5.http.HttpResponse;
029
030import org.ametys.core.util.URIUtils;
031import org.ametys.runtime.plugin.component.AbstractLogEnabled;
032
033/**
034 * Proxies a session attribute to the back-office, under the form of a request header prefixed by "X-Ametys-Session-".
035 */
036public class SessionAttributeRequestProxy extends AbstractLogEnabled implements BackOfficeRequestProxy, Configurable
037{
038    /** The header prefix */
039    public static final String HEADER_PREFIX = "X-Ametys-Session-";
040    
041    /** The list of session attribute to proxy */
042    protected List<String> _attributes = new ArrayList<>();
043    
044    public void configure(Configuration configuration) throws ConfigurationException
045    {
046        for (Configuration attributeConfig : configuration.getChildren("attribute"))
047        {
048            _attributes.add(attributeConfig.getValue());
049        }
050    }
051    
052    public void prepareBackOfficeRequest(Request request, HttpRequest backOfficeRequest)
053    {
054        Session session = request.getSession(false);
055        if (session != null)
056        {
057            for (String attributeName : _attributes)
058            {
059                Object attribute = session.getAttribute(attributeName);
060                if (attribute != null)
061                {
062                    backOfficeRequest.setHeader(HEADER_PREFIX + URIUtils.encodeHeader(attributeName), attribute.toString());
063                }
064            }
065        }
066    }
067
068    public void handleBackOfficeResponse(Response response, HttpResponse backOfficeResponse)
069    {
070        // nothing to do
071    }
072}