package com.reyun.saas.security.hadler;

import com.reyun.saas.common.restResult.ResultGenerator;
import com.fasterxml.jackson.databind.ObjectMapper;
import lombok.extern.slf4j.Slf4j;
import org.springframework.http.HttpMethod;
import org.springframework.security.core.AuthenticationException;
import org.springframework.security.web.AuthenticationEntryPoint;

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

/**
 * 用户未登录时的处理

 * @date 2019-8-8 17:37:27
 */
@Slf4j
public class SecurityAuthenticationEntryPoint implements AuthenticationEntryPoint {
	@Override
	public void commence(HttpServletRequest request, HttpServletResponse response, AuthenticationException authException) throws IOException, ServletException {
		if(request.getMethod() != HttpMethod.OPTIONS.toString()) {
			log.debug("尚未登录:" + authException.getMessage());
		}
		// 1. 返回json让前端自己处理
		response.setContentType("application/json");
		response.setStatus(HttpServletResponse.SC_UNAUTHORIZED);
		try {
			ObjectMapper mapper = new ObjectMapper();
			mapper.writeValue(response.getOutputStream(),ResultGenerator.genUnauthResult());
		} catch (Exception e) {
			throw new ServletException();
		}

		// 2. 由后端直接跳转到登录页面
		/*try {
			response.sendRedirect(request.getContextPath() + "/static/login.html");
		} catch (IOException e) {
			e.printStackTrace();
		}*/
	}
}
