package ink.wgink.login.oauth2.client.converter;

import com.alibaba.fastjson.JSONObject;
import ink.wgink.pojo.bos.RoleGrantedAuthorityBO;
import ink.wgink.pojo.bos.UserInfoBO;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.oauth2.provider.token.UserAuthenticationConverter;

import java.util.*;

/**
 * @ClassName: UserAuthConverter
 * @Description: 重写用户认证
 * @Author: WangGeng
 * @Date: 2019/2/27 4:57 PM
 * @Version: 1.0
 **/
public class OAuth2ClientUserAuthConverter implements UserAuthenticationConverter {

    private static final Logger LOG = LoggerFactory.getLogger(OAuth2ClientUserAuthConverter.class);

    public OAuth2ClientUserAuthConverter() {
    }

    @Override
    public Map<String, ?> convertUserAuthentication(Authentication authentication) {
        return new LinkedHashMap();
    }

    @Override
    public Authentication extractAuthentication(Map<String, ?> map) {
        // 解析客户端的权限请求
        Object principal = map.get("user_name");
        if (!Objects.isNull(principal)) {
            // 包含用户信息，则直接抽取其中的用户信息
            principal = JSONObject.parseObject(map.get("user_info").toString(), UserInfoBO.class);
            LOG.debug("获取用户权限");
            List<LinkedHashMap<String, Object>> grantedAuthoritieList = (ArrayList<LinkedHashMap<String, Object>>) map.get("authorities");
            Set<GrantedAuthority> grantedAuthorities = new HashSet<>();
            grantedAuthoritieList.forEach(authMap -> {
                RoleGrantedAuthorityBO roleGrantedAuthorityBO = new RoleGrantedAuthorityBO((String) authMap.get("roleId"),
                        (String) authMap.get("roleName"),
                        (List<String>) authMap.get("menuUrls"),
                        (List<String>) authMap.get("inserts"),
                        (List<String>) authMap.get("deletes"),
                        (List<String>) authMap.get("updates"),
                        (List<String>) authMap.get("queries"));
                grantedAuthorities.add(roleGrantedAuthorityBO);
            });
            return new UsernamePasswordAuthenticationToken(principal, "N/A", grantedAuthorities);
        }
        return null;
    }

}
