package cn.reghao.bnt.web.admin.security.access;

import lombok.extern.slf4j.Slf4j;
import org.springframework.security.access.AccessDecisionManager;
import org.springframework.security.access.AccessDeniedException;
import org.springframework.security.access.ConfigAttribute;
import org.springframework.security.authentication.InsufficientAuthenticationException;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.web.FilterInvocation;
import org.springframework.stereotype.Component;

import java.util.Collection;

/**
 * @author reghao
 * @date 2024-08-22 20:40:36
 */
@Slf4j
@Component
@Deprecated
public class MyAccessDecisionManager implements AccessDecisionManager {
    @Override
    public void decide(Authentication authentication, Object object, Collection<ConfigAttribute> configAttributes)
            throws AccessDeniedException, InsufficientAuthenticationException {
        String url = "";
        if (object instanceof FilterInvocation) {
            FilterInvocation fi = (FilterInvocation) object;
            url = fi.getRequestUrl();
        }

        if (configAttributes.isEmpty()) {
            log.info("访问 {} 不需要任何权限", url);
            return;
        }

        // 获取用户拥有的权限信息
        Collection<? extends GrantedAuthority> authorities = authentication.getAuthorities();
        // 判断用户拥有的角色是否可访问 url
        for (ConfigAttribute configAttribute : configAttributes) {
            String attribute = configAttribute.getAttribute();
            for (GrantedAuthority authority : authorities) {
                if (attribute.equals(authority.getAuthority())) {
                    return;
                }
            }
        }

        // 没有匹配就抛出异常
        throw new AccessDeniedException(String.format("权限不足,无法访问 %s", url));
    }

    // 此 AccessDecisionManager 实现是否可以处理传递的 ConfigAttribute
    @Override
    public boolean supports(ConfigAttribute attribute) {
        return true;
    }

    // 此 AccessDecisionManager 实现是否能够提供该对象类型的访问控制决策。
    @Override
    public boolean supports(Class<?> clazz) {
        return true;
    }
}
