package com.huigou.uasp.bmp.intercept;

import com.huigou.context.Operator;
import org.springframework.util.AntPathMatcher;
import org.springframework.util.PathMatcher;
import org.springframework.util.StringUtils;

import javax.servlet.http.HttpServletRequest;
import java.util.Arrays;

/**
 * @author yonghuan
 */
public class RefererHeaderCsrfTokenVerifyStrategy implements CsrfTokenVerifyStrategy {

    private String[] whiteListUrls;
    private final PathMatcher pathMatcher = new AntPathMatcher();

    public void setWhiteListUrl(String whiteListUrl) {
        this.whiteListUrls = StringUtils.tokenizeToStringArray(whiteListUrl, ",");
    }

    @Override
    public boolean verify(HttpServletRequest request, Operator operator) {
        String referer = request.getHeader("Referer");
        if (referer == null) {
            return false;
        }
        return Arrays.stream(whiteListUrls)
                .filter(whiteListUrl -> pathMatcher.match(whiteListUrl, referer))
                .findAny()
                .isPresent();
    }
}
