package com.dxhy.auth.client.interceptor;

import java.util.List;

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

import org.jetbrains.annotations.NotNull;
import org.springframework.web.method.HandlerMethod;
import org.springframework.web.servlet.handler.HandlerInterceptorAdapter;

import com.dxhy.auth.client.annotation.IgnoreClientToken;
import com.dxhy.auth.client.config.ServiceAuthConfig;
import com.dxhy.auth.client.jwt.ServiceAuthUtil;
import com.dxhy.common.exception.auth.ClientForbiddenException;
import com.dxhy.common.jwt.IJWTInfo;

import lombok.extern.slf4j.Slf4j;

/**
 * @author jiaohongyang
 * @date 2019年3月26日 下午5:51:54
 *
 */
@Slf4j
public class ServiceAuthRestInterceptor extends HandlerInterceptorAdapter {

    @Resource
    private ServiceAuthUtil serviceAuthUtil;

    @Resource
    private ServiceAuthConfig serviceAuthConfig;

    private List<String> allowedClient;

    @Override
    public boolean preHandle(@NotNull HttpServletRequest request, @NotNull HttpServletResponse response,
        @NotNull Object handler) throws Exception {
        HandlerMethod handlerMethod = (HandlerMethod)handler;
        // 配置该注解，说明不进行服务拦截
        IgnoreClientToken annotation = handlerMethod.getBeanType().getAnnotation(IgnoreClientToken.class);
        if (annotation == null) {
            annotation = handlerMethod.getMethodAnnotation(IgnoreClientToken.class);
        }
        if (annotation != null) {
            return super.preHandle(request, response, handler);
        }

        String token = request.getHeader(serviceAuthConfig.getTokenHeader());
        IJWTInfo infoFromToken = serviceAuthUtil.getInfoFromToken(token);
        String loginName = infoFromToken.getLoginName();
        for (String client : serviceAuthUtil.getAllowedClient()) {
            if (client.equals(loginName)) {
                return super.preHandle(request, response, handler);
            }
        }
        throw new ClientForbiddenException("Client is Forbidden!");
    }
}
