package im.tox.upsourcebot.filters;

import com.google.common.io.ByteStreams;

import org.apache.commons.codec.digest.HmacUtils;

import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.security.MessageDigest;

import javax.ws.rs.container.ContainerRequestContext;
import javax.ws.rs.container.ContainerRequestFilter;
import javax.ws.rs.core.Response;

@GitHubHMAC
public class GitHubHMACFilter implements ContainerRequestFilter {

  private byte[] secret;

  public GitHubHMACFilter(String secret) {
    this.secret = secret.getBytes();
  }

  @Override
  public void filter(ContainerRequestContext requestContext) throws IOException {
    String hubSignature = requestContext.getHeaderString("X-Hub-Signature");
    if (hubSignature == null) {
      requestContext.abortWith(Response.status(Response.Status.UNAUTHORIZED).build());
      return;
    }

    InputStream input = requestContext.getEntityStream();
    ByteArrayOutputStream out = new ByteArrayOutputStream();
    byte[] requestBody = ByteStreams.toByteArray(input);
    String hmac = "sha1=" + HmacUtils.hmacSha1Hex(secret, requestBody);
    if (!MessageDigest.isEqual(hmac.getBytes(), hubSignature.getBytes())) {
      requestContext.abortWith(Response.status(Response.Status.UNAUTHORIZED).build());
    }
    requestContext.setEntityStream(new ByteArrayInputStream(requestBody));
  }

}

@@ -179,85 +179,19 @@
 .io.
-ByteArrayOutputStream;%0Aimport java.io.IOException;%0Aimport java.io.InputStream
+IOException
 ;%0Aim
@@ -876,177 +876,85 @@
     
-InputStream input = requestContext.getEntityStream();%0A    ByteArrayOutputStream out = new ByteArrayOutputStream();%0A    byte%5B%5D requestBody = ByteStreams.toByteArray(input
+byte%5B%5D requestBody = ByteStreams.toByteArray(requestContext.getEntityStream()
 );%0A 

Remove useless variables