package com.yonge.cooleshow.common.security;

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

import javax.servlet.ServletException;
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.springframework.http.MediaType;
import org.springframework.security.authentication.InsufficientAuthenticationException;
import org.springframework.security.core.AuthenticationException;
import org.springframework.security.oauth2.common.exceptions.InvalidTokenException;
import org.springframework.security.web.AuthenticationEntryPoint;
import org.springframework.stereotype.Component;

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

@Component
public class BaseAuthenticationEntryPoint implements AuthenticationEntryPoint {

	@Override
	public void commence(HttpServletRequest request, HttpServletResponse response, AuthenticationException authException) throws IOException, ServletException {
		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;
		}

		int errorCode = 500;
		if (e instanceof InvalidTokenException || e instanceof InsufficientAuthenticationException) {
			errorCode = HttpServletResponse.SC_FORBIDDEN;
		}

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

		ObjectMapper objectMapper = new ObjectMapper();

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

}
