/
VerifyIftttWebhook.php
83 lines (66 loc) · 2.32 KB
/
VerifyIftttWebhook.php
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
<?php
namespace App\Middleware;
class VerifyIftttWebhook
{
private $logger;
private $config;
private $validator;
/**
* VerifyIftttWebhook constructor.
*
* @param $logger
* @param $config
* @param $validator
*/
public function __construct($logger, $config, $validator)
{
$this->logger = $logger;
$this->config = $config['ifttt'];
$this->validator = $validator;
}
/**
* Validate request data for IFTTT webhooks.
*
* @param \Psr\Http\Message\ServerRequestInterface $request PSR7 request
* @param \Psr\Http\Message\ResponseInterface $response PSR7 response
* @param callable $next Next middleware
*
* @return \Psr\Http\Message\ResponseInterface
*/
public function __invoke($request, $response, $next)
{
// Log the invocation of this middleware
$this->log($request);
// Get the request object
$payload = (object) $request->getParsedBody();
// Load the IFTTT JSON schema
$this->validator->validate($payload, (object) ['$ref' => 'file://' . PROJECT_ROOT . '/resources/schema/ifttt.json']);
// Validate the JSON payload against the IFTTT schema
// Log and fail otherwise
if (! $this->validator->isValid()) {
$this->logger->warning("\n[RESULT] Invalid payload.");
return $response->withJson('Invalid payload.', 422);
}
// Ensure the key sent is our IFTTT Maker key
// Log and fail otherwise
if ($payload->key !== $this->config['key']) {
$this->logger->warning("\n[RESULT] Invalid key.");
return $response->withJson('Well that didn\'t work.', 401);
}
// Successfully verified webhook.
$this->logger->info("\n[RESULT] IFTTT webhook verified.");
return $next($request->withParsedBody($payload), $response);
}
/**
* Log this request.
*
* @param $request
*/
private function log($request)
{
$routeInfo = $request->getAttribute('routeInfo')['request'];
$payload = json_encode($request->getParsedBody(), JSON_PRETTY_PRINT);
$message = sprintf("\n[%s] %s\n[PAYLOAD]\n%s", $routeInfo[0], $routeInfo[1], $payload);
$this->logger->info($message);
}
}