package cn.reghao.oss.console.account.security.filter;

import org.springframework.security.core.context.SecurityContext;
import org.springframework.security.core.context.SecurityContextHolder;

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

/**
 * 已登录状态下，访问 /login 页面自动跳转到 /
 *
 * @author reghao
 * @date 2019-06-04 23:06:50
 */
public class LoginRedirectFilter implements Filter {
    @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);
        }
    }
}
