package com.uas.platform.b2b.manage.web.filter;

import com.uas.platform.b2b.manage.core.support.SystemSession;
import com.uas.platform.b2b.manage.model.User;
import org.springframework.web.servlet.handler.HandlerInterceptorAdapter;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

/**
 * 用户信息拦截器，对所有的请求，自动将Session 中的用户信息设置进
 *
 * @author hejq
 * @date 2018-08-30 10:00
 */
public class SystemSessionInterceptor extends HandlerInterceptorAdapter {

    /**
     * 传入的attribute关键字 user
     */
    private final String USER_KEY = "user";

    /**
     * This implementation always returns {@code true}.
     */
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler)
            throws Exception {
        if (SystemSession.getUser() == null) {
            HttpSession session = request.getSession(false);
            if (session != null && session.getAttribute(USER_KEY) != null) {
                SystemSession.setUser((User) session.getAttribute(USER_KEY));
            }
            SystemSession.setSession(session);
        }
        return true;
    }
}
