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.web.rights;
017
018import java.util.ArrayList;
019import java.util.Arrays;
020import java.util.List;
021import java.util.Set;
022import java.util.stream.Collectors;
023
024import org.apache.avalon.framework.context.Context;
025import org.apache.avalon.framework.context.ContextException;
026import org.apache.avalon.framework.context.Contextualizable;
027import org.apache.cocoon.components.ContextHelper;
028import org.apache.cocoon.environment.Request;
029import org.apache.commons.lang3.StringUtils;
030
031import org.ametys.plugins.core.impl.right.StringHierarchicalAccessController;
032import org.ametys.plugins.core.impl.right.WorkspaceAccessController;
033import org.ametys.web.WebHelper;
034
035/**
036 * This impl of {@link WorkspaceAccessController} will add the current sitemap to the cms workspace   
037 */
038public class WebWorkspaceAccessController extends StringHierarchicalAccessController implements Contextualizable
039{
040    private Context _context;
041    
042    public void contextualize(Context context) throws ContextException
043    {
044        _context = context;
045    }
046
047    @Override
048    protected Set<String> getSupportedPrefixes()
049    {
050        String sitename = _getSiteName();
051        if (StringUtils.isBlank(sitename))
052        {
053            return null;
054        }
055
056        return _prefixes;
057    }
058    
059    @Override
060    protected Object _convertContext(Object initialContext)
061    {
062        String supportedContext = (String) initialContext;
063        List<String> contexts = new ArrayList<>(Arrays.asList(StringUtils.split(supportedContext, '/')));
064        contexts.add(1, _getSiteName());
065        return "/" + StringUtils.join(contexts, "/");
066    }
067    
068    @Override
069    protected Set<String> getRootPrefixes()
070    {
071        String sitename = "/" + _getSiteName();
072        return _prefixes.stream().map(p -> p + sitename).collect(Collectors.toSet());
073    }
074    
075    private String _getSiteName()
076    {
077        Request request = ContextHelper.getRequest(_context);
078        return WebHelper.getSiteName(request);
079    }
080}