package com.xkcoding.oauth2.config;

import com.xkcoding.oauth2.constants.TokenConstants;
import com.xkcoding.oauth2.vo.UserVo;
import org.apache.commons.lang3.StringUtils;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.oauth2.common.DefaultOAuth2AccessToken;
import org.springframework.security.oauth2.common.OAuth2AccessToken;
import org.springframework.security.oauth2.provider.OAuth2Authentication;
import org.springframework.security.oauth2.provider.token.TokenEnhancer;
import org.springframework.web.context.request.RequestAttributes;
import org.springframework.web.context.request.RequestContextHolder;

import java.util.LinkedHashMap;
import java.util.Map;
import java.util.Objects;

/**
 * <p>
 *
 * </p>
 *
 * @author wanxinabo
 * @date 2021/7/13
 */
public class UserJwtTokenEnhancer implements TokenEnhancer {

    private String dc;

    public UserJwtTokenEnhancer(String dc) {
        this.dc = dc;
    }

    @Override
    public OAuth2AccessToken enhance(OAuth2AccessToken oAuth2AccessToken, OAuth2Authentication oAuth2Authentication) {
        if (oAuth2Authentication.getUserAuthentication() instanceof UsernamePasswordAuthenticationToken) {
            UsernamePasswordAuthenticationToken authenticationToken = (UsernamePasswordAuthenticationToken) oAuth2Authentication.getUserAuthentication();
            Map<String ,Object> info = new LinkedHashMap<>(oAuth2AccessToken.getAdditionalInformation());
            if (authenticationToken.getPrincipal() instanceof UserVo) {
                UserVo userVo = (UserVo) authenticationToken.getPrincipal();
                if(Objects.nonNull(userVo.getUserId())){
                    //当前用户id
                    info.put(TokenConstants.USER_ID,userVo.getUserId());
                    //当前用户手机号
                    info.put(TokenConstants.MOBILE,userVo.getMobile());
                    //独立部署标志
                    info.put(TokenConstants.DC,dc);
                }
                // 改request域是ThreadLocal的,线程独有的,可用用来做登录日志的处理 HandlerInterceptor
                RequestContextHolder.getRequestAttributes().setAttribute("currentUserInfo", userVo, RequestAttributes.SCOPE_REQUEST);
            }
            ((DefaultOAuth2AccessToken) oAuth2AccessToken).setAdditionalInformation(info);
        }
        return oAuth2AccessToken;
    }
}
