package com.uas.finance.filter;

import com.uas.sso.SSOConfig;
import com.uas.sso.SSOHelper;
import com.uas.sso.SSOToken;
import org.springframework.web.servlet.handler.HandlerInterceptorAdapter;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.logging.Logger;

/**
 * spring mvc 接口，SSO 过滤器验证登录状态
 * 
 * @author yingp
 *
 */
public abstract class AbstractSSOInterceptor extends HandlerInterceptorAdapter {

	private static final Logger logger = Logger.getLogger(com.uas.sso.web.spring.AbstractSSOInterceptor.class.getName());

	/**
	 * 未登录情况下的处理
	 * 
	 * @param request
	 * @param response
	 * @return true继续，false跳转登录
	 */
	protected abstract boolean onAuthenticateFailed(HttpServletRequest request, HttpServletResponse response);

	/**
	 * 已登录情况下的处理
	 * 
	 * @param request
	 * @param response
	 * @return
	 */
	protected abstract void onAuthenticateSuccess(HttpServletRequest request, HttpServletResponse response);

	/**
	 * 跳转登录
	 * 
	 * @param request
	 * @param response
	 * @throws IOException
	 */
	protected void sendRedirect(HttpServletRequest request, HttpServletResponse response) throws IOException {
		boolean cross = SSOHelper.isCrossDomain(request);
		if (cross) {
			request.getSession().setAttribute(SSOConfig.SSOReferer, request.getRequestURL());
			response.sendRedirect(SSOHelper.getSSOService().getConfig().getCrossProxyUri());
		} else {
			SSOHelper.clearRedirectLogin(request, response);
		}
	}

	private final boolean authenticate(HttpServletRequest request, HttpServletResponse response) throws IOException {
		SSOToken token = SSOHelper.getToken(request);
		if (token == null) {
			// 返回false表示需要跳转登录
			if (!onAuthenticateFailed(request, response)) {
				if (isRedirectAble(request)) {
					/**
					 * 重新登录
					 */
					logger.fine("logout. request url:" + request.getRequestURL());
					sendRedirect(request, response);
				}
				return false;
			} else {
				return true;
			}
		}
		request.setAttribute(SSOConfig.SSO_TOKEN_ATTR, token);
		onAuthenticateSuccess(request, response);
		return true;
	}

	@Override
	public final boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
		if (super.preHandle(request, response, handler)) {
			return authenticate(request, response);
		}
		return false;
	}

	protected boolean isRedirectAble(HttpServletRequest request) {
		return null == request.getHeader("x-requested-with")
				&& (null == request.getHeader("Accept") || !request.getHeader("Accept").contains("application/json"));
	}
}
