package com.thinkgem.jeesite.common.filter;

import com.thinkgem.jeesite.common.constant.ComCode;
import com.thinkgem.jeesite.common.utils.MD5;

import javax.servlet.*;
import javax.servlet.annotation.WebFilter;
import javax.servlet.http.HttpServletRequest;
import java.io.IOException;

/**
 * 验证sign
 */
@WebFilter(filterName = "validationFilter", urlPatterns = "/api/*")
public class ValidationFilter implements Filter {
    @Override
    public void init(FilterConfig filterConfig) {
    }

    @Override
    public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {
        HttpServletRequest httpRequest = (HttpServletRequest) servletRequest;
        String url = httpRequest.getRequestURL().toString();
        if (url == null || url.trim().length() == 0) {
            return;
        }
        String signCode = ComCode.signCode;
        String subMerchantId = httpRequest.getParameter("subMerchantId");
        String timestamp = httpRequest.getParameter("timestamp");
        String sign = httpRequest.getParameter("sign");
        String checkSign = MD5.sign(subMerchantId + signCode + timestamp, "", "utf-8");
        if (!checkSign.equals(sign)) {
            servletRequest.getRequestDispatcher("/com/filterError/returnError?code=" + 1 + "&subMerchantId=" + subMerchantId).forward(servletRequest, servletResponse);
            return;
        }
        filterChain.doFilter(servletRequest, servletResponse);
        return;
    }

    @Override
    public void destroy() {
    }
}
