package com.css.simulation.resource.server.infra.oauth;

import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.AuthorityUtils;
import org.springframework.security.oauth2.provider.token.DefaultUserAuthenticationConverter;
import org.springframework.stereotype.Component;
import org.springframework.util.StringUtils;

import java.util.*;

@Component
public class MyUserAuthenticationConverter extends DefaultUserAuthenticationConverter {

    @Override
    public Authentication extractAuthentication(Map<String, ?> map) {
        List<GrantedAuthority> list = new LinkedList<>();
        //解析权限
        if (map.containsKey(AUTHORITIES)) {
            Object authorities = map.get(AUTHORITIES);
            if (authorities instanceof String) {
                list = AuthorityUtils.commaSeparatedStringToAuthorityList((String) authorities);
            } else if (authorities instanceof Collection) {
                list = AuthorityUtils.commaSeparatedStringToAuthorityList(StringUtils.collectionToCommaDelimitedString((Collection) authorities));
            } else {
                throw new IllegalArgumentException("Authorities must be either a String or a Collection");
            }
        }
        //解析当前登录人信息
        MyUserDetails userDetails = new MyUserDetails();
        userDetails.setId((String) map.get("id"));
        userDetails.setUsername((String) map.get("username"));
        userDetails.setRoleCode((String) map.get("roleCode"));
        userDetails.setUseType((String) map.get("useType"));
        userDetails.setCreateUserId((String) map.get("createUserId"));
        return new UsernamePasswordAuthenticationToken(userDetails, "N/A", list);
    }



}
