package com.songhua.framework.sso.utli;

import org.springframework.stereotype.Component;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import javax.servlet.http.HttpSessionEvent;
import javax.servlet.http.HttpSessionListener;
import java.util.LinkedHashMap;
import java.util.Map;

/**
 * 记录所有已创建的 HttpSession 对象 
 * 
 * <b> 此种方式有性能问题，仅做demo示例，真实项目中请更换为其它方案记录用户会话数据 </b>
 * 
 * @author kong
 * @since: 2022-4-30
 */
@Component
public class MyHttpSessionHolder implements HttpSessionListener {
	
	public static Map<String, HttpSession> sessionMap = new LinkedHashMap<String, HttpSession>();
	
	public void sessionCreated(HttpSessionEvent httpSessionEvent) {
		HttpSession session = httpSessionEvent.getSession();
		sessionMap.put(session.getId(), session);
	}

	public void sessionDestroyed(HttpSessionEvent httpSessionEvent) {
		HttpSession session = httpSessionEvent.getSession();
		sessionMap.remove(session.getId());
	}

	/**
	 * 获取指定请求的 HttpSession (前后台分离模式下必须使用此方法获取 HttpSession ) 
	 * @param request
	 */
	public static HttpSession getSession(HttpServletRequest request) {
		// 先使用默认的尝试一下 
		HttpSession session = request.getSession(false);
		if(session != null) {
			return session;
		}
		
		// 获取前端提交的 token
		String token = request.getHeader("JSESSIONID");
		if(token == null) {
			token = request.getHeader("satoken");
			if(token == null) {
				token = request.getParameter("satoken");
			}
		}
		
		// 获取
		HttpSession session2 = sessionMap.get(token);
		if(session2 != null) {
			return session2;
		}
		
		return request.getSession();
	}

	
}
