package com.dxhy.auth.interceptor;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.springframework.web.servlet.handler.HandlerInterceptorAdapter;

import com.alibaba.fastjson.JSON;
import com.dxhy.admin.sys.service.LoginService;
import com.dxhy.auth.config.AuthConfig;
import com.dxhy.auth.util.user.JwtTokenUtil;
import com.dxhy.common.jwt.IJWTInfo;
import com.dxhy.common.utils.BaseContextHandler;

import lombok.extern.slf4j.Slf4j;

/**
 * @author jiaohongyang
 * @date 2019年3月26日 下午5:55:06
 *
 */
@Slf4j

public class UserAuthRestInterceptor extends HandlerInterceptorAdapter {
    @Resource
    private JwtTokenUtil jwtTokenUtil;

    @Resource
    private LoginService loginService;

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler)
        throws Exception {
        String token = request.getHeader(AuthConfig.userTokenHeader);
        IJWTInfo infoFromToken = jwtTokenUtil.getInfoFromToken(token);
        BaseContextHandler.setUsername(infoFromToken.getUserName());
        BaseContextHandler.setLoginname(infoFromToken.getLoginName());
        BaseContextHandler.setUserID(infoFromToken.getId());
        BaseContextHandler.setUserInfo(JSON.toJSONString(loginService.infoList(infoFromToken.getLoginName())));
        return super.preHandle(request, response, handler);
    }

    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex)
        throws Exception {
        BaseContextHandler.remove();
        super.afterCompletion(request, response, handler, ex);
    }
}
