package com.enterprise.manage.core.secure.support;

import com.enterprise.manage.modules.system.domain.po.Menu;
import com.enterprise.manage.modules.system.domain.po.User;
import org.springframework.security.access.PermissionEvaluator;
import org.springframework.security.core.Authentication;
import org.springframework.stereotype.Component;

import java.io.Serializable;
import java.util.HashSet;
import java.util.List;
import java.util.Set;

/**
 * spring security 自定义权限注解实现
 *
 * @author PeiZhi Guo
 * 2021-2-18 16:24
 */
@Component
public class SecurePermissionSupport implements PermissionEvaluator {

    /**
     * 自定义 spring security 权限认证 @hasPermission
     */
    @Override
    public boolean hasPermission(Authentication authentication, Object targetDomainObject, Object permission) {
        User securityUserDetails = (User) authentication.getPrincipal();
        List<Menu> menuList = securityUserDetails.getMenuList();
        Set<String> permissions = new HashSet<>();
        for (Menu sysMenu : menuList) {
            permissions.add(sysMenu.getCode());
        }
        return permissions.contains(permission.toString());
    }

    @Override
    public boolean hasPermission(Authentication authentication, Serializable serializable, String s, Object o) {
        return false;
    }
}
