package com.huimv.admin.session;

import lombok.extern.slf4j.Slf4j;
import org.springframework.session.web.http.HttpSessionIdResolver;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.Collections;
import java.util.List;

/**
 * @author yejijie
 * @created 2020年7月16日 上午9:35:46
*/
@Slf4j
public class PlatformHttpSessionIdResolver implements HttpSessionIdResolver {

	private static final String PLATFORM_AUTH_TOKEN = "x-auth-token";
	private final String tokenName;
	private String paramName;
	
	public static PlatformHttpSessionIdResolver authToken() {
		return new PlatformHttpSessionIdResolver(PLATFORM_AUTH_TOKEN);
	}
	
	public PlatformHttpSessionIdResolver(String tokenName) {
		if (tokenName == null) {
			throw new IllegalArgumentException("headerName cannot be null");
		}
		this.tokenName = tokenName;
		this.paramName = tokenName;
	}
	
	public void setParamName(String paramName) {
		this.paramName = paramName;
	}

	@Override
	public List<String> resolveSessionIds(HttpServletRequest request) {
		String headerValue = request.getHeader(this.tokenName);
		log.info("header auth->"+headerValue);
		if(headerValue != null)
			return Collections.singletonList(headerValue);
		//处理其他方式
		String paramValue = request.getParameter(this.paramName);
		log.info("param auth->"+paramValue);
		if(paramValue != null)
			return Collections.singletonList(paramValue);
		return Collections.emptyList();
	}

	@Override
	public void setSessionId(HttpServletRequest request, HttpServletResponse response, String sessionId) {

		response.setHeader(this.tokenName, sessionId);
	}

	@Override
	public void expireSession(HttpServletRequest request, HttpServletResponse response) {

		response.setHeader(this.tokenName, "");
	}

}
