package org.springblade.common.auth;

import javax.servlet.http.HttpSession;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

public class UserContextUtil {

    private static final Logger logger = LoggerFactory.getLogger(UserContextUtil.class);

    public static UserContext getUserContext(HttpSession session) {
        try {
            if (session.getAttribute(session.getId()) == null) {
                return null;
            }
            if (!(session.getAttribute(session.getId()) instanceof UserContext)) {
                return null;
            }
            UserContext userContext = (UserContext) session.getAttribute(session.getId());
            return userContext;
        } catch (IllegalStateException e) {
            logger.error("get user context error, session is invalidate." + e.getMessage());
            return null;
        }
    }
    
    public static UserContext getUserContext() {
        HttpSession session = getSession();
        if (session == null) {
            return null;
        }
        return getUserContext(session);
    }
    
    private static HttpSession getSession() {
        ServletRequestAttributes attrs = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();
        return attrs.getRequest().getSession();
    }

}
