1 /* 2 * Copyright 2004-2009 the original author or authors. 3 * 4 * Licensed under the Apache License, Version 2.0 (the "License"); 5 * you may not use this file except in compliance with the License. 6 * You may obtain a copy of the License at 7 * 8 * http://www.apache.org/licenses/LICENSE-2.0 9 * 10 * Unless required by applicable law or agreed to in writing, software 11 * distributed under the License is distributed on an "AS IS" BASIS, 12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 * See the License for the specific language governing permissions and 14 * limitations under the License. 15 */ 16 17 package org.springmodules.validation.valang.functions; 18 19 import java.util.Collection; 20 21 import org.springframework.security.core.Authentication; 22 import org.springframework.security.core.GrantedAuthority; 23 import org.springframework.security.core.context.SecurityContextHolder; 24 25 /** 26 * A function that accepts a one string argument that indicates a security role. This function 27 * returns a <code>true</code> if the current user is in the passed in role, and <code>false</code> 28 * otherwise. 29 * <br/><br/> 30 * This method uses Acegi's <code>SecurityContextHolder.getContext().getAuthentication()</code> to 31 * get the current user. 32 * <br/><br/> 33 * This function may be used to apply different validation rules based on the logged in user roles. 34 * 35 * @author Uri Boness 36 * @since May 25, 2006 37 */ 38 public class InRoleFunction extends AbstractFunction { 39 40 public InRoleFunction(Function[] arguments, int line, int column) { 41 super(arguments, line, column); 42 definedExactNumberOfArguments(1); 43 } 44 45 protected Object doGetResult(Object target) { 46 47 Object role = getArguments()[0].getResult(target); 48 49 Authentication authentication = SecurityContextHolder.getContext().getAuthentication(); 50 if (authentication == null) { 51 return Boolean.FALSE; 52 } 53 54 Collection<? extends GrantedAuthority> authorities = authentication.getAuthorities(); 55 56 for (GrantedAuthority authority : authorities) { 57 if (authority.equals(role)) { 58 return Boolean.TRUE; 59 } 60 } 61 62 return Boolean.FALSE; 63 } 64 65 }