Created
November 18, 2011 17:03
-
-
Save rponte/1377051 to your computer and use it in GitHub Desktop.
adapting BodyGuard project (Facelets EL functions) to work with spring security 3.x
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
package br.eti.faces.facelets.bodyguard.el; | |
import java.util.Arrays; | |
import java.util.List; | |
import org.springframework.security.core.Authentication; | |
import org.springframework.security.core.GrantedAuthority; | |
import org.springframework.security.core.context.SecurityContextHolder; | |
import org.springframework.security.core.userdetails.UserDetails; | |
public class SecurityFunctions { | |
//Internal use code | |
private static Authentication getAuthentication() { | |
if (SecurityContextHolder.getContext() != null) { | |
return SecurityContextHolder.getContext().getAuthentication(); | |
} | |
return null; | |
} | |
private static boolean isGranted(String roles, boolean checkAllRoles) { | |
Authentication auth = getAuthentication(); | |
if (auth == null) | |
return false; | |
if (roles == null) | |
return false; | |
List desiredRoles = Arrays.asList(roles.split(",")); | |
if(checkAllRoles) { | |
int checkedRoles = 0; | |
for (GrantedAuthority authority : auth.getAuthorities()) { | |
if (desiredRoles.contains(authority.getAuthority())) { | |
checkedRoles++; | |
} | |
} | |
return (auth.getAuthorities().size() == checkedRoles); | |
} | |
else { | |
for (GrantedAuthority authority : auth.getAuthorities()) { | |
if (desiredRoles.contains(authority.getAuthority())) { | |
return true; | |
} | |
} | |
} | |
return false; | |
} | |
//EL Functions | |
public static boolean isUserInAnyRoles(String roles) { | |
return isGranted(roles, false); | |
} | |
public static boolean isUserNotInRoles(String roles) { | |
return ! isGranted(roles, false); | |
} | |
public static boolean isUserInAllRoles(String roles) { | |
return isGranted(roles, true); | |
} | |
public static boolean isAuthenticated() { | |
String user = remoteUser(); | |
return (user != null && ! user.equals("roleAnonymous")); | |
} | |
public static String remoteUser() { | |
Authentication auth = getAuthentication(); | |
if (auth == null) | |
return null; | |
Object principal = auth.getPrincipal(); | |
if(principal instanceof String) | |
return (String) auth.getPrincipal(); | |
else | |
return ((UserDetails) auth.getPrincipal()) | |
.getUsername(); | |
} | |
} |
rponte, descobri um bug..
Quando é feito qualquer submit ele da uma ELException dizendo que a function não existe :'(
Checaremos isso na segunda-feira :-)
Será que vale colocar a lib github?
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
more informations, http://faces.eti.br/2008/11/09/bodyguard-facelets-el-functions-for-spring-security/