codingoutloud
7/26/2012 - 8:18 PM

Handle HTTP Post for WebHook

Handle HTTP Post for WebHook

// POST /api/githubpushes
// FAILS: Content-Type: application/json
// WORKS: Content-Type: application/x-www-form-urlencoded
public HttpResponseMessage<string> Post(
   // not needed, but might be if more complex: [FromBody] 
   SimpleFormData webHookData)
{
   var pushManifestJson = webHookData.Payload;
   var pushManifest = JsonConvert.DeserializeObject<GithubPushManifest>(pushManifestJson);

   if (!IsValidSourceAddress())
   {
      return new HttpResponseMessage<string>("This service can only be invoked by Github WebHooks.", HttpStatusCode.Forbidden);
   }
   else
   {
      return InnerPost(pushManifest, pushManifestJson);
   }
}

public HttpResponseMessage<string> InnerPost(GithubPushManifest pushManifest, string pushManifestJson)
{
   string lastCommitText = GetLastCommitText(pushManifest);
   try
   {
      Uri fullUri = GetSharedAccessSignatureUri(Request.RequestUri); // assumes fullUri is piggybacking as a Query String
      UpdateBlobContents(lastCommitText, fullUri);
      return new HttpResponseMessage<string>(HttpStatusCode.Created);
   }
   catch (Exception ex)
   {
      return new HttpResponseMessage<string>(ex.Message + " : " + new TracerBullet().GetContext(), HttpStatusCode.BadRequest);
   }
}

private static bool IsValidGithubWebHookIpAddress(string ipAddress)
{
   var validGithubHookIpAddresses = new List<string> { "207.97.227.253", "50.57.128.197", "108.171.174.178", // <<= REAL
      "108.171.174.178", "173.48.23.122", "50.57.128.197" }; // <<= NOT SURE (include's Bill's home IP Addr
   // throws exception if not found: var found = validGithubHookIpAddresses.First(goodIp => goodIp == ipAddress);
   var found = validGithubHookIpAddresses.Find(goodIp => goodIp == ipAddress);
   return found != null;
}