package ru.micord.ervu.security.webbpm.jwt;

import java.util.Arrays;
import java.util.Set;
import java.util.stream.Collectors;
import javax.servlet.http.HttpServletRequest;

import org.springframework.security.web.util.matcher.AntPathRequestMatcher;
import org.springframework.security.web.util.matcher.RequestMatcher;

import static ru.micord.ervu.security.webbpm.jwt.util.SecurityUtil.extractAuthToken;

public final class JwtMatcher implements RequestMatcher {
  private final Set<AntPathRequestMatcher> excludedPathMatchers;
  private final AntPathRequestMatcher securedMatcher;

  public JwtMatcher(String securedPath, String... excludedPaths) {
    this.securedMatcher = new AntPathRequestMatcher(securedPath);
    this.excludedPathMatchers = Arrays.stream(excludedPaths)
        .map(AntPathRequestMatcher::new)
        .collect(Collectors.toSet());
  }

  @Override
  public boolean matches(HttpServletRequest request) {
    if (this.excludedPathMatchers.stream().anyMatch(matcher -> matcher.matches(request))) {
      return false;
    }
    else {
      return extractAuthToken(request) != null && this.securedMatcher.matches(request);
    }
  }
}
