package com.kmall.api.interceptor;

import com.kmall.api.annotation.IgnoreAuth;
import com.kmall.api.cache.UserTokenCache;
import com.kmall.api.entity.TokenEntity;
import com.kmall.common.utils.ApiRRException;
import org.apache.commons.lang.StringUtils;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.springframework.stereotype.Component;
import org.springframework.web.method.HandlerMethod;
import org.springframework.web.servlet.handler.HandlerInterceptorAdapter;

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

/**
 * 权限(Token)验证
 *
 * @author Scott
 * @email
 * @date 2017-03-23 15:38
 */
@Component
public class AuthorizationInterceptor extends HandlerInterceptorAdapter {

    public static final String LOGIN_USER_KEY = "LOGIN_USER_KEY";
    public static final String LOGIN_TOKEN_KEY = "X-Nideshop-Token";
    public static final String IS_REFUSED_LOGIN = "isRefusedLogin";
    protected Log logger = LogFactory.getLog(AuthorizationInterceptor.class);


    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        IgnoreAuth annotation;
        if (handler instanceof HandlerMethod) {
            annotation = ((HandlerMethod) handler).getMethodAnnotation(IgnoreAuth.class);
        } else {
            return true;
        }

        //如果有@IgnoreAuth注解，则不验证token
        if (annotation != null) {
            return true;
        }

        //从header中获取token
        String token = request.getHeader(LOGIN_TOKEN_KEY);
        //如果header中不存在token，则从参数中获取token
        if (StringUtils.isBlank(token)) {
            token = request.getParameter(LOGIN_TOKEN_KEY);
        }

        //从header中获取IS_REFUSED_LOGIN
        String isRefusedLogin = request.getHeader(IS_REFUSED_LOGIN);

        //token为空
        if(isRefusedLogin != null && !isRefusedLogin.equalsIgnoreCase("")){
            if (StringUtils.isBlank(token) && !isRefusedLogin.equalsIgnoreCase("true")) {
                logger.info("已授权，且token为空，请先登录");
                throw new ApiRRException("请先登录", 401);
            }

            //查询token信息
            TokenEntity tokenEntity = UserTokenCache.getUserInfoByToken(token);
            if ((tokenEntity == null || tokenEntity.getExpireTime().getTime() < System.currentTimeMillis())&& !isRefusedLogin.equalsIgnoreCase("true")) {
                logger.info("已授权，且token不为空，根据token查询token信息为空，token失效，请重新登录");
                throw new ApiRRException("token失效，请重新登录", 401);
            }

            if (tokenEntity != null && tokenEntity.getExpireTime().getTime() > System.currentTimeMillis()) {
                logger.info("已授权，且token不为空，根据token查询token信息userId："+tokenEntity.getUserId());
                //设置userId到request里，后续根据userId，获取用户信息
                request.setAttribute(LOGIN_USER_KEY, tokenEntity.getUserId());
            }
        }else{
            if (StringUtils.isBlank(token)) {
                throw new ApiRRException("请先登录", 401);
            }
            //查询token信息
            TokenEntity tokenEntity = UserTokenCache.getUserInfoByToken(token);
            if ((tokenEntity == null || tokenEntity.getExpireTime().getTime() < System.currentTimeMillis())) {
                throw new ApiRRException("token失效，请重新登录", 401);
            }

            if (tokenEntity != null && tokenEntity.getExpireTime().getTime() > System.currentTimeMillis()) {
                //设置userId到request里，后续根据userId，获取用户信息
                request.setAttribute(LOGIN_USER_KEY, tokenEntity.getUserId());
            }
        }

        return true;
    }
}
