package com.tuoheng.config;

import com.alibaba.fastjson.JSONObject;
import com.tuoheng.mapper.UserMapper;
import com.tuoheng.model.dto.UserBaseInfoDto;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.oauth2.core.OAuth2TokenType;
import org.springframework.security.oauth2.core.oidc.endpoint.OidcParameterNames;
import org.springframework.security.oauth2.server.authorization.token.JwtEncodingContext;
import org.springframework.security.oauth2.server.authorization.token.OAuth2TokenCustomizer;

import java.util.Collection;
import java.util.Collections;
import java.util.List;
import java.util.stream.Collectors;

/**
 * @author chenjiandong
 * @description: TODO
 * @date 2022/9/22 15:06
 */
@Configuration(proxyBeanMethods = false)
public class IdTokenCustomizerConfig {

    @Autowired
    private UserMapper userMapper;

    @Bean
    public OAuth2TokenCustomizer<JwtEncodingContext> tokenCustomizer() {
        return (context) -> {
            if ("id_token".equals(context.getTokenType().getValue())) {
                context.getClaims().claims(claims ->
                        claims.put("role", context.getPrincipal().getAuthorities()
                                .stream().map(GrantedAuthority::getAuthority)
                                .collect(Collectors.toSet())));
            }
            if ("access_token".equals(context.getTokenType().getValue())) {
                UserBaseInfoDto userBaseInfoDto = userMapper.getUserBaseInfo(context.getPrincipal().getName());
                context.getClaims().claims(claims ->
                        claims.put("scope", context.getPrincipal().getAuthorities()
                                .stream().map(GrantedAuthority::getAuthority)
                                .collect(Collectors.toSet())))
                        .claims(claims ->
                                claims.put("username", context.getPrincipal().getName()))
                        .claims(claims ->
                                claims.put("oUserId", userBaseInfoDto.getUserId()))
                        .claims(claims ->
                                claims.put("clientRoleList", JSONObject.toJSONString(userBaseInfoDto.getClientRoleDtoList())));
            }
        };
    }
}