package com.philisense.www.access;

import com.philisense.www.utils.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
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.stereotype.Service;

import java.util.Collection;
import java.util.Iterator;

@Service
public class WebRestURLAccessDecisionManager implements AccessDecisionManager {

    private static final Logger log = LoggerFactory.getLogger(WebRestURLAccessDecisionManager.class);

    @Override
    public void decide(Authentication authentication, Object object, Collection<ConfigAttribute> configAttributes) throws AccessDeniedException, InsufficientAuthenticationException {
        if(StringUtils.isNull(configAttributes) || configAttributes.isEmpty()) {
            return;
        }

        log.info("{} 正在访问的url是：{}", authentication.getAuthorities(), object.toString());

        ConfigAttribute c;
        String needRole;
        for(Iterator<ConfigAttribute> iter = configAttributes.iterator(); iter.hasNext(); ) {
            c = iter.next();
            needRole = c.getAttribute();
            if("ROLE_NEVER_EXIST".equals(needRole.trim())) {
                log.info("{}, 该 【{}】 不验权", needRole.trim(), object.toString());
                return ;
            }
            for(GrantedAuthority ga : authentication.getAuthorities()) {
                if(needRole.trim().equals(ga.getAuthority())) {
                    return ;
                }
            }
        }

        throw new AccessDeniedException("访问了没有权限的资源,让我们去捕捉----- 没有权限访问！");
    }

    @Override
    public boolean supports(ConfigAttribute attribute) {
        return true;
    }

    @Override
    public boolean supports(Class<?> clazz) {
        return true;
    }
}