package com.cm.common.handler;

import com.alibaba.fastjson.JSONObject;
import com.cm.common.enums.ErrorResultCodeEnum;
import com.cm.common.result.ErrorResult;
import org.springframework.http.HttpStatus;
import org.springframework.http.MediaType;
import org.springframework.security.access.AccessDeniedException;
import org.springframework.security.web.access.AccessDeniedHandler;

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

/**
 * @ClassName: AccessDenyHandler
 * @Description: 权限校验失败
 * @Author: WangGeng
 * @Date: 2019-06-09 13:58
 * @Version: 1.0
 **/
public class AccessDenyHandler implements AccessDeniedHandler {

    @Override
    public void handle(HttpServletRequest request, HttpServletResponse response, AccessDeniedException accessDeniedException) throws IOException, ServletException {
        String contentType = request.getContentType();
        if (contentType != null && contentType.contains(MediaType.APPLICATION_JSON_VALUE)) {
            response.setContentType(MediaType.APPLICATION_JSON_UTF8_VALUE);
            response.setStatus(HttpStatus.FORBIDDEN.value());
            response.getWriter().write(JSONObject.toJSONString(new ErrorResult(ErrorResultCodeEnum.PERMISSION_ERROR.getValue(), "权限不足")));
        } else {
            response.setContentType(MediaType.TEXT_HTML_VALUE);
            request.getRequestDispatcher("/error/403.html").forward(request, response);
        }
    }

}
