package com.yonge.cooleshow.common.security;

import java.io.IOException;
import java.io.PrintWriter;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.lang3.exception.ExceptionUtils;
import org.codehaus.jackson.map.ObjectMapper;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.http.MediaType;
import org.springframework.security.access.AccessDeniedException;
import org.springframework.security.oauth2.provider.error.OAuth2AccessDeniedHandler;
import org.springframework.stereotype.Component;

import com.yonge.cooleshow.common.constant.CommonConstants;
import com.yonge.cooleshow.common.entity.HttpResponseResult;

@Component
public class BaseAccessDeniedHandler extends OAuth2AccessDeniedHandler {

	private final static Logger logger = LoggerFactory.getLogger(BaseAccessDeniedHandler.class);

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

		logger.info("授权失败，禁止访问 {}", request.getRequestURI());

		response.setCharacterEncoding(CommonConstants.UTF8);
		response.setContentType(MediaType.APPLICATION_JSON_UTF8_VALUE);
		response.setStatus(HttpServletResponse.SC_OK);
		PrintWriter printWriter = response.getWriter();
		
		Throwable e = ExceptionUtils.getRootCause(authException);
		if (e == null) {
			e = authException;
		}

		HttpResponseResult result = new HttpResponseResult(false, HttpServletResponse.SC_FORBIDDEN, null, e.getMessage());

		ObjectMapper objectMapper = new ObjectMapper();

		printWriter.append(objectMapper.writeValueAsString(result));
		printWriter.flush();
		printWriter.close();
	}
}
