package com.bizzan.bitrade.core;

import org.apache.shiro.web.filter.authc.FormAuthenticationFilter;
import org.json.JSONObject;

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

/**
 * 自定义 Shiro 认证过滤器
 * 未登录时直接返回 JSON {code: 4000}，而不是 302 重定向到登录页，
 * 避免前端 axios 跟随重定向后无法识别响应。
 */
public class AjaxAwareAuthenticationFilter extends FormAuthenticationFilter {

    @Override
    protected boolean onAccessDenied(ServletRequest request, ServletResponse response) throws Exception {
        HttpServletResponse httpResponse = (HttpServletResponse) response;
        httpResponse.setStatus(200);
        httpResponse.setContentType("application/json;charset=UTF-8");
        httpResponse.setCharacterEncoding("UTF-8");
        PrintWriter out = httpResponse.getWriter();
        JSONObject json = new JSONObject();
        json.put("code", 4000);
        json.put("message", "please login");
        out.print(json.toString());
        out.flush();
        out.close();
        return false;
    }
}
