package com.ynfy.app.api.v1.interceptor;

import com.auth0.jwt.exceptions.TokenExpiredException;
import com.ynfy.app.api.v1.annoation.IgnoreAuth;
import com.ynfy.app.api.v1.util.TokenUtil;
import org.apache.commons.lang3.StringUtils;
import org.jeecg.common.exception.JeecgBootException;
import org.jeecg.common.system.util.JwtUtil;
import org.jeecg.modules.system.entity.SysUser;
import org.jeecg.modules.system.service.ISysUserService;
import org.springframework.stereotype.Component;
import org.springframework.web.method.HandlerMethod;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

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

/**
 * 权限(Token)验证
 */
@Component
public class AuthorizationInterceptor implements HandlerInterceptor {

    @Resource
    private ISysUserService sysUserService;

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {

        //支持跨域请求
        response.setHeader("Access-Control-Allow-Methods", "POST, GET, OPTIONS, DELETE");
        response.setHeader("Access-Control-Allow-Credentials", "true");
        response.setHeader("Access-Control-Allow-Headers", "x-requested-with,X-Exam-Token,X-URL-PATH,content-type");
        response.setHeader("Access-Control-Allow-Origin", request.getHeader("Origin"));

        IgnoreAuth annotation;
        if (handler instanceof HandlerMethod) {
            annotation = ((HandlerMethod) handler).getMethodAnnotation(IgnoreAuth.class);
        } else {
            return true;
        }

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

        //获取token
        String token = TokenUtil.getToken(request);
        String userName = TokenUtil.getUserName(token);

        if (StringUtils.isEmpty(userName)) {
            throw new JeecgBootException("token错误");
        } else {
            SysUser user = sysUserService.getUserByName(userName);
            if (user == null) {
                throw new JeecgBootException("用户不存在!");
            } else {
                try {
                    JwtUtil.verify(token, userName, user.getPassword());
                } catch (TokenExpiredException var6) {
                    throw new JeecgBootException("token失效，请重新登录");
                } catch (Exception e) {
                    throw new JeecgBootException("token认证失败");
                }
            }
        }
        return true;
    }

    //方法执行后
    @Override
    public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) {

    }

    //页面渲染前
    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) {

    }

}
