package com.kiisoo.ic.filter;

import com.alibaba.fastjson.JSONObject;
import org.apache.shiro.web.filter.authc.FormAuthenticationFilter;

import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.PrintWriter;

/**
 * @author Larry 统一判断Ajax登录过期
 */
public class AjaxSessionTimeoutFilter extends FormAuthenticationFilter {

    private static final String RS_KEY = "9999";
    private static final String RS_VALUE = "会话过期请重新登录";
    private static final String XMLHTTP_REQUEST = "XMLHttpRequest";
    private static final String X_REQUESTED_WITH = "X-Requested-With";
    private static final String SESSIONSTATUS = "sessionstatus";
    private static final String TIMEOUT = "timeout";

    @Override
    protected boolean onAccessDenied(ServletRequest request, ServletResponse response) throws Exception {
        HttpServletRequest httpServletRequest = (HttpServletRequest) request;
        HttpServletResponse httpServletResponse = (HttpServletResponse) response;

        if("OPTIONS".equalsIgnoreCase(httpServletRequest.getMethod())){
            return true;
        }

        if (XMLHTTP_REQUEST.equalsIgnoreCase(httpServletRequest.getHeader(X_REQUESTED_WITH))) {
            httpServletResponse.setHeader(SESSIONSTATUS, TIMEOUT);
            JSONObject root = new JSONObject();
            root.put("code", RS_KEY);
            root.put("errorMsg", RS_VALUE);
            PrintWriter out = httpServletResponse.getWriter();
            out.println(root.toString());
            out.flush();
            out.close();
            return false;
        }
        return super.onAccessDenied(request, response);
    }
}