package com.jeeplus.gateway.excepiton;

import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.core.io.buffer.DataBuffer;
import org.springframework.core.io.buffer.DataBufferUtils;
import org.springframework.http.HttpStatus;
import org.springframework.http.MediaType;
import org.springframework.http.server.reactive.ServerHttpResponse;
import org.springframework.security.access.AccessDeniedException;
import org.springframework.security.web.server.authorization.ServerAccessDeniedHandler;
import org.springframework.stereotype.Component;
import org.springframework.web.server.ServerWebExchange;
import reactor.core.publisher.Mono;

/**
 * 权限不足处理类，返回403
 * Author: liugaofeng
 */
@Slf4j
@Component
public class JwtAccessDeniedHandler implements ServerAccessDeniedHandler {

    @Autowired
    private ObjectMapper mapper;

    @Override
    public Mono <Void> handle(ServerWebExchange exchange, AccessDeniedException e) {
        //登陆状态下，权限不足执行该方法
        log.error ( "权限不足：" + e.getMessage ( ) );

        ServerHttpResponse response = exchange.getResponse ( );
        response.setStatusCode ( HttpStatus.FORBIDDEN );
        response.getHeaders ( ).setContentType ( MediaType.APPLICATION_JSON_UTF8 );

        try {
            DataBuffer buffer = response.bufferFactory ( ).wrap ( mapper.writeValueAsBytes ( "权限不足：" + e.getMessage ( ) ) );
            return response.writeWith ( Mono.just ( buffer ) ).doOnError ( (error) -> {
                DataBufferUtils.release ( buffer );
            } );
        } catch (JsonProcessingException var5) {
            return Mono.error ( var5 );
        }

    }
}
