001/*
002 * Licensed under the Apache License, Version 2.0 (the "License");
003 * you may not use this file except in compliance with the License.
004 * You may obtain a copy of the License at
005 *
006 *      http://www.apache.org/licenses/LICENSE-2.0
007 *
008 * Unless required by applicable law or agreed to in writing, software
009 * distributed under the License is distributed on an "AS IS" BASIS,
010 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
011 * See the License for the specific language governing permissions and
012 * limitations under the License.
013 */
014package org.apache.shiro.ee.faces.tags;
015
016import javax.el.ELException;
017import javax.el.ValueExpression;
018import javax.faces.FacesException;
019import javax.faces.component.UIComponent;
020import javax.faces.view.facelets.FaceletContext;
021import javax.faces.view.facelets.TagAttribute;
022import javax.faces.view.facelets.TagConfig;
023import java.io.IOException;
024
025/**
026 * Base TagHandler for Tags that check for permissions.
027 */
028public abstract class PermissionTagHandler extends SecureTagHandler {
029    private final TagAttribute name;
030
031    public PermissionTagHandler(TagConfig config) {
032        super(config);
033        this.name = this.getRequiredAttribute("name");
034    }
035
036    private String getAttrValue(FaceletContext ctx, TagAttribute attr) {
037        String value;
038        if (attr.isLiteral()) {
039            value = attr.getValue(ctx);
040        } else {
041            ValueExpression expression = attr.getValueExpression(ctx, String.class);
042            value = (String) expression.getValue(ctx);
043        }
044        return value;
045    }
046
047    @Override
048    public void apply(FaceletContext ctx, UIComponent parent)
049            throws IOException, FacesException, ELException {
050        String perm;
051        perm = getAttrValue(ctx, name);
052        if (showTagBody(perm)) {
053            this.nextHandler.apply(ctx, parent);
054        }
055    }
056
057    protected boolean isPermitted(String p) {
058        return getSubject() != null && getSubject().isPermitted(p);
059    }
060
061    protected abstract boolean showTagBody(String p);
062}