001/*
002 *  Copyright 2022 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.cms.workflow;
017
018import java.util.Map;
019
020import org.ametys.core.user.UserIdentity;
021import org.ametys.plugins.repository.AmetysObject;
022import org.ametys.plugins.repository.AmetysRepositoryException;
023import org.ametys.plugins.workflow.component.CheckRightsCondition;
024import org.ametys.plugins.workflow.repository.WorkflowAwareAmetysObject;
025
026import com.opensymphony.workflow.WorkflowException;
027
028/**
029 * Condition for checking rights of an user for the current action
030 * using the right ametys object context.<p>
031 * The following configuration can be used for checking rights:<br>
032 * <pre>
033 * &lt;condition type="avalon"&gt;
034 * &nbsp;&nbsp;&lt;arg name="role"&gt;org.ametys.cms.workflow.AmetysObjectCheckRightsCondition&lt;/arg&gt;
035 * &nbsp;&nbsp;&lt;arg name="right"&gt;Right_Edition&lt;/arg&gt;
036 * &lt;/condition&gt;
037 * </pre>
038 */
039public class AmetysObjectCheckRightsCondition extends CheckRightsCondition
040{
041    /** Constant for storing the ametys object into the transient variables map. */
042    public static final String AMETYS_OBJECT_KEY = AmetysObject.class.getName();
043    
044    @Override
045    protected Object _computeContext(Map transientVars, Map args, UserIdentity user, String right) throws WorkflowException
046    {
047        try
048        {
049            return getAmetysObject(transientVars);
050        }
051        catch (AmetysRepositoryException e)
052        {
053            throw new WorkflowException("Unable to retrieve ametys object name", e);
054        }
055    }
056    
057    /**
058     * Retrieve the ametys object associated with the workflow.
059     * @param transientVars the parameters from the call.
060     * @return the ametys object.
061     * @throws WorkflowException if the content is not found.
062     */
063    protected WorkflowAwareAmetysObject getAmetysObject(Map transientVars) throws WorkflowException
064    {
065        WorkflowAwareAmetysObject content = (WorkflowAwareAmetysObject) transientVars.get(AMETYS_OBJECT_KEY);
066        
067        if (content == null)
068        {
069            throw new WorkflowException("Unable to retrieve ametys object");
070        }
071        
072        // Found in transient variables map
073        return content;
074    }
075}