package com.microservices.common.security.interceptor;

import com.microservices.common.core.constant.SecurityConstants;
import com.microservices.common.core.context.SecurityContextHolder;
import com.microservices.common.core.utils.ServletUtils;
import com.microservices.common.core.utils.SpringUtils;
import com.microservices.common.core.utils.StringUtils;
import com.microservices.common.security.auth.AuthUtil;
import com.microservices.common.security.service.IRequestCustomService;
import com.microservices.system.api.domain.SysUserDeptRole;
import com.microservices.system.api.model.LoginUser;
import org.springframework.web.method.HandlerMethod;
import org.springframework.web.servlet.AsyncHandlerInterceptor;

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

/**
 * 自定义请求头拦截器，将Header数据封装到线程变量中方便获取
 * 注意：此拦截器会同时验证当前用户有效期自动刷新有效期
 *
 * @author microservices
 */
public class HeaderInterceptor implements AsyncHandlerInterceptor {

    public IRequestCustomService requestCustomService = SpringUtils.getBean(IRequestCustomService.class);
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        if (!(handler instanceof HandlerMethod)) {
            return true;
        }
        SecurityContextHolder.setUserId(ServletUtils.getHeader(request, SecurityConstants.DETAILS_USER_ID));
        SecurityContextHolder.setUserName(ServletUtils.getHeader(request, SecurityConstants.DETAILS_USERNAME));
        SecurityContextHolder.setUserKey(ServletUtils.getHeader(request, SecurityConstants.USER_KEY));
        SecurityContextHolder.setDeptId(requestCustomService.processRequestDeptId(request));

        LoginUser loginUser = null;
        String userKey = SecurityContextHolder.getUserKey();
        if (StringUtils.isNotEmpty(userKey)) {
            loginUser = AuthUtil.getLoginUserByUserKey(userKey);
        }
        if (StringUtils.isNull(loginUser)) {
            return true;
        }

        AuthUtil.verifyLoginUserExpire(loginUser);
        SecurityContextHolder.set(SecurityConstants.LOGIN_USER, loginUser);
        SysUserDeptRole userIdentify = AuthUtil.getUserIdentify(loginUser.getUsername(), SecurityContextHolder.getDeptId());
        if (userIdentify != null) {
            SecurityContextHolder.set(SecurityConstants.USER_IDENTITY, userIdentify);
        }
        return true;
    }

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