package com.dxhy.auth.interceptor;

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

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

import com.dxhy.auth.config.AuthConfig;
import com.dxhy.auth.service.AuthClientService;
import com.dxhy.auth.util.client.ClientTokenUtil;
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:55:01
 *
 */
@Slf4j

public class ServiceAuthRestInterceptor extends HandlerInterceptorAdapter {

    @Resource
    private ClientTokenUtil clientTokenUtil;
    @Resource
    private AuthClientService authClientService;

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler)
        throws Exception {
        HandlerMethod handlerMethod = (HandlerMethod)handler;
        String token = request.getHeader(AuthConfig.clientTokenHeader);
        IJWTInfo infoFromToken = clientTokenUtil.getInfoFromToken(token);
        String loginName = infoFromToken.getLoginName();
        for (String client : authClientService.getAllowedClient(AuthConfig.clientId)) {
            if (client.equals(loginName)) {
                return super.preHandle(request, response, handler);
            }
        }
        throw new ClientForbiddenException("Client is Forbidden!");
    }
}
