package com.icloud.server.web.shiro.config;

import org.apache.shiro.web.servlet.ShiroHttpServletRequest;
import org.apache.shiro.web.session.mgt.DefaultWebSessionManager;
import org.apache.shiro.web.util.WebUtils;

import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletRequest;
import java.io.Serializable;
import java.util.Map;

public class CustomSessionManager extends DefaultWebSessionManager {

    private static final String AUTHORIZATION = "token";//Authorization
//    private static final String AUTHORIZATION = "Authorization";//


    public CustomSessionManager(){
        super();
    }

    @Override
    protected Serializable getSessionId(ServletRequest request, ServletResponse response) {
        String token = WebUtils.toHttp(request).getHeader("Authorization");
        System.out.println("Authorization:"+token);
        String sessionId = WebUtils.toHttp(request).getHeader(AUTHORIZATION);
        System.out.println(WebUtils.toHttp(request));
        String URI = WebUtils.toHttp(request).getRequestURI();
        HttpServletRequest httpServletRequest = WebUtils.toHttp(request);
        String servletPath = httpServletRequest.getServletPath();
        Map<String, String[]> parameterMap = httpServletRequest.getParameterMap();
        System.out.println("======路径:"+URI);
        for(Object key:parameterMap.keySet()){
            String v = parameterMap.get(key)[0];
            System.out.println("======参数:"+key+":"+v);
        }
        System.out.println("======sessionId:"+sessionId);


        if(sessionId==null||"".equals(sessionId)){
            sessionId=request.getParameter(AUTHORIZATION);
        }
        if(sessionId != null){
            request.setAttribute(ShiroHttpServletRequest.REFERENCED_SESSION_ID_SOURCE,
                    ShiroHttpServletRequest.COOKIE_SESSION_ID_SOURCE);
            request.setAttribute(ShiroHttpServletRequest.REFERENCED_SESSION_ID, sessionId);

            //automatically mark it valid here.  If it is invalid, the
            //onUnknownSession method below will be invoked and we'll remove the attribute at that time.
            request.setAttribute(ShiroHttpServletRequest.REFERENCED_SESSION_ID_IS_VALID, Boolean.TRUE);
            return sessionId;

        }else {
            return super.getSessionId(request,response);
        }

    }


}
