2012-06-07 50 views
2

採取提供的建議here,我已經實現了我自己的RoleVoter類來擴展RoleVoter,並且我需要添加的額外檢查是用戶,角色和組織都基於在我存儲在會議中的組織中。自定義RoleVoter和訪問UserRole的額外投票檢查

我有以下的UserRole類:

class UserRole implements Serializable { 
    User user 
    Role role 
    Organization organization 
    .... 
} 

這是我OrganizationRoleVoter類:

class OrganizationRoleVoter extends RoleVoter { 

    @Override 
    public int vote(Authentication authentication, Object object, Collection<ConfigAttribute> attributes) { 

    int result = ACCESS_ABSTAIN 
    Collection<? extends GrantedAuthority> authorities = extractAuthorities(authentication) 

    attributes.each {ConfigAttribute attribute -> 
     if (this.supports(attribute)) { 
     result = ACCESS_DENIED 

     authorities.each {GrantedAuthority authority -> 
      //TODO this should also check the chosen organization 
      if (attribute.attribute.equals(authority.authority)) { 
      return ACCESS_GRANTED 
      } 
     } 
     } 
    } 
    return result 
    } 

    Collection<? extends GrantedAuthority> extractAuthorities(Authentication authentication) { 
    return authentication.getAuthorities(); 
    } 

} 

正如你可以在我的TODO看,這是我需要也說「是在這裏授予的權威也與我在會議上發佈的組織保持一致。對於如何實現這一目標,真的很遺憾。

回答

2

這是我如何解決它遠。這似乎工作,但我總是打開改進:

class OrganizationRoleVoter extends RoleVoter { 

    @Override 
    public int vote(Authentication authentication, Object object, Collection<ConfigAttribute> attributes) { 

    int result = ACCESS_ABSTAIN 
    Collection<? extends GrantedAuthority> authorities = extractAuthorities(authentication) 
    GrailsWebRequest request = RequestContextHolder.currentRequestAttributes() 
    Organization selectedOrganization = (Organization) request.session.getAttribute("selectedOrganizationSession") 

    attributes.each {ConfigAttribute attribute -> 
     if (this.supports(attribute)) { 
     result = ACCESS_DENIED 
     for (GrantedAuthority authority : authorities) { 
      if (attribute.attribute.equals(authority.authority)) { 
      def user = User.findByUsername(authentication.name) 
      def role = Role.findByAuthority(authority.authority) 
      if (UserRole.findByUserAndOrganizationAndRole(user, selectedOrganization, role)) { 
       result = ACCESS_GRANTED 
       break 
      } 
      } 
     } 
     } 
    } 
    return result 
    } 

    Collection<? extends GrantedAuthority> extractAuthorities(Authentication authentication) { 
    return authentication.getAuthorities(); 
    } 

}