
/**
 * Copyright 2008-2009. Chongqing Communications Industry Services Co.,Ltd Information Technology Branch. All rights reserved. <a>http://www.crunii.com</a>
 */
package com.crunii.micro.gateway.config;

import com.crunii.micro.common.constants.CommonConstants;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.util.AntPathMatcher;
import springfox.documentation.builders.ApiInfoBuilder;
import springfox.documentation.builders.PathSelectors;
import springfox.documentation.oas.annotations.EnableOpenApi;
import springfox.documentation.service.*;
import springfox.documentation.spi.DocumentationType;
import springfox.documentation.spi.service.contexts.SecurityContext;
import springfox.documentation.spring.web.plugins.Docket;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

/**
 * <pre>
 * 	 本地和测试环境需要api 生产环境安全原因不加载
 * </pre>
 *
 * @author 田平 create 2018年10月15日下午2:39:36
 */
@Configuration
@ConditionalOnProperty(name = "swagger.enabled", havingValue = "true")
@EnableOpenApi
public class GatewaySwaggerConfiguration {

	@Value("${spring.application.name}")
	private String appName;

	private AntPathMatcher matcher = new AntPathMatcher();

	@Bean
	public Docket createRestApi() {
		return new Docket(DocumentationType.OAS_30)
				.apiInfo(apiInfo())
				.select()
				.paths(PathSelectors.any())
				.build()
				.securitySchemes(securitySchemes())
				.securityContexts(securityContexts());
	}

	private ApiInfo apiInfo() {
		return new ApiInfoBuilder().title(appName + " Rest Api").version("1.0").build();
	}

	private List<SecurityScheme> securitySchemes() {
		List<SecurityScheme> schemes = new ArrayList<>();
		schemes.add(new ApiKey("Authorization", "token", "header"));
		return schemes;
	}

	private List<SecurityContext> securityContexts() {
		return Arrays.asList(SecurityContext.builder()
				.securityReferences(defaultAuth())
				.operationSelector(ctx -> matcher.match(CommonConstants.AUTH_PATTERN, ctx.requestMappingPattern()))
				.build());
	}

	private List<SecurityReference> defaultAuth() {
		AuthorizationScope[] authorizationScopes = { new AuthorizationScope("global", "accessEverything") };
		return Arrays.asList(new SecurityReference("Authorization", authorizationScopes));
	}

}
