package cn.com.capcloud.core.system.security;

import cn.com.capcloud.core.system.exception.CustomException;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import org.springframework.http.HttpStatus;
import org.springframework.security.access.AccessDecisionManager;
import org.springframework.security.access.ConfigAttribute;
import org.springframework.security.authentication.AnonymousAuthenticationToken;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.stereotype.Component;

import java.util.Collection;

@Component
public class UrlAccessDecisionManager implements AccessDecisionManager {
    Logger logger = LogManager.getLogger();
    @Override
    public void decide(Authentication authentication, Object object, Collection<ConfigAttribute> configAttributes) {
        for (ConfigAttribute configAttribute : configAttributes) {
            String needRoleName = configAttribute.getAttribute();
            if ("ROLE_LOGIN".equals(needRoleName)) {
                if (authentication instanceof AnonymousAuthenticationToken) {
                    logger.info("当前未登录 | 不允许访问资源");
                    throw new CustomException("4010",HttpStatus.UNAUTHORIZED);//未登录不允许访问资源
                } else if (authentication instanceof UsernamePasswordAuthenticationToken) {
                    // 当前已登录 | 允许访问资源
                    return;
                }
            }
            for (GrantedAuthority authority : authentication.getAuthorities()) {
                if (authority.getAuthority().equals(needRoleName)) {
                    return;
                }
            }
        }
        logger.error("访问资源不存在 或 权限不足");
        throw new CustomException("4030",HttpStatus.UNAUTHORIZED);//该资源暂未开放，或被下架。前端可以控制跳到首页
    }

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

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