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.plugins.workspaces.dav;
017
018import java.util.HashMap;
019import java.util.Map;
020
021import org.apache.avalon.framework.parameters.Parameters;
022import org.apache.cocoon.acting.AbstractAction;
023import org.apache.cocoon.environment.ObjectModelHelper;
024import org.apache.cocoon.environment.Redirector;
025import org.apache.cocoon.environment.Request;
026import org.apache.cocoon.environment.SourceResolver;
027import org.apache.commons.lang3.StringUtils;
028
029import org.ametys.core.authentication.AuthenticateAction;
030
031/**
032 * Action to get the token and the path from the URI/Header
033 * the uri can be token/path/to/resource, or just path/to/resource if the token is in the X-Ametys-Token header
034 */
035public class GetTokenAndObjectPathAction extends AbstractAction
036{
037    @Override
038    public Map act(Redirector redirector, SourceResolver resolver, Map objectModel, String source, Parameters parameters) throws Exception
039    {
040        Map<String, String> result = new HashMap<>();
041        
042        Request request = ObjectModelHelper.getRequest(objectModel);
043        String token = request.getHeader(AuthenticateAction.HEADER_TOKEN);
044        
045        String objectPath = parameters.getParameter("endUri", null);
046        
047        if (StringUtils.isBlank(token))
048        {
049            if (objectPath != null)
050            {
051                int posOfSlash = StringUtils.indexOf(objectPath, "/");
052                if (posOfSlash > 0 && posOfSlash < objectPath.length() - 1) // if there is a slash, and it is not the last char
053                {
054                    token = objectPath.substring(0, posOfSlash);
055                    objectPath = objectPath.substring(posOfSlash);
056                }
057            }
058        }
059
060        result.put("token", token);
061        result.put("objectPath", objectPath);
062        return result;
063    }
064}