package cn.reghao.bnt.web.admin.security.session;

import lombok.extern.slf4j.Slf4j;
import org.springframework.security.core.session.SessionInformation;
import org.springframework.security.web.session.SessionInformationExpiredEvent;
import org.springframework.security.web.session.SessionInformationExpiredStrategy;
import org.springframework.stereotype.Component;

import jakarta.servlet.ServletException;
import jakarta.servlet.http.HttpServletResponse;
import java.io.IOException;

/**
 * ConcurrentSessionFilter 中检测到过期 session 时的处理策略
 *
 * @author reghao
 * @date 2024-02-02 16:32:43
 */
@Slf4j
@Component
public class MySessionInformationExpiredStrategy implements SessionInformationExpiredStrategy {
    @Override
    public void onExpiredSessionDetected(SessionInformationExpiredEvent event) throws IOException, ServletException {
        SessionInformation sessionInformation = event.getSessionInformation();
        String loginId = sessionInformation.getSessionId();
        Object principal = sessionInformation.getPrincipal();
        log.info("UserId {} 的会话 {} 已过期...", principal, loginId);

        HttpServletResponse response = event.getResponse();
        /*response.setStatus(HttpServletResponse.SC_UNAUTHORIZED);
        response.setContentType("application/json;charset=utf-8");
        response.getWriter().write("您的账号已经在别的地方登入！");*/
        String redirectPath = "/bg/login";
        response.sendRedirect(redirectPath);
    }
}
