-
Notifications
You must be signed in to change notification settings - Fork 4
Expand file tree
/
Copy pathOAuth2ClientCredentials.php
More file actions
68 lines (53 loc) · 2.84 KB
/
Copy pathOAuth2ClientCredentials.php
File metadata and controls
68 lines (53 loc) · 2.84 KB
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
<?php
/**
* REDCap External Module: REDCap REST
* Send API calls when saving particular instruments when a trigger condition is met.
* @author Luke Stevens, Murdoch Children's Research Institute
*/
namespace MCRI\REDCapREST;
class OAuth2ClientCredentials extends OAuth2 {
public function oauth2Call(string $method, string $url, string $contentType, array $headers, array $curlOptions, string $payload, $allowRetry=true): void {
// update access token if needed (first connection or expired)
$this->updateAccessToken();
$authHeaders = $headers;
$authHeaders[] = "Authorization: Bearer ".$this->access_token;
list($this->response, $this->info) = $this->module->curlCall($method, $url, $contentType, $authHeaders, $curlOptions, $payload);
if ($this->info['http_code'] === 401 && $allowRetry) {
// retry once with new token
$this->access_token = null;
$this->access_token_expiry = null;
$this->updateAccessToken();
$authHeaders = $headers;
$authHeaders[] = "Authorization: Bearer ".$this->access_token;
list($this->response, $this->info) = $this->module->curlCall($method, $url, $contentType, $authHeaders, $curlOptions, $payload);
}
}
/**
* updateAccessToken()
* If there is a cached and unexpired access token then do nothing, otherwise obtain a new token
*/
protected function updateAccessToken(): void {
// if have unexpired access token then do nothing
if (!empty($this->access_token) && !empty($this->access_token_expiry)) {
$tokenRefreshAt = $this->access_token_expiry->sub(new \DateInterval('PT5M'));
$now = new \DateTime("now");
if ($now < $tokenRefreshAt) return;
}
// obtain an access token
$payload = http_build_query(array('grant_type' => 'client_credentials'));
$curlOptions = array(array(CURLOPT_USERPWD, $this->client_id.":".$this->client_secret));
list($response, $info) = $this->module->curlCall('POST', $this->token_endpoint, 'application/x-www-form-urlencoded', array(), $curlOptions, $payload);
if (!isset($info['http_code']) || $info['http_code'] !== 200) {
throw new \Exception('Unable to obtain access token');
}
$tokenDetails = json_decode($response, true);
if (!isset($tokenDetails['access_token']) || !isset($tokenDetails['expires_in'])) {
throw new \Exception('Unexpected access token response');
}
$this->access_token = $tokenDetails['access_token'];
$now = new \DateTime("now");
$this->access_token_expiry = clone $now;
$this->access_token_expiry = $this->access_token_expiry->add(new \DateInterval('PT'.intval($tokenDetails['expires_in']).'S'));
$this->saveAccessToken();
}
}