package com.tofly.common.oauth.compent;

import com.fasterxml.jackson.databind.ObjectMapper;
import com.tofly.common.core.constant.CommonConstants;
import com.tofly.common.core.entity.ResultRespone;
import com.tofly.common.oauth.exception.ToflyDeniedException;
import lombok.AllArgsConstructor;
import lombok.SneakyThrows;
import lombok.extern.slf4j.Slf4j;
import org.springframework.http.HttpStatus;
import org.springframework.security.access.AccessDeniedException;
import org.springframework.security.oauth2.provider.error.OAuth2AccessDeniedHandler;
import org.springframework.stereotype.Component;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.PrintWriter;

/**
 * @author Administrator
 * @date 2019/9/16  10:47
 *  * 授权拒绝处理器，覆盖默认的OAuth2AccessDeniedHandler
 *  * 包装失败信息到ToflyDeniedException
 */
@Slf4j
@AllArgsConstructor
@Component
public class ToflyAccessDeniedHandler extends OAuth2AccessDeniedHandler {
    private  ObjectMapper objectMapper;


    /**
     * 授权拒绝处理
     */
    @Override
    @SneakyThrows
    public void handle(HttpServletRequest request, HttpServletResponse response, AccessDeniedException authException) {
        log.info("授权失败，禁止访问 {}", request.getRequestURI());
        response.setCharacterEncoding(CommonConstants.UTF8);
        response.setContentType(CommonConstants.CONTENT_TYPE);
        ResultRespone<ToflyDeniedException> result = ResultRespone.failed(new ToflyDeniedException("授权失败，禁止访问"));
        response.setStatus(HttpStatus.FORBIDDEN.value());
        PrintWriter printWriter = response.getWriter();
        printWriter.append(objectMapper.writeValueAsString(result));
    }
}
