package com.tofly.feesapi.security.compent;

import com.tofly.feesapi.security.config.FilterPassUrlConfig;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.access.AccessDecisionManager;
import org.springframework.security.access.AccessDecisionVoter;
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 org.springframework.util.PatternMatchUtils;
import org.springframework.util.StringUtils;

import java.util.Collection;
import java.util.List;

/**
 * 自定义权限认证，获取url判断是否有权限
 */
@Component
public class ToflyAccessDecisionManager implements AccessDecisionManager {

    private List<AccessDecisionVoter<? extends Object>> decisionVoters;
    @Autowired
    private FilterPassUrlConfig filterPassUrlConfig;

    @Override
    public void decide(Authentication authentication, Object object, Collection<ConfigAttribute> configAttributes) throws AccessDeniedException, InsufficientAuthenticationException {
        String requestUrl = ((FilterInvocation) object).getRequest().getRequestURI();

        Collection<? extends GrantedAuthority> authorities = authentication.getAuthorities();

        boolean flag = authorities.stream()
                .map(GrantedAuthority::getAuthority)
                .filter(StringUtils::hasText)
                .anyMatch(x -> "ROLE_ADMIN".equals(x) || PatternMatchUtils.simpleMatch(requestUrl, x) );
        if(flag){
            return;
        }

        //自定义过滤URL未起作用，待调试，临时解决方案，在此处将过滤URL重新过滤一遍
        flag=filterPassUrlConfig.getUrls().stream()
                .anyMatch(x -> {
                    x=x.replace("**","");
                    return requestUrl.contains(x);
                });
        if(flag){
            return;
        }
        throw new AccessDeniedException("用户无访问权限");
    }

    @Override
    public boolean supports(ConfigAttribute attribute) {
        for (AccessDecisionVoter voter : this.decisionVoters) {
            if (voter.supports(attribute)) {
                return true;
            }
        }
        return false;
    }

    @Override
    public boolean supports(Class<?> clazz) {
        for (AccessDecisionVoter voter : this.decisionVoters) {
            if (!voter.supports(clazz)) {
                return false;
            }
        }
        return true;
    }
}
