package gaf3.core.gateway.webfilter

import org.slf4j.LoggerFactory
import org.springframework.cloud.gateway.support.ServerWebExchangeUtils
import org.springframework.http.HttpStatus
import org.springframework.web.server.ServerWebExchange
import org.springframework.web.server.WebFilter
import org.springframework.web.server.WebFilterChain
import reactor.core.publisher.Mono

class ApiAccessFilter @JvmOverloads constructor(val includes: Array<String> = emptyArray(), val excludes: Array<String> = emptyArray()): WebFilter {
    override fun filter(exchange: ServerWebExchange, chain: WebFilterChain) : Mono<Void>{
        log.debug("[ApiAccess] start...")
        val path = exchange.request.path.value()
        log.debug("[ApiAccess] path : {}", path)
        return if(path.startsWith("/api")) {
            chain.filter(exchange.mutate().build())
        } else if ((includes.isNotEmpty() && !includes.any { path.startsWith(it) })
                || excludes.any { path.startsWith(it) }) {
            chain.filter(exchange.mutate().build())
        } else {
            ServerWebExchangeUtils.setResponseStatus(exchange, HttpStatus.FORBIDDEN)
            exchange.response.setComplete()
        }
    }

    companion object {
        internal val log = LoggerFactory.getLogger(ApiAccessFilter::class.java)
    }

}
