package com.njzscloud.common.security.permission;

import org.springframework.security.core.Authentication;
import org.springframework.security.core.GrantedAuthority;

import java.util.Collection;

/**
 * 投票器
 */
public class PermissionVoter {

    int ACCESS_GRANTED = 1;

    int ACCESS_ABSTAIN = 0;

    int ACCESS_DENIED = -1;

    public int vote(Authentication authentication, Object object, Collection<String> attributes) {
        if (authentication == null) {
            return ACCESS_DENIED;
        }
        int result = ACCESS_ABSTAIN;
        Collection<? extends GrantedAuthority> authorities = authentication.getAuthorities();
        for (String attribute : attributes) {
            result = ACCESS_DENIED;
            for (GrantedAuthority authority : authorities) {
                if (attribute.equals(authority.getAuthority())) {
                    return ACCESS_GRANTED;
                }
            }
        }
        return result;
    }
}
