package com.ym.mec.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.codehaus.jackson.map.ObjectMapper;
import org.springframework.http.MediaType;
import org.springframework.security.core.AuthenticationException;
import org.springframework.security.web.AuthenticationEntryPoint;
import org.springframework.stereotype.Component;

import com.ym.mec.common.constant.CommonConstants;
import com.ym.mec.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();

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

		ObjectMapper objectMapper = new ObjectMapper();

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

}
