PluginProbe
WooCommerce / 11.1.0-rc.2
WooCommerce v11.1.0-rc.2
11.1.0 11.1.0-rc.2 11.1.0-rc.1 11.1.0-beta.2 11.1.0-beta.1 11.0.1 11.0.0 11.0.0-rc.3 11.0.0-rc.2 11.0.0-rc.1 11.0.0-beta.2 11.0.0-beta.1 10.9.4 10.9.3 10.9.2 10.9.1 10.9.0 10.9.0-rc.1 10.9.0-beta.2 10.9.0-beta.1 10.8.1 10.8.0 10.8.0-rc.1 10.8.0-beta.2 10.8.0-beta.1 All 648 releases
woocommerce / includes / class-wc-auth.php
class-wc-auth.php
456 lines 12.7 KB
No matching file
Up and down to move Enter to open Esc to close
Raw Download Zip
1 <?php
2 /**
3 * WooCommerce Auth
4 *
5 * Handles wc-auth endpoint requests.
6 *
7 * @package WooCommerce\RestApi
8 * @since 2.4.0
9 */
10
11 defined( 'ABSPATH' ) || exit;
12
13 /**
14 * Auth class.
15 */
16 class WC_Auth {
17
18 /**
19 * Version.
20 *
21 * @var int
22 */
23 const VERSION = 1;
24
25 /**
26 * Setup class.
27 *
28 * @since 2.4.0
29 */
30 public function __construct() {
31 // Add query vars.
32 add_filter( 'query_vars', array( $this, 'add_query_vars' ), 0 );
33
34 // Register auth endpoint.
35 add_action( 'init', array( __CLASS__, 'add_endpoint' ), 0 );
36
37 // Handle auth requests.
38 add_action( 'parse_request', array( $this, 'handle_auth_requests' ), 0 );
39 }
40
41 /**
42 * Add query vars.
43 *
44 * @since 2.4.0
45 * @param array $vars Query variables.
46 * @return string[]
47 */
48 public function add_query_vars( $vars ) {
49 $vars[] = 'wc-auth-version';
50 $vars[] = 'wc-auth-route';
51 return $vars;
52 }
53
54 /**
55 * Add auth endpoint.
56 *
57 * @since 2.4.0
58 */
59 public static function add_endpoint() {
60 add_rewrite_rule( '^wc-auth/v([1]{1})/(.*)?', 'index.php?wc-auth-version=$matches[1]&wc-auth-route=$matches[2]', 'top' );
61 }
62
63 /**
64 * Get scope name.
65 *
66 * @since 2.4.0
67 * @param string $scope Permission scope.
68 * @return string
69 */
70 protected function get_i18n_scope( $scope ) {
71 $permissions = array(
72 'read' => __( 'Read', 'woocommerce' ),
73 'write' => __( 'Write', 'woocommerce' ),
74 'read_write' => __( 'Read/Write', 'woocommerce' ),
75 );
76
77 return $permissions[ $scope ];
78 }
79
80 /**
81 * Return a list of permissions a scope allows.
82 *
83 * @since 2.4.0
84 * @param string $scope Permission scope.
85 * @return array
86 */
87 protected function get_permissions_in_scope( $scope ) {
88 $permissions = array();
89 switch ( $scope ) {
90 case 'read':
91 $permissions[] = __( 'View coupons', 'woocommerce' );
92 $permissions[] = __( 'View customers', 'woocommerce' );
93 $permissions[] = __( 'View orders and sales reports', 'woocommerce' );
94 $permissions[] = __( 'View products', 'woocommerce' );
95 break;
96 case 'write':
97 $permissions[] = __( 'Create webhooks', 'woocommerce' );
98 $permissions[] = __( 'Create coupons', 'woocommerce' );
99 $permissions[] = __( 'Create customers', 'woocommerce' );
100 $permissions[] = __( 'Create orders', 'woocommerce' );
101 $permissions[] = __( 'Create products', 'woocommerce' );
102 break;
103 case 'read_write':
104 $permissions[] = __( 'Create webhooks', 'woocommerce' );
105 $permissions[] = __( 'View and manage coupons', 'woocommerce' );
106 $permissions[] = __( 'View and manage customers', 'woocommerce' );
107 $permissions[] = __( 'View and manage orders and sales reports', 'woocommerce' );
108 $permissions[] = __( 'View and manage products', 'woocommerce' );
109 break;
110 }
111 return apply_filters( 'woocommerce_api_permissions_in_scope', $permissions, $scope );
112 }
113
114 /**
115 * Build auth urls.
116 *
117 * @since 2.4.0
118 * @param array $data Data to build URL.
119 * @param string $endpoint Endpoint.
120 * @return string
121 */
122 protected function build_url( $data, $endpoint ) {
123 $url = wc_get_endpoint_url( 'wc-auth/v' . self::VERSION, $endpoint, home_url( '/' ) );
124
125 return add_query_arg(
126 array(
127 'app_name' => wc_clean( $data['app_name'] ),
128 'user_id' => wc_clean( $data['user_id'] ),
129 'return_url' => rawurlencode( $this->get_formatted_url( $data['return_url'] ) ),
130 'callback_url' => rawurlencode( $this->get_formatted_url( $data['callback_url'] ) ),
131 'scope' => wc_clean( $data['scope'] ),
132 ),
133 $url
134 );
135 }
136
137 /**
138 * Decode and format a URL.
139 *
140 * @param string $url URL.
141 * @return string
142 */
143 protected function get_formatted_url( $url ) {
144 $url = urldecode( $url );
145
146 if ( ! strstr( $url, '://' ) ) {
147 $url = 'https://' . $url;
148 }
149
150 return $url;
151 }
152
153 /**
154 * Make validation.
155 *
156 * @since 2.4.0
157 * @throws Exception When validate fails.
158 */
159 protected function make_validation() {
160 $data = array();
161 $params = array(
162 'app_name',
163 'user_id',
164 'return_url',
165 'callback_url',
166 'scope',
167 );
168
169 foreach ( $params as $param ) {
170 if ( empty( $_REQUEST[ $param ] ) ) { // WPCS: input var ok, CSRF ok.
171 /* translators: %s: parameter */
172 throw new Exception( sprintf( __( 'Missing parameter %s', 'woocommerce' ), $param ) );
173 }
174
175 $data[ $param ] = wp_unslash( $_REQUEST[ $param ] ); // WPCS: input var ok, CSRF ok, sanitization ok.
176 }
177
178 if ( ! in_array( $data['scope'], array( 'read', 'write', 'read_write' ), true ) ) {
179 /* translators: %s: scope */
180 throw new Exception( sprintf( __( 'Invalid scope %s', 'woocommerce' ), wc_clean( $data['scope'] ) ) );
181 }
182
183 foreach ( array( 'return_url', 'callback_url' ) as $param ) {
184 $param = $this->get_formatted_url( $data[ $param ] );
185
186 if ( false === filter_var( $param, FILTER_VALIDATE_URL ) ) {
187 /* translators: %s: url */
188 throw new Exception( sprintf( __( 'The %s is not a valid URL', 'woocommerce' ), $param ) );
189 }
190 }
191
192 $callback_url = $this->get_formatted_url( $data['callback_url'] );
193
194 if ( 0 !== stripos( $callback_url, 'https://' ) ) {
195 throw new Exception( __( 'The callback_url needs to be over SSL', 'woocommerce' ) );
196 }
197 }
198
199 /**
200 * Create keys.
201 *
202 * @since 2.4.0
203 *
204 * @param string $app_name App name.
205 * @param string $app_user_id User ID.
206 * @param string $scope Scope.
207 *
208 * @return array
209 */
210 protected function create_keys( $app_name, $app_user_id, $scope ) {
211 global $wpdb;
212
213 $description = sprintf(
214 '%s - API (%s)',
215 wc_trim_string( wc_clean( $app_name ), 170 ),
216 gmdate( 'Y-m-d H:i:s' )
217 );
218 $user = wp_get_current_user();
219
220 // Created API keys.
221 $permissions = in_array( $scope, array( 'read', 'write', 'read_write' ), true ) ? sanitize_text_field( $scope ) : 'read';
222 $consumer_key = 'ck_' . wc_rand_hash();
223 $consumer_secret = 'cs_' . wc_rand_hash();
224
225 $wpdb->insert(
226 $wpdb->prefix . 'woocommerce_api_keys',
227 array(
228 'user_id' => $user->ID,
229 'description' => $description,
230 'permissions' => $permissions,
231 'consumer_key' => wc_api_hash( $consumer_key ),
232 'consumer_secret' => $consumer_secret,
233 'truncated_key' => substr( $consumer_key, -7 ),
234 ),
235 array(
236 '%d',
237 '%s',
238 '%s',
239 '%s',
240 '%s',
241 '%s',
242 )
243 );
244
245 return array(
246 'key_id' => $wpdb->insert_id,
247 'user_id' => $app_user_id,
248 'consumer_key' => $consumer_key,
249 'consumer_secret' => $consumer_secret,
250 'key_permissions' => $permissions,
251 );
252 }
253
254 /**
255 * Post consumer data.
256 *
257 * @since 2.4.0
258 *
259 * @throws Exception When validation fails.
260 * @param array $consumer_data Consumer data.
261 * @param string $url URL.
262 * @return bool
263 */
264 protected function post_consumer_data( $consumer_data, $url ) {
265 $params = array(
266 'body' => wp_json_encode( $consumer_data ),
267 'timeout' => 60,
268 'headers' => array(
269 'Content-Type' => 'application/json;charset=' . get_bloginfo( 'charset' ),
270 ),
271 );
272
273 $response = wp_safe_remote_post( esc_url_raw( $url ), $params );
274
275 if ( is_wp_error( $response ) ) {
276 throw new Exception( $response->get_error_message() );
277 } elseif ( 200 !== intval( $response['response']['code'] ) ) {
278 throw new Exception( __( 'An error occurred in the request and at the time were unable to send the consumer data', 'woocommerce' ) );
279 }
280
281 return true;
282 }
283
284 /**
285 * Handle auth requests.
286 *
287 * @since 2.4.0
288 * @throws Exception When auth_endpoint validation fails.
289 */
290 public function handle_auth_requests() {
291 global $wp;
292
293 if ( ! empty( $_GET['wc-auth-version'] ) ) { // WPCS: input var ok, CSRF ok.
294 $wp->query_vars['wc-auth-version'] = wc_clean( wp_unslash( $_GET['wc-auth-version'] ) ); // WPCS: input var ok, CSRF ok.
295 }
296
297 if ( ! empty( $_GET['wc-auth-route'] ) ) { // WPCS: input var ok, CSRF ok.
298 $wp->query_vars['wc-auth-route'] = wc_clean( wp_unslash( $_GET['wc-auth-route'] ) ); // WPCS: input var ok, CSRF ok.
299 }
300
301 // wc-auth endpoint requests.
302 if ( ! empty( $wp->query_vars['wc-auth-version'] ) && ! empty( $wp->query_vars['wc-auth-route'] ) ) {
303 $this->auth_endpoint( $wp->query_vars['wc-auth-route'] );
304 }
305 }
306
307 /**
308 * Auth endpoint.
309 *
310 * @since 2.4.0
311 * @throws Exception When validation fails.
312 * @param string $route Route.
313 */
314 protected function auth_endpoint( $route ) {
315 ob_start();
316
317 $consumer_data = array();
318
319 try {
320 $route = strtolower( wc_clean( $route ) );
321 $this->make_validation();
322
323 $data = wp_unslash( $_REQUEST ); // WPCS: input var ok, CSRF ok.
324
325 // Login endpoint.
326 if ( 'login' === $route && ! is_user_logged_in() ) {
327 /**
328 * If a merchant is using the WordPress SSO (handled through Jetpack)
329 * to manage their authorisation then it is likely they'll find that
330 * their username and password do not work through this form. We
331 * instead need to redirect them to the WordPress login so that they
332 * can then be redirected back here with a valid token.
333 */
334
335 // Check if Jetpack is installed and activated.
336 if ( class_exists( 'Jetpack' ) && Jetpack::connection()->has_connected_owner() ) {
337
338 // Check if the user is using the WordPress.com SSO.
339 if ( Jetpack::is_module_active( 'sso' ) ) {
340
341 $redirect_url = $this->build_url( $data, 'authorize' );
342
343 // Build the SSO URL.
344 $login_url = \Automattic\Jetpack\Connection\SSO::get_instance()->build_sso_button_url(
345 array(
346 'redirect_to' => rawurlencode( esc_url_raw( $redirect_url ) ),
347 'action' => 'login',
348 )
349 );
350
351 // Perform the redirect.
352 wp_safe_redirect( $login_url );
353 exit;
354 }
355 }
356
357 wc_get_template(
358 'auth/form-login.php',
359 array(
360 'app_name' => wc_clean( $data['app_name'] ),
361 'return_url' => add_query_arg(
362 array(
363 'success' => 0,
364 'user_id' => wc_clean( $data['user_id'] ),
365 ),
366 $this->get_formatted_url( $data['return_url'] )
367 ),
368 'redirect_url' => $this->build_url( $data, 'authorize' ),
369 )
370 );
371 exit;
372
373 } elseif ( 'login' === $route && is_user_logged_in() ) {
374 // Redirect with user is logged in.
375 wp_redirect( esc_url_raw( $this->build_url( $data, 'authorize' ) ) );
376 exit;
377
378 } elseif ( 'authorize' === $route && ! is_user_logged_in() ) {
379 // Redirect with user is not logged in and trying to access the authorize endpoint.
380 wp_redirect( esc_url_raw( $this->build_url( $data, 'login' ) ) );
381 exit;
382
383 } elseif ( 'authorize' === $route && current_user_can( 'manage_woocommerce' ) ) {
384 // Authorize endpoint.
385 wc_get_template(
386 'auth/form-grant-access.php',
387 array(
388 'app_name' => wc_clean( $data['app_name'] ),
389 'callback_url' => $this->get_formatted_url( $data['callback_url'] ),
390 'return_url' => add_query_arg(
391 array(
392 'success' => 0,
393 'user_id' => wc_clean( $data['user_id'] ),
394 ),
395 $this->get_formatted_url( $data['return_url'] )
396 ),
397 'scope' => $this->get_i18n_scope( wc_clean( $data['scope'] ) ),
398 'permissions' => $this->get_permissions_in_scope( wc_clean( $data['scope'] ) ),
399 'granted_url' => wp_nonce_url( $this->build_url( $data, 'access_granted' ), 'wc_auth_grant_access', 'wc_auth_nonce' ),
400 'logout_url' => wp_logout_url( $this->build_url( $data, 'login' ) ),
401 'user' => wp_get_current_user(),
402 )
403 );
404 exit;
405
406 } elseif ( 'access_granted' === $route && current_user_can( 'manage_woocommerce' ) ) {
407 // Granted access endpoint.
408 if ( ! isset( $_GET['wc_auth_nonce'] ) || ! wp_verify_nonce( sanitize_key( wp_unslash( $_GET['wc_auth_nonce'] ) ), 'wc_auth_grant_access' ) ) { // WPCS: input var ok.
409 throw new Exception( __( 'Invalid nonce verification', 'woocommerce' ) );
410 }
411
412 $consumer_data = $this->create_keys( $data['app_name'], $data['user_id'], $data['scope'] );
413 $response = $this->post_consumer_data( $consumer_data, $this->get_formatted_url( $data['callback_url'] ) );
414
415 if ( $response ) {
416 wp_redirect(
417 esc_url_raw(
418 add_query_arg(
419 array(
420 'success' => 1,
421 'user_id' => wc_clean( $data['user_id'] ),
422 ),
423 $this->get_formatted_url( $data['return_url'] )
424 )
425 )
426 );
427 exit;
428 }
429 } else {
430 throw new Exception( __( 'You do not have permission to access this page', 'woocommerce' ) );
431 }
432 } catch ( Exception $e ) {
433 $this->maybe_delete_key( $consumer_data );
434
435 /* translators: %s: error message */
436 wp_die( sprintf( esc_html__( 'Error: %s.', 'woocommerce' ), esc_html( $e->getMessage() ) ), esc_html__( 'Access denied', 'woocommerce' ), array( 'response' => 401 ) );
437 }
438 }
439
440 /**
441 * Maybe delete key.
442 *
443 * @since 2.4.0
444 *
445 * @param array $key Key.
446 */
447 private function maybe_delete_key( $key ) {
448 global $wpdb;
449
450 if ( isset( $key['key_id'] ) ) {
451 $wpdb->delete( $wpdb->prefix . 'woocommerce_api_keys', array( 'key_id' => $key['key_id'] ), array( '%d' ) );
452 }
453 }
454 }
455 new WC_Auth();
456