001 /*
002 * Copyright 2007 Robin Helgelin
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 */
016
017 package nu.localhost.tapestry.acegi.components;
018
019 import java.security.Principal;
020
021 import org.apache.tapestry.Block;
022 import org.apache.tapestry.annotations.Parameter;
023 import org.apache.tapestry.ioc.annotations.Inject;
024 import org.apache.tapestry.services.RequestGlobals;
025
026 /**
027 * Render it's body depending whether the user is logged in or not.
028 *
029 * @author Robin Helgelin
030 * @author Tapestry Project (doc comments)
031 */
032 public class IfLoggedIn {
033 /**
034 * Optional parameter to invert the test. If true, then the body is rendered when the test
035 * parameter is false (not true).
036 */
037 @Parameter
038 private boolean negate;
039
040 /**
041 * An alternate {@link Block} to render if the test parameter is false. The default, null, means
042 * render nothing in that situation.
043 */
044 @Parameter(name = "else")
045 private Block elseBlock;
046
047 @Inject
048 private RequestGlobals requestGlobals;
049
050 private boolean test() {
051 Principal principal = requestGlobals.getHTTPServletRequest().getUserPrincipal();
052 return principal != null && principal.getName() != "";
053 }
054
055 /**
056 * Returns null if the test method returns true, which allows normal rendering (of the body). If
057 * the test parameter is false, returns the else parameter (this may also be null).
058 */
059 Object beginRender() {
060 if (test() != negate) {
061 return null;
062 } else {
063 return elseBlock;
064 }
065 }
066
067 /**
068 * If the test method returns true, then the body is rendered, otherwise not. The component does
069 * not have a template or do any other rendering besides its body.
070 */
071 boolean beforeRenderBody() {
072 return test() != negate;
073 }
074
075 void setup(String role, boolean negate, Block elseBlock) {
076 this.negate = negate;
077 this.elseBlock = elseBlock;
078 }
079 }