package com.huimv.admin.session;

import lombok.extern.slf4j.Slf4j;
import org.springframework.http.HttpHeaders;
import org.springframework.util.Assert;
import org.springframework.web.server.ServerWebExchange;
import org.springframework.web.server.session.WebSessionIdResolver;

import java.util.Collections;
import java.util.List;

/**
 * @author yejijie
 * @created 2020年7月29日 下午2:27:21
*/
@Slf4j
public class PlatformWebSessionIdResolver implements WebSessionIdResolver {

	private static final String PLATFORM_HEADER_TOKEN = "x-auth-token";
	private static final String PLATFORM_URL_TOKEN = "token";
	private final String urlName;
	private String headerName;

	public static PlatformWebSessionIdResolver authToken() {
		return new PlatformWebSessionIdResolver(PLATFORM_HEADER_TOKEN,PLATFORM_URL_TOKEN);
	}
	
	public PlatformWebSessionIdResolver(String headerToken, String urlToken) {
		Assert.hasText(headerToken, "'headerToken' must not be empty");
		Assert.hasText(urlToken, "'urlToken' must not be empty");
		this.urlName = urlToken;
		this.headerName = headerToken;
	}

	@Override
	public List<String> resolveSessionIds(ServerWebExchange exchange) {
		HttpHeaders headers = exchange.getRequest().getHeaders();
		List<String> headerValues = headers.getOrDefault(this.headerName, null);
		log.info("header auth->"+(headerValues== null? null:headerValues.get(0)));
		if(headerValues != null)
			return headerValues;
		//处理其他方式
		List<String> paramValues = exchange.getRequest().getQueryParams().getOrDefault(this.urlName, Collections.emptyList());
		log.info("url auth->"+(paramValues.size() == 0? null:paramValues.get(0)));
		return paramValues;
	}

	@Override
	public void setSessionId(ServerWebExchange exchange, String sessionId) {
		exchange.getResponse().getHeaders().set(this.headerName, sessionId);
	}

	@Override
	public void expireSession(ServerWebExchange exchange) {
		exchange.getResponse().getHeaders().set(this.headerName, "");
	}

}
