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.web;
017
018import org.apache.avalon.framework.component.Component;
019import org.apache.avalon.framework.context.Context;
020import org.apache.avalon.framework.context.ContextException;
021import org.apache.avalon.framework.context.Contextualizable;
022import org.apache.cocoon.components.ContextHelper;
023import org.apache.cocoon.environment.Request;
024import org.apache.cocoon.environment.Session;
025
026import org.ametys.runtime.plugin.component.AbstractLogEnabled;
027
028/**
029 * Component for getting a session attribute, potentially proxied by the front-office.
030 */
031public class WebSessionAttributeProvider extends AbstractLogEnabled implements Component, Contextualizable
032{
033    /** Avalon role */
034    public static final String ROLE = WebSessionAttributeProvider.class.getName();
035    
036    private Context _context;
037    
038    public void contextualize(Context context) throws ContextException
039    {
040        _context = context;        
041    }
042    
043    /**
044     * Retrieve the session attribute, either proxied by the back-office, or in the back-office session.
045     * @param name the attribute name
046     * @return the value stored either in the front-office session, or in the back-office session, or null if none
047     */
048    public Object getSessionAttribute(String name)
049    {
050        Request request = ContextHelper.getRequest(_context);
051        if (request != null)
052        {
053            String attributeFromHeader = request.getHeader("X-Ametys-Session-" + name);
054            if (attributeFromHeader != null)
055            {
056                return attributeFromHeader;
057            }
058            
059            Session session = request.getSession(false);
060            if (session != null)
061            {
062                return session.getAttribute(name);
063            }
064        }
065        
066        return null;
067    }
068}