package com.ruoyi.framework.shiro.web.filter.authc;

import java.io.IOException;
import jakarta.servlet.ServletRequest;
import jakarta.servlet.ServletResponse;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import org.apache.shiro.web.filter.authc.UserFilter;
import org.apache.shiro.web.util.WebUtils;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.ruoyi.common.core.domain.AjaxResult;
import com.ruoyi.common.utils.ServletUtils;

/**
 * 让前后端分离场景下的未登录请求返回 JSON，而不是 302 跳转登录页。
 */
public class AjaxAwareUserFilter extends UserFilter
{
    private static final ObjectMapper OBJECT_MAPPER = new ObjectMapper();

    @Override
    protected boolean onAccessDenied(ServletRequest request, ServletResponse response) throws Exception
    {
        HttpServletRequest httpRequest = (HttpServletRequest) request;
        HttpServletResponse httpResponse = (HttpServletResponse) response;
        if (ServletUtils.isAjaxRequest(httpRequest))
        {
            AjaxResult ajaxResult = AjaxResult.error("登录状态已失效，请重新登录");
            ajaxResult.put(AjaxResult.CODE_TAG, 401);
            ServletUtils.renderString(httpResponse, OBJECT_MAPPER.writeValueAsString(ajaxResult));
            return false;
        }
        saveRequestAndRedirectToLogin(request, response);
        return false;
    }

    @Override
    protected void redirectToLogin(ServletRequest request, ServletResponse response) throws IOException
    {
        if (request instanceof HttpServletRequest && ServletUtils.isAjaxRequest((HttpServletRequest) request))
        {
            return;
        }
        WebUtils.issueRedirect(request, response, getLoginUrl());
    }
}
