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