/**
 * Copyright (c) 2022 cloud Authors. All Rights Reserved.
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
package com.lutao.cloud.gateway.filter;
import cn.hutool.core.util.StrUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.cloud.gateway.filter.GatewayFilter;
import org.springframework.cloud.gateway.filter.factory.AbstractGatewayFilterFactory;
import org.springframework.http.HttpMethod;
import org.springframework.http.HttpStatus;
import org.springframework.http.server.reactive.ServerHttpRequest;
import org.springframework.http.server.reactive.ServerHttpResponse;
import org.springframework.stereotype.Component;

/**

 * @date 2018/8/21 演示环境过滤处理
 */
@Slf4j
@Component
public class PreviewGatewayFilter extends AbstractGatewayFilterFactory{

	private static final String TOKEN = "token";
	/**
	 * Unless required by applicable law or agreed to in writing, software
	 * distributed under the License is distributed on an "AS IS" BASIS,
	 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
	 * See the License for the specific language governing permissions and
	 * limitations under the License.
	 * @param config
	 * @return
	 */
	@Override
	public GatewayFilter apply(Object config){
		return (exchange, chain) ->{
			ServerHttpRequest request = exchange.getRequest();
			// GET，直接向下执行
			if (StrUtil.equalsIgnoreCase(request.getMethodValue(), HttpMethod.GET.name())
					|| StrUtil.containsIgnoreCase(request.getURI().getPath(), TOKEN)){
				return chain.filter(exchange);
			}
			log.warn("演示环境不能操作->{},{}", request.getMethodValue(), request.getURI().getPath());
			ServerHttpResponse response = exchange.getResponse();
			response.setStatusCode(HttpStatus.LOCKED);
			return response.setComplete();
		};
	}

}
