package com.fzm.mall.server.admin.config.interceptor;

import com.alibaba.fastjson.JSONObject;
import com.fzm.mall.server.admin.repo.ResponseFactory;
import com.fzm.mall.server.admin.config.Redis;
import com.fzm.mall.server.admin.constant.MALLGlobalConfig;
import com.fzm.mall.server.admin.constant.MallResponseError;
import lombok.RequiredArgsConstructor;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.regex.Pattern;

/**
 * @author wangp
 * @date 2021/2/26 18:09
 * @description token拦截
 * @since JDK 1.8
 */
@Component
@RequiredArgsConstructor(onConstructor = @__(@Autowired))
public class TokenInterceptor implements HandlerInterceptor {

    private final ResponseFactory resFac;
    private final Redis redis;

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        String token = request.getHeader("token");
        String adminId = request.getHeader("adminId");
        String requestURI = request.getRequestURI();

        //放行
        if (Pattern.matches("^/malladmin/(?:homePage|merchantApply|sms)/.*$", requestURI) &&
                !requestURI.equals("/malladmin/homePage/getAdminAuthMenu") &&
                !requestURI.equals("/malladmin/homePage/logout")) {
            return true;
        }
        if (Pattern.matches("^/malladmin/upload/.*$", requestURI)) {
            return true;
        }

        if (StringUtils.isBlank(token)) {
            JSONObject.writeJSONString(response.getWriter(), resFac.getResponse(MallResponseError.NULL_TOKEN_ERROR));
            return false;
        }
        String redisToken = redis.getKey(adminId + MALLGlobalConfig.MALL_TOKEN_REDIS_KEY_SUFFIX);

        if (redisToken == null || !redisToken.equals(token)) {
            JSONObject.writeJSONString(response.getWriter(), resFac.getResponse(MallResponseError.INVALID_TOKEN_ERROR));
            return false;
        }

        return true;
    }

}
