package com.platform.modules.qk.interceptor;

import io.jsonwebtoken.Claims;

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

import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.web.method.HandlerMethod;
import org.springframework.web.servlet.handler.HandlerInterceptorAdapter;

import com.platform.common.exception.RRException;
import com.platform.modules.app.annotation.Login;
import com.platform.modules.qk.utils.CloulClipsJwtUtils;


/**
 * 权限(Token)验证
 * @author weiyan
 * @date 2018-08-23 15:38
 */
@Component
public class CloudClipsAuthorizationInterceptor  extends HandlerInterceptorAdapter {
    @Autowired
    private CloulClipsJwtUtils jwtUtils;

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

        if(annotation == null){
            return true;
        }

        //获取用户凭证
        String token = request.getParameter("accessToken");

        //凭证为空
        if(StringUtils.isBlank(token)){
            throw new RRException("accessToken为空", 10000);
        }

        Claims claims = jwtUtils.getClaimByToken(token);
        if(claims == null || jwtUtils.isTokenExpired(claims.getExpiration())){
            throw new RRException("accessToken失效", 10001);
        }

        return true;
    }
}
