package com.tofly.auth.config;

import com.tofly.common.core.constant.SecurityConstants;
import com.tofly.common.oauth.auth.ToFlyClientDetailsService;
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.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.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 javax.sql.DataSource;
import java.util.HashMap;
import java.util.Map;

/**
 * @author Administrator
 * OAuth 授权服务器配置
 * @date 2019/9/9  13:47
 */
@Configuration
@EnableAuthorizationServer
@AllArgsConstructor
@Slf4j
public class AuthorizationServerConfiguration extends AuthorizationServerConfigurerAdapter {

    private DataSource dataSource;
    private UserDetailsService userDetailsService;
    private RedisConnectionFactory redisConnectionFactory;
    private AuthenticationManager authenticationManager;

    //配置客户端详情信息
    @Override
    public void configure(ClientDetailsServiceConfigurer clients) throws Exception {
        ToFlyClientDetailsService toFlyClientDetailsService = new ToFlyClientDetailsService(dataSource);
        toFlyClientDetailsService.setSelectClientDetailsSql(SecurityConstants.DEFAULT_SELECT_STATEMENT);
        toFlyClientDetailsService.setFindClientDetailsSql(SecurityConstants.DEFAULT_FIND_STATEMENT);
        clients.withClientDetails(toFlyClientDetailsService);
    }

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



    //定义授权和令牌端点和令牌服务
    @Override
    public void configure(AuthorizationServerEndpointsConfigurer endpoints) throws Exception {
        //endpoints.tokenServices(tokenServices());
        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<>();
            ToflyUser user = (ToflyUser) authentication.getUserAuthentication().getPrincipal();
            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());
            ((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;
    }
}
