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.site;
017
018import java.util.HashMap;
019import java.util.Map;
020
021import org.apache.avalon.framework.parameters.Parameters;
022import org.apache.avalon.framework.service.ServiceException;
023import org.apache.avalon.framework.service.ServiceManager;
024import org.apache.avalon.framework.service.Serviceable;
025import org.apache.avalon.framework.thread.ThreadSafe;
026import org.apache.cocoon.acting.AbstractAction;
027import org.apache.cocoon.environment.ObjectModelHelper;
028import org.apache.cocoon.environment.Redirector;
029import org.apache.cocoon.environment.Request;
030import org.apache.cocoon.environment.SourceResolver;
031
032import org.ametys.plugins.site.token.GetTokenExtensionPoint;
033
034/**
035 * Extracts token from the request and give it as sitemap parameter.
036 */
037public class GetTokenAction extends AbstractAction implements ThreadSafe, Serviceable 
038{
039    private GetTokenExtensionPoint _tokenExtensionPoint;
040    
041    public void service(ServiceManager manager) throws ServiceException
042    {
043        _tokenExtensionPoint = (GetTokenExtensionPoint) manager.lookup(GetTokenExtensionPoint.ROLE);
044    }
045    
046    public Map act(Redirector redirector, SourceResolver resolver, Map objectModel, String source, Parameters parameters) throws Exception
047    {
048        Request request = ObjectModelHelper.getRequest(objectModel);
049        String token = _tokenExtensionPoint.getToken(request);
050        String tokenContext = _tokenExtensionPoint.getTokenContext(request);
051        
052        if (token != null)
053        {
054            Map<String, String> result = new HashMap<>();
055            result.put("token", token);
056            
057            if (tokenContext != null)
058            {
059                result.put("tokenContext", tokenContext);
060            }
061            return result;
062        }
063        
064        return null;
065    }
066}