package com.cm.common.utils.authority;

import com.alibaba.fastjson.JSON;
import com.cm.common.pojo.bos.RoleGrantedAuthority;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.AuthorityUtils;
import org.springframework.security.core.authority.SimpleGrantedAuthority;

import java.util.Collection;
import java.util.HashSet;
import java.util.Set;

/**
 * @ClassName: AuthorityUtil
 * @Description: 权限工具
 * @Author: WangGeng
 * @Date: 2019-06-17 22:25
 * @Version: 1.0
 **/
public class AuthorityUtil extends AuthorityUtils {

    /**
     * 权限列表转集合
     *
     * @param userAuthorities
     * @return
     */
    public static Set<String> authorities(
            Collection<? extends GrantedAuthority> userAuthorities) {
        Set<String> set = new HashSet<>(userAuthorities.size());

        for (GrantedAuthority authority : userAuthorities) {
            if (authority instanceof SimpleGrantedAuthority) {
                set.add(authority.getAuthority());
            }
            if (authority instanceof RoleGrantedAuthority) {
                RoleGrantedAuthority roleGrantedAuthority = (RoleGrantedAuthority) authority;
                set.add(JSON.toJSONString(roleGrantedAuthority).replace(",", "_wg_"));
            }
        }

        return set;
    }

}
