package cn.reghao.tnb.auth.app.security.filter;

import org.springframework.security.core.context.SecurityContext;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.web.filter.GenericFilterBean;

import jakarta.servlet.*;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import java.io.IOException;

/**
 * 用于 Web 应用
 * 已登入状态下，访问认证页面/接口自动跳转到首页
 *
 * @author reghao
 * @date 2019-06-04 23:06:50
 */
public class LoginRedirectFilter extends GenericFilterBean {
    @Override
    public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain)
            throws IOException, ServletException {
        HttpServletRequest httpRequest = (HttpServletRequest) request;
        HttpServletResponse httpResponse = (HttpServletResponse) response;

        SecurityContext securityContext = SecurityContextHolder.getContext();
        String url = httpRequest.getRequestURI().substring(httpRequest.getContextPath().length());
        if (securityContext != null && securityContext.getAuthentication() != null && "/login".equals(url)) {
            // 将登入页面重定向到主页
            httpResponse.sendRedirect("/");
        } else {
            chain.doFilter(request, response);
        }
    }
}
