package com.diagbot.config;

import com.diagbot.facade.SysDictionaryFacade;
import com.diagbot.service.UrlUserService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.core.io.ClassPathResource;
import org.springframework.security.authentication.AuthenticationManager;
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.TokenEnhancer;
import org.springframework.security.oauth2.provider.token.TokenEnhancerChain;
import org.springframework.security.oauth2.provider.token.TokenStore;
import org.springframework.security.oauth2.provider.token.store.JwtAccessTokenConverter;
import org.springframework.security.oauth2.provider.token.store.JwtTokenStore;
import org.springframework.security.oauth2.provider.token.store.KeyStoreKeyFactory;

import java.util.Arrays;

/**
 * @Description: OAuth2授权认证配置类
 * @author: gaodm
 * @time: 2018/8/2 14:24
 */
@Configuration
@EnableAuthorizationServer
@Slf4j
public class OAuth2Configurer extends AuthorizationServerConfigurerAdapter {
    @Autowired
    private UrlUserService urlUserService;
    @Autowired
    private SysDictionaryFacade sysDictionaryFacade;

    @Override
    public void configure(ClientDetailsServiceConfigurer clients) throws Exception {
        int accessToken = 24 * 3600;
        int refreshToken = 30 * 24 * 3600;
        if (sysDictionaryFacade.getDictionaryWithKey() != null
                && sysDictionaryFacade.getDictionaryWithKey().containsKey("31")
                && sysDictionaryFacade.getDictionaryWithKey().get("31").containsKey("accessToken")
                && sysDictionaryFacade.getDictionaryWithKey().get("31").containsKey("refreshToken")) {
            accessToken = Integer.parseInt(sysDictionaryFacade.getDictionaryWithKey().get("31").get("accessToken"));
            refreshToken = Integer.parseInt(sysDictionaryFacade.getDictionaryWithKey().get("31").get("refreshToken"));
        }
        clients.inMemory()
                .withClient("uaa-service")
                .secret("{noop}123456")
                .scopes("service")
                .autoApprove(true)
                .authorizedGrantTypes("implicit", "refresh_token", "password", "authorization_code")
                .accessTokenValiditySeconds(accessToken)
                .refreshTokenValiditySeconds(refreshToken);
    }

    /**
     * 注入自定义token生成方式
     *
     * @return
     */
    @Bean
    public TokenEnhancer customerEnhancer() {
        return new CustomTokenEnhancer();
    }

    @Override
    public void configure(AuthorizationServerEndpointsConfigurer endpoints) throws Exception {
        //指定认证管理器
        endpoints.authenticationManager(authenticationManager).userDetailsService(urlUserService);
        //指定token存储位置
        endpoints.tokenStore(new JwtTokenStore(jwtTokenEnhancerServer()));
        // 自定义token生成方式
        TokenEnhancerChain tokenEnhancerChain = new TokenEnhancerChain();
        tokenEnhancerChain.setTokenEnhancers(Arrays.asList(customerEnhancer(), jwtTokenEnhancerServer()));
        endpoints.tokenEnhancer(tokenEnhancerChain);
    }

    @Override
    public void configure(AuthorizationServerSecurityConfigurer security) throws Exception {
        security.tokenKeyAccess("permitAll()")
                .checkTokenAccess("isAuthenticated()")
                .allowFormAuthenticationForClients();
    }

    @Autowired
    @Qualifier("authenticationManagerBean")
    private AuthenticationManager authenticationManager;

    @Bean("JwtTokenEnhancerServer")
    protected JwtAccessTokenConverter jwtTokenEnhancerServer() {
        KeyStoreKeyFactory keyStoreKeyFactory = new KeyStoreKeyFactory(new ClassPathResource("diagbot-jwt.jks"), "diagbot123456".toCharArray());
        JwtAccessTokenConverter converter = new JwtAccessTokenConverter();
        converter.setKeyPair(keyStoreKeyFactory.getKeyPair("diagbot-jwt"));
        log.info("Created jwtTokenEnhancerServer success");
        return converter;
    }
}
