package cn.reghao.autodop.dmaster.rbac.security;

import cn.reghao.autodop.dmaster.rbac.UserContext;
import cn.reghao.autodop.dmaster.rbac.model.po.User;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.context.SecurityContext;

import javax.servlet.*;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
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;
        HttpSession session = httpRequest.getSession();

        String url = httpRequest.getRequestURI().substring(httpRequest.getContextPath().length());
        SecurityContext securityContext = (SecurityContext) session.getAttribute("SPRING_SECURITY_CONTEXT");
        if (securityContext != null) {
            Authentication authentication = securityContext.getAuthentication();
            User user = (User) authentication.getPrincipal();
            try (UserContext context = new UserContext(user)) {
                if ("/login".equals(url)) {
                    // 将登录页面重定向到主页
                    httpResponse.sendRedirect("/");
                } else {
                    chain.doFilter(request, response);
                }
            }
        } else {
            chain.doFilter(request, response);
        }
    }
}
