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

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

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

/**
 * ConcurrentSessionFilter 中检测到过期 session 时的处理策略
 *
 * @author reghao
 * @date 2024-02-02 16:32:43
 */
@Slf4j
@Component
public class SessionExpiredStrategy implements SessionInformationExpiredStrategy {
    @Override
    public void onExpiredSessionDetected(SessionInformationExpiredEvent event) throws IOException, ServletException {
        String principal = (String) event.getSessionInformation().getPrincipal();
        log.info("{} 已在别处登录！", principal);

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