Skip to content

Instantly share code, notes, and snippets.

@rponte
Created November 18, 2011 17:03
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save rponte/1377051 to your computer and use it in GitHub Desktop.
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
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
Copy link
Author

rponte commented Nov 18, 2011

@Quindin
Copy link

Quindin commented Nov 19, 2011

rponte, descobri um bug..
Quando é feito qualquer submit ele da uma ELException dizendo que a function não existe :'(

@rponte
Copy link
Author

rponte commented Nov 19, 2011

Checaremos isso na segunda-feira :-)

@ararog
Copy link

ararog commented Nov 17, 2012

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