This repository has been archived by the owner on Dec 5, 2023. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 0
/
wp-google-auth-api.php
260 lines (215 loc) · 6.5 KB
/
wp-google-auth-api.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
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
<?php
/**
* WP Google Auth API
*
* @package WP-API-Libraries\WP-Google-Auth-API
*/
/*
* Plugin Name: WP Google Auth API
* Plugin URI: https://github.com/wp-api-libraries/wp-google-auth-api
* Description: Generate access tokens for google service accounts.
* Author: WP API Libraries
* Version: 1.0.0
* Author URI: https://wp-api-libraries.com
* GitHub Plugin URI: https://github.com/wp-api-libraries/wp-google-auth-api
* GitHub Branch: master
*/
/* Exit if accessed directly. */
if ( ! defined( 'ABSPATH' ) ) {
exit;
}
/* Check if class exists. */
if ( ! class_exists( 'WPGoogleAuth' ) ) {
/**
* WPGoogleAuth Class.
*/
class WPGoogleAuth {
/**
* API Key.
*
* @var string
*/
public $access_token;
/**
* The type of token returned.
*
* @var string
*/
public $token_type;
/**
* Unix timestamp of when the token will expire.
*
* @var string
*/
public $expires_at;
/**
* Service Account Array
*
* @var Array
*/
private $service_account;
/**
* Token access scope to be requested.
*
* @access protected
* @var string
*/
private $scope;
/**
* Args to be passed into request.
*
* @var array
*/
private $args = array();
/**
* Class constructor.
*
* @param string $service_account_json Service account json token.
* @param string $scope Authorization scope you want to grant the token.
*/
public function __construct( $service_account_json, $scope ) {
$service_account = $this->is_json_valid( $service_account_json );
if ( is_wp_error( $service_account ) ) {
$this->access_token = $service_account;
return $this;
}
$this->service_account = $service_account;
$response = $this->generate_token( $scope );
if ( is_wp_error( $response ) ) {
$this->access_token = $response;
}
return $this;
}
/**
* Prepares API request.
*
* @param array $args Arguments to pass into the API call.
* @param string $method HTTP Method to use for request.
* @return self Returns an instance of itself so it can be chained to the fetch method.
*/
protected function build_request( $args = array(), $method = 'GET' ) {
// Start building query.
$this->set_headers();
$this->args['method'] = $method;
$this->args['body'] = $args;
return $this;
}
/**
* Fetch the request from the API.
*
* @access private
* @return array|WP_Error Request results or WP_Error on request failure.
*/
protected function fetch() {
// Make the request.
$response = wp_remote_request( $this->service_account->token_uri, $this->args );
// Retrieve Status code & body.
$code = wp_remote_retrieve_response_code( $response );
$body = json_decode( wp_remote_retrieve_body( $response ) );
$this->clear();
// Return WP_Error if request is not successful.
if ( ! $this->is_status_ok( $code ) ) {
// translators: HTTP status code.
return new WP_Error( 'response-error', sprintf( __( 'Status: %d', 'wp-google-auth-api' ), $code ), $body );
}
return $body;
}
/**
* Set request headers.
*/
protected function set_headers() {
// Set request headers.
$this->args['headers'] = array(
'Content-Type' => 'application/x-www-form-urlencoded',
);
}
/**
* Clear query data.
*/
protected function clear() {
$this->args = array();
}
/**
* Check if HTTP status code is a success.
*
* @param int $code HTTP status code.
* @return boolean True if status is within valid range.
*/
protected function is_status_ok( $code ) {
return ( 200 <= $code && 300 > $code );
}
/**
* Undocumented function
*
* @param string $service_account_json Service account json string to be validated.
* @return Object|WP_Error
*/
private function is_json_valid( $service_account_json ) {
$service_account = json_decode( $service_account_json );
if ( json_last_error() !== JSON_ERROR_NONE
|| ! array_key_exists( 'private_key', $service_account )
|| ! array_key_exists( 'client_email', $service_account )
|| ! array_key_exists( 'token_uri', $service_account )
|| ! array_key_exists( 'auth_uri', $service_account )
) {
return new WP_Error( 'invalid-service-account-json', __( 'Please verify that a valid service account json string is being used.', 'wp-google-auth-api' ) );
}
return $service_account;
}
/**
* Generate access token.
*
* @param string $scope Auth scope to grant the token.
* @return string|WP_Error
*/
public function generate_token( $scope ) {
// Unix time of when token was issued.
$issue_time = time();
// JWT Header.
$header = wp_json_encode(
array(
'typ' => 'JWT',
'alg' => 'RS256',
)
);
// JWT Payload.
$payload = wp_json_encode(
array(
'iss' => $this->service_account->client_email,
'scope' => $scope,
'aud' => $this->service_account->token_uri,
'exp' => $issue_time + ( MINUTE_IN_SECONDS * 59 ), // Set to max amount of time.
'iat' => $issue_time,
)
);
// Encode Header to Base64Url String.
$base64_header = str_replace( array( '+', '/', '=' ), array( '-', '_', '' ), base64_encode( $header ) );
// Encode Payload to Base64Url String.
$base64_payload = str_replace( array( '+', '/', '=' ), array( '-', '_', '' ), base64_encode( $payload ) );
// Create Signature Hash.
if ( ! openssl_sign( $base64_header . '.' . $base64_payload, $signature, $this->service_account->private_key, OPENSSL_ALGO_SHA256 ) ) {
return new WP_Error( 'token-signature-failed', __( 'Please verify that a valid private key is included in service account json.', 'wp-google-auth-api' ) );
}
// Prepare URL and make http request.
$base64_signature = str_replace( array( '+', '/', '=' ), array( '-', '_', '' ), base64_encode( $signature ) );
$args = 'grant_type=' . rawurlencode( 'urn:ietf:params:oauth:grant-type:jwt-bearer' ) . '&assertion=' . $base64_header . '.' . $base64_payload . '.' . $base64_signature;
$response = $this->build_request( $args, 'POST' )->fetch();
if ( is_wp_error( $response ) ) {
$this->access_token = $response;
return $this;
}
$this->access_token = $response->access_token;
$this->token_type = $response->token_type;
$this->expires_at = time() + $response->expires_in - 1;
return $this->access_token;
}
/**
* Method that checks if current token is expired.
*
* @return boolean
*/
public function is_token_expired() {
return ( time() > $this->expires_at );
}
}
}