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 org.apache.shiro.subject.PrincipalCollection;
017
018import javax.faces.context.FacesContext;
019import java.beans.BeanInfo;
020import java.beans.IntrospectionException;
021import java.beans.Introspector;
022import java.beans.PropertyDescriptor;
023import java.io.IOException;
024import java.lang.reflect.InvocationTargetException;
025import java.lang.reflect.Modifier;
026
027import lombok.Getter;
028import lombok.Setter;
029import lombok.extern.slf4j.Slf4j;
030
031/**
032 * <p>Tag used to print out the String value of a user's default principal,
033 * or a specific principal as specified by the tag's attributes.
034 * <p>
035 * <p> If no attributes are specified, the tag prints out the toString()
036 * value of the user's default principal.  If the type attribute
037 * is specified, the tag looks for a principal with the given type.  If the
038 * property attribute is specified, the tag prints the string value of
039 * the specified property of the principal.  If no principal is found or the user
040 * is not authenticated, the tag displays nothing unless a defaultValue
041 * is specified.<p>
042 */
043@Slf4j
044public class PrincipalTag extends SecureComponent {
045    /**
046     * The type of principal to be retrieved, or null if the default principal should be used.
047     */
048    @Getter
049    @Setter
050    private String type;
051    /**
052     * The property name to retrieve of the principal, or null if the <tt>toString()</tt> value should be used.
053     */
054    @Getter
055    @Setter
056    private String property;
057    /**
058     * The default value that should be displayed if the user is not authenticated, or no principal is found.
059     */
060    @Getter
061    @Setter
062    private String defaultValue;
063
064    private Object[] values;
065
066
067    @Override
068    protected void doEncodeAll(FacesContext ctx) throws IOException {
069        String strValue = null;
070
071        try {
072            if (getSubject() != null) {
073                // Get the principal to print out
074                Object principal;
075
076                if (type == null) {
077                    principal = getSubject().getPrincipal();
078                } else {
079                    principal = getPrincipalFromClassName();
080                }
081
082                // Get the string value of the principal
083                if (principal != null) {
084                    if (property == null) {
085                        strValue = principal.toString();
086                    } else {
087                        strValue = getPrincipalProperty(principal, property);
088                    }
089                }
090            }
091        } catch (IOException e) {
092            log.error("Error getting principal type [" + type + "], property [" + property + "]: " + e.getMessage(), e);
093        }
094
095        if (strValue == null) {
096            strValue = defaultValue;
097        }
098
099        // Print out the principal value if not null
100        if (strValue != null) {
101            try {
102                ctx.getResponseWriter().write(strValue);
103            } catch (IOException e) {
104                throw new IOException("Error writing [" + strValue + "] to output.");
105            }
106        }
107    }
108
109    private Object getPrincipalFromClassName() {
110        Object principal = null;
111
112        try {
113            Class<?> cls = Class.forName(type);
114            PrincipalCollection principals = getSubject().getPrincipals();
115            if (principals != null) {
116                principal = principals.oneByType(cls);
117            }
118        } catch (ClassNotFoundException e) {
119            if (log.isErrorEnabled()) {
120                log.error("Unable to find class for name [" + type + "]");
121            }
122        } catch (Exception e) {
123            if (log.isErrorEnabled()) {
124                log.error("Unknown error while getting principal for type [" + type + "]: " + e.getMessage(), e);
125            }
126        }
127        return principal;
128    }
129
130    private String getPrincipalProperty(Object principal, String property) throws IOException {
131        String strValue = null;
132
133        try {
134            BeanInfo bi = Introspector.getBeanInfo(principal.getClass());
135
136            // Loop through the properties to get the string value of the specified property
137            boolean foundProperty = false;
138            for (PropertyDescriptor pd : bi.getPropertyDescriptors()) {
139                if (pd.getName().equals(property) && (Modifier.isPublic(pd.getReadMethod().getModifiers()))) {
140                    Object value = null;
141                    try {
142                        pd.getReadMethod().setAccessible(true);
143                        value = pd.getReadMethod().invoke(principal, (Object[]) null);
144                    } finally {
145                        pd.getReadMethod().setAccessible(false);
146                    }
147                    strValue = String.valueOf(value);
148                    foundProperty = true;
149                    break;
150                }
151            }
152
153            if (!foundProperty) {
154                final String message = "Property [" + property + "] not found in principal of type ["
155                        + principal.getClass().getName() + "]";
156                if (log.isErrorEnabled()) {
157                    log.error(message);
158                }
159                throw new IOException(message);
160            }
161
162        } catch (IntrospectionException | IOException | IllegalAccessException | InvocationTargetException e) {
163            final String message = "Error reading property [" + property + "] from principal of type ["
164                    + principal.getClass().getName() + "]";
165            if (log.isErrorEnabled()) {
166                log.error(message, e);
167            }
168            throw new IOException(message);
169        }
170
171        return strValue;
172    }
173
174    @Override
175    @SuppressWarnings("MagicNumber")
176    public Object saveState(FacesContext context) {
177        if (values == null) {
178            values = new Object[4];
179        }
180        values[0] = super.saveState(context);
181        values[1] = type;
182        values[2] = property;
183        values[3] = defaultValue;
184
185        return values;
186    }
187
188    @Override
189    public void restoreState(FacesContext context, Object state) {
190        values = (Object[]) state;
191        super.restoreState(context, values[0]);
192        type = (String) values[1];
193        property = (String) values[2];
194        defaultValue = (String) values[3];
195    }
196}