package com.tofly.auth.config;

import com.baomidou.mybatisplus.core.toolkit.ObjectUtils;
import com.tofly.common.core.constant.SecurityConstants;
import com.tofly.common.oauth.auth.ToflyUser;
import com.tofly.common.oauth.compent.ToflyWebResponseExceptionTranslator;
import lombok.AllArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Primary;
import org.springframework.data.redis.connection.RedisConnectionFactory;
import org.springframework.http.HttpMethod;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.oauth2.common.DefaultOAuth2AccessToken;
import org.springframework.security.oauth2.config.annotation.configurers.ClientDetailsServiceConfigurer;
import org.springframework.security.oauth2.config.annotation.web.configuration.AuthorizationServerConfigurerAdapter;
import org.springframework.security.oauth2.config.annotation.web.configuration.EnableAuthorizationServer;
import org.springframework.security.oauth2.config.annotation.web.configurers.AuthorizationServerEndpointsConfigurer;
import org.springframework.security.oauth2.config.annotation.web.configurers.AuthorizationServerSecurityConfigurer;
import org.springframework.security.oauth2.provider.ClientDetails;
import org.springframework.security.oauth2.provider.client.BaseClientDetails;
import org.springframework.security.oauth2.provider.token.AuthorizationServerTokenServices;
import org.springframework.security.oauth2.provider.token.DefaultTokenServices;
import org.springframework.security.oauth2.provider.token.TokenEnhancer;
import org.springframework.security.oauth2.provider.token.TokenStore;
import org.springframework.security.oauth2.provider.token.store.redis.RedisTokenStore;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.Map;

@Configuration
@EnableAuthorizationServer
@AllArgsConstructor
@Slf4j
public class AuthorizationServerConfiguration extends AuthorizationServerConfigurerAdapter {

    private final UserDetailsService userDetailsService;
    private final RedisConnectionFactory redisConnectionFactory;
    private final AuthenticationManager authenticationManager;

    // 配置客户端详情信息
    @Override
    public void configure(ClientDetailsServiceConfigurer clients) throws Exception {
        ToflyMemoryClientDetailsService clientDetailsService = new ToflyMemoryClientDetailsService();
        BaseClientDetails clientDetails = new BaseClientDetails();
        clientDetails.setClientId("tofly");
        clientDetails.setClientSecret("tofly");
        clientDetails.setScope(new ArrayList<String>() {{ add("server"); }});
        clientDetails.setAuthorizedGrantTypes(new ArrayList<String>() {{
            add("password");
            add("authorization_code");
            add("refresh_token");
            add("client_credentials");
        }});
        clientDetails.setAutoApproveScopes(new ArrayList<String>() {{
            add("true");
        }});
        HashMap<String, ClientDetails> map = new HashMap<>();
        map.put("tofly", clientDetails);
        clientDetailsService.setClientDetailsStore(map);
        clients.withClientDetails(clientDetailsService);
    }

    // 配置令牌端点(Token Endpoint)的安全与权限访问
    @Override
    public void configure(AuthorizationServerSecurityConfigurer security) {
        security.allowFormAuthenticationForClients()
                .checkTokenAccess("isAuthenticated()");
    }


    //定义授权和令牌端点和令牌服务
    @Override
    public void configure(AuthorizationServerEndpointsConfigurer endpoints) {
        endpoints.tokenServices(tokenServices());
        endpoints.allowedTokenEndpointRequestMethods(HttpMethod.GET, HttpMethod.POST)
                .tokenStore(tokenStore())
                .tokenEnhancer(tokenEnhancer())
                .authenticationManager(authenticationManager)
                .userDetailsService(userDetailsService)
                //.reuseRefreshTokens(false)
                .reuseRefreshTokens(true)
                .exceptionTranslator(new ToflyWebResponseExceptionTranslator());
    }


    @Bean
    public TokenStore tokenStore() {
        RedisTokenStore tokenStore = new RedisTokenStore(redisConnectionFactory);
        tokenStore.setPrefix(SecurityConstants.PROJECT_PREFIX + SecurityConstants.OAUTH_PREFIX);
        return tokenStore;
    }

    @Bean
    public TokenEnhancer tokenEnhancer() {
        return (accessToken, authentication) -> {
            final Map<String, Object> additionalInfo = new HashMap<>();
            Authentication userAuthentication = authentication.getUserAuthentication();
            if (ObjectUtils.isNotNull(userAuthentication)) {
                ToflyUser user = (ToflyUser) userAuthentication.getPrincipal();
                if (ObjectUtils.isNotNull(user)) {
                    additionalInfo.put(SecurityConstants.DETAILS_LICENSE, SecurityConstants.PROJECT_LICENSE);
                    additionalInfo.put(SecurityConstants.DETAILS_USERNAME, user.getUsername());
                    additionalInfo.put(SecurityConstants.DETAILS_USER_ID, user.getUserid());
                    additionalInfo.put(SecurityConstants.DETAILS_DEPT_ID, user.getDepartmentId());
                    additionalInfo.put(SecurityConstants.DETAILS_USER_LEVEL, user.getUserLevel());
                    additionalInfo.put(SecurityConstants.DETAILS_DEPT_NAME, user.getDepartemntName());
                    additionalInfo.put(SecurityConstants.DETAILS_REAL_NAME, user.getRealName());
                    additionalInfo.put(SecurityConstants.DETAILS_USER_AVATAR, user.getAvatar());
                    additionalInfo.put(SecurityConstants.PARENT_COMPANY_ID, user.getParentCompanyId());
                    additionalInfo.put(SecurityConstants.PARENT_COMPANY_NAME, user.getParentCompanyName());
                    additionalInfo.put(SecurityConstants.COMPANY_ID, user.getCompanyId());
                    additionalInfo.put(SecurityConstants.COMPANY_NAME, user.getCompanyName());
                }
            }
            ((DefaultOAuth2AccessToken) accessToken).setAdditionalInformation(additionalInfo);
            return accessToken;
        };
    }

    @Primary
    @Bean
    public AuthorizationServerTokenServices tokenServices() {
        DefaultTokenServices defaultTokenServices = new DefaultTokenServices();
        defaultTokenServices.setAccessTokenValiditySeconds(-1);
        defaultTokenServices.setRefreshTokenValiditySeconds(500);
        defaultTokenServices.setSupportRefreshToken(true);
        //defaultTokenServices.setReuseRefreshToken(false);
        defaultTokenServices.setReuseRefreshToken(true);
        defaultTokenServices.setTokenStore(tokenStore());
        defaultTokenServices.setTokenEnhancer(tokenEnhancer());

        defaultTokenServices.setAuthenticationManager(authenticationManager);
        return defaultTokenServices;
    }
}
