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

import cn.reghao.bnt.web.admin.service.MenuService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.security.access.ConfigAttribute;
import org.springframework.security.access.SecurityConfig;
import org.springframework.security.web.FilterInvocation;
import org.springframework.security.web.access.intercept.FilterInvocationSecurityMetadataSource;
import org.springframework.stereotype.Component;
import org.springframework.util.CollectionUtils;

import jakarta.servlet.http.HttpServletRequest;
import java.util.Collection;
import java.util.List;
import java.util.Locale;

/**
 * @author reghao
 * @date 2024-08-22 20:41:48
 */
@Slf4j
@Component
@Deprecated
public class MySecurityMetadataSource implements FilterInvocationSecurityMetadataSource {
    private final MenuService menuService;

    public MySecurityMetadataSource(MenuService menuService) {
        this.menuService = menuService;
    }

    @Override
    public Collection<ConfigAttribute> getAttributes(Object object) throws IllegalArgumentException {
        // 获取 url
        FilterInvocation filterInvocation = (FilterInvocation) object;
        HttpServletRequest request = filterInvocation.getRequest();
        String method = request.getMethod();
        if (method == null) {
            method = "";
        }

        String requestUrl = request.getRequestURI();
        // 获取可访问 url 的角色集合
        List<String> roles = menuService.getRolesByUrl(method, requestUrl);
        String[] attributes = roles.toArray(new String[0]);
        return SecurityConfig.createList(attributes);
    }

    @Override
    public Collection<ConfigAttribute> getAllConfigAttributes() {
        return null;
    }

    // 是否能为 Class 提供 Collection<ConfigAttribute>
    @Override
    public boolean supports(Class<?> clazz) {
        return true;
    }
}
