package com.sy.coinage.core.interceptor;

import java.lang.reflect.Method;

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

import org.springframework.web.method.HandlerMethod;
import org.springframework.web.servlet.HandlerInterceptor;

import com.sy.coinage.core.annotation.LoginNotRequired;
import com.sy.coinage.core.constants.Constants;
import com.sy.coinage.core.exception.TokenErrorException;
import com.sy.coinage.core.vo.CacheUserVO;

/**
 * token 拦截
 */
public class TokenInterceptor implements HandlerInterceptor {

    private TokenVerify tokenVerify;

    public TokenInterceptor(TokenVerify tokenVerify) {
        this.tokenVerify = tokenVerify;
    }

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler)
                    throws Exception {
        // 如果不是映射到方法直接通过
        if (!(handler instanceof HandlerMethod)) {
            return true;
        }
        HandlerMethod handlerMethod = (HandlerMethod) handler;
        Method method = handlerMethod.getMethod();
        // 判断接口是否需要登录
        LoginNotRequired methodAnnotation = method.getAnnotation(LoginNotRequired.class);
        // 有 @LoginNotRequired 注解，不需要认证
        if (methodAnnotation != null) {
            return true;
        }
        // 判断是否存在令牌信息，如果存在，则允许登录
        String token = request.getHeader(Constants.TOKEN);
        if (null == token) {
            this.setHeader(response);
            throw new TokenErrorException();
        }
        CacheUserVO user = this.tokenVerify.getCacheUser(token);
        if (user == null) {
            this.setHeader(response);
            throw new TokenErrorException();
        }
        // 当前登录用户@CurrentUser
        request.setAttribute(Constants.CURRENT_USER, user);
        return true;

    }

    private void setHeader(HttpServletResponse response) {
        response.setHeader("Access-Control-Request-Headers", "authorization");
        response.setHeader("Access-Control-Allow-Origin", "*");
    }

}
