package com.skr.mdm.authentication.admin;

import com.skr.mdm.enums.ResultCodeEnum;
import com.skr.mdm.result.ResponseResult;
import com.skr.mdm.util.ResponseUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.http.HttpStatus;
import org.springframework.security.access.AccessDeniedException;
import org.springframework.security.web.access.AccessDeniedHandler;
import org.springframework.security.web.csrf.InvalidCsrfTokenException;
import org.springframework.security.web.csrf.MissingCsrfTokenException;
import org.springframework.stereotype.Component;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

/**
 * @author nfq
 * @date 2020/7/11 18:56
 */
@Slf4j
@Component
public class AccessDeniedAuthenticationHandler implements AccessDeniedHandler {

    @Override
    public void handle(HttpServletRequest request, HttpServletResponse response, AccessDeniedException accessDeniedException) throws IOException, ServletException {

        ResponseResult result = ResponseResult.failure(ResultCodeEnum.ACCESS_DENIED);
        if (accessDeniedException instanceof InvalidCsrfTokenException) {
            log.error("csrfToken错误:", accessDeniedException);
            result = ResponseResult.failure(ResultCodeEnum.ILLEGAL_REQUEST);
        }
        if (accessDeniedException instanceof AdminTimeCheckException) {
            result = ResponseResult.failure(ResultCodeEnum.TIME_CHECK);
        }
        if (accessDeniedException instanceof IllegalRequestException) {
            result = ResponseResult.failure(ResultCodeEnum.ILLEGAL_REQUEST);
        }
        if (accessDeniedException instanceof MissingCsrfTokenException) {
            log.error("没有找到csrfToken 请求地址：" + request.getRequestURI(), accessDeniedException);
            result = ResponseResult.failure(ResultCodeEnum.ILLEGAL_REQUEST);
        }
        ResponseUtil.responseJson(response, HttpStatus.FORBIDDEN.value(), result);

    }
}
