class-wc-auth.php 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420
  1. <?php
  2. /**
  3. * WooCommerce Auth
  4. *
  5. * Handles wc-auth endpoint requests.
  6. *
  7. * @package WooCommerce/API
  8. * @since 2.4.0
  9. */
  10. defined( 'ABSPATH' ) || exit;
  11. /**
  12. * Auth class.
  13. */
  14. class WC_Auth {
  15. /**
  16. * Version.
  17. *
  18. * @var int
  19. */
  20. const VERSION = 1;
  21. /**
  22. * Setup class.
  23. *
  24. * @since 2.4.0
  25. */
  26. public function __construct() {
  27. // Add query vars.
  28. add_filter( 'query_vars', array( $this, 'add_query_vars' ), 0 );
  29. // Register auth endpoint.
  30. add_action( 'init', array( __CLASS__, 'add_endpoint' ), 0 );
  31. // Handle auth requests.
  32. add_action( 'parse_request', array( $this, 'handle_auth_requests' ), 0 );
  33. }
  34. /**
  35. * Add query vars.
  36. *
  37. * @since 2.4.0
  38. * @param array $vars Query variables.
  39. * @return string[]
  40. */
  41. public function add_query_vars( $vars ) {
  42. $vars[] = 'wc-auth-version';
  43. $vars[] = 'wc-auth-route';
  44. return $vars;
  45. }
  46. /**
  47. * Add auth endpoint.
  48. *
  49. * @since 2.4.0
  50. */
  51. public static function add_endpoint() {
  52. add_rewrite_rule( '^wc-auth/v([1]{1})/(.*)?', 'index.php?wc-auth-version=$matches[1]&wc-auth-route=$matches[2]', 'top' );
  53. }
  54. /**
  55. * Get scope name.
  56. *
  57. * @since 2.4.0
  58. * @param string $scope Permission scope.
  59. * @return string
  60. */
  61. protected function get_i18n_scope( $scope ) {
  62. $permissions = array(
  63. 'read' => __( 'Read', 'woocommerce' ),
  64. 'write' => __( 'Write', 'woocommerce' ),
  65. 'read_write' => __( 'Read/Write', 'woocommerce' ),
  66. );
  67. return $permissions[ $scope ];
  68. }
  69. /**
  70. * Return a list of permissions a scope allows.
  71. *
  72. * @since 2.4.0
  73. * @param string $scope Permission scope.
  74. * @return array
  75. */
  76. protected function get_permissions_in_scope( $scope ) {
  77. $permissions = array();
  78. switch ( $scope ) {
  79. case 'read':
  80. $permissions[] = __( 'View coupons', 'woocommerce' );
  81. $permissions[] = __( 'View customers', 'woocommerce' );
  82. $permissions[] = __( 'View orders and sales reports', 'woocommerce' );
  83. $permissions[] = __( 'View products', 'woocommerce' );
  84. break;
  85. case 'write':
  86. $permissions[] = __( 'Create webhooks', 'woocommerce' );
  87. $permissions[] = __( 'Create coupons', 'woocommerce' );
  88. $permissions[] = __( 'Create customers', 'woocommerce' );
  89. $permissions[] = __( 'Create orders', 'woocommerce' );
  90. $permissions[] = __( 'Create products', 'woocommerce' );
  91. break;
  92. case 'read_write':
  93. $permissions[] = __( 'Create webhooks', 'woocommerce' );
  94. $permissions[] = __( 'View and manage coupons', 'woocommerce' );
  95. $permissions[] = __( 'View and manage customers', 'woocommerce' );
  96. $permissions[] = __( 'View and manage orders and sales reports', 'woocommerce' );
  97. $permissions[] = __( 'View and manage products', 'woocommerce' );
  98. break;
  99. }
  100. return apply_filters( 'woocommerce_api_permissions_in_scope', $permissions, $scope );
  101. }
  102. /**
  103. * Build auth urls.
  104. *
  105. * @since 2.4.0
  106. * @param array $data Data to build URL.
  107. * @param string $endpoint Endpoint.
  108. * @return string
  109. */
  110. protected function build_url( $data, $endpoint ) {
  111. $url = wc_get_endpoint_url( 'wc-auth/v' . self::VERSION, $endpoint, home_url( '/' ) );
  112. return add_query_arg(
  113. array(
  114. 'app_name' => wc_clean( $data['app_name'] ),
  115. 'user_id' => wc_clean( $data['user_id'] ),
  116. 'return_url' => rawurlencode( $this->get_formatted_url( $data['return_url'] ) ),
  117. 'callback_url' => rawurlencode( $this->get_formatted_url( $data['callback_url'] ) ),
  118. 'scope' => wc_clean( $data['scope'] ),
  119. ), $url
  120. );
  121. }
  122. /**
  123. * Decode and format a URL.
  124. *
  125. * @param string $url URL.
  126. * @return string
  127. */
  128. protected function get_formatted_url( $url ) {
  129. $url = urldecode( $url );
  130. if ( ! strstr( $url, '://' ) ) {
  131. $url = 'https://' . $url;
  132. }
  133. return $url;
  134. }
  135. /**
  136. * Make validation.
  137. *
  138. * @since 2.4.0
  139. * @throws Exception When validate fails.
  140. */
  141. protected function make_validation() {
  142. $data = array();
  143. $params = array(
  144. 'app_name',
  145. 'user_id',
  146. 'return_url',
  147. 'callback_url',
  148. 'scope',
  149. );
  150. foreach ( $params as $param ) {
  151. if ( empty( $_REQUEST[ $param ] ) ) { // WPCS: input var ok, CSRF ok.
  152. /* translators: %s: parameter */
  153. throw new Exception( sprintf( __( 'Missing parameter %s', 'woocommerce' ), $param ) );
  154. }
  155. $data[ $param ] = wp_unslash( $_REQUEST[ $param ] ); // WPCS: input var ok, CSRF ok, sanitization ok.
  156. }
  157. if ( ! in_array( $data['scope'], array( 'read', 'write', 'read_write' ), true ) ) {
  158. /* translators: %s: scope */
  159. throw new Exception( sprintf( __( 'Invalid scope %s', 'woocommerce' ), wc_clean( $data['scope'] ) ) );
  160. }
  161. foreach ( array( 'return_url', 'callback_url' ) as $param ) {
  162. $param = $this->get_formatted_url( $data[ $param ] );
  163. if ( false === filter_var( $param, FILTER_VALIDATE_URL ) ) {
  164. /* translators: %s: url */
  165. throw new Exception( sprintf( __( 'The %s is not a valid URL', 'woocommerce' ), $param ) );
  166. }
  167. }
  168. $callback_url = $this->get_formatted_url( $data['callback_url'] );
  169. if ( 0 !== stripos( $callback_url, 'https://' ) ) {
  170. throw new Exception( __( 'The callback_url needs to be over SSL', 'woocommerce' ) );
  171. }
  172. }
  173. /**
  174. * Create keys.
  175. *
  176. * @since 2.4.0
  177. *
  178. * @param string $app_name App name.
  179. * @param string $app_user_id User ID.
  180. * @param string $scope Scope.
  181. *
  182. * @return array
  183. */
  184. protected function create_keys( $app_name, $app_user_id, $scope ) {
  185. global $wpdb;
  186. $description = sprintf(
  187. /* translators: 1: app name 2: scope 3: date 4: time */
  188. __( '%1$s - API %2$s (created on %3$s at %4$s).', 'woocommerce' ),
  189. wc_clean( $app_name ),
  190. $this->get_i18n_scope( $scope ),
  191. date_i18n( wc_date_format() ),
  192. date_i18n( wc_time_format() )
  193. );
  194. $user = wp_get_current_user();
  195. // Created API keys.
  196. $permissions = in_array( $scope, array( 'read', 'write', 'read_write' ), true ) ? sanitize_text_field( $scope ) : 'read';
  197. $consumer_key = 'ck_' . wc_rand_hash();
  198. $consumer_secret = 'cs_' . wc_rand_hash();
  199. $wpdb->insert(
  200. $wpdb->prefix . 'woocommerce_api_keys',
  201. array(
  202. 'user_id' => $user->ID,
  203. 'description' => $description,
  204. 'permissions' => $permissions,
  205. 'consumer_key' => wc_api_hash( $consumer_key ),
  206. 'consumer_secret' => $consumer_secret,
  207. 'truncated_key' => substr( $consumer_key, -7 ),
  208. ),
  209. array(
  210. '%d',
  211. '%s',
  212. '%s',
  213. '%s',
  214. '%s',
  215. '%s',
  216. )
  217. );
  218. return array(
  219. 'key_id' => $wpdb->insert_id,
  220. 'user_id' => $app_user_id,
  221. 'consumer_key' => $consumer_key,
  222. 'consumer_secret' => $consumer_secret,
  223. 'key_permissions' => $permissions,
  224. );
  225. }
  226. /**
  227. * Post consumer data.
  228. *
  229. * @since 2.4.0
  230. *
  231. * @throws Exception When validation fails.
  232. * @param array $consumer_data Consumer data.
  233. * @param string $url URL.
  234. * @return bool
  235. */
  236. protected function post_consumer_data( $consumer_data, $url ) {
  237. $params = array(
  238. 'body' => wp_json_encode( $consumer_data ),
  239. 'timeout' => 60,
  240. 'headers' => array(
  241. 'Content-Type' => 'application/json;charset=' . get_bloginfo( 'charset' ),
  242. ),
  243. );
  244. $response = wp_safe_remote_post( esc_url_raw( $url ), $params );
  245. if ( is_wp_error( $response ) ) {
  246. throw new Exception( $response->get_error_message() );
  247. } elseif ( 200 !== intval( $response['response']['code'] ) ) {
  248. throw new Exception( __( 'An error occurred in the request and at the time were unable to send the consumer data', 'woocommerce' ) );
  249. }
  250. return true;
  251. }
  252. /**
  253. * Handle auth requests.
  254. *
  255. * @since 2.4.0
  256. */
  257. public function handle_auth_requests() {
  258. global $wp;
  259. if ( ! empty( $_GET['wc-auth-version'] ) ) { // WPCS: input var ok, CSRF ok.
  260. $wp->query_vars['wc-auth-version'] = wc_clean( wp_unslash( $_GET['wc-auth-version'] ) ); // WPCS: input var ok, CSRF ok.
  261. }
  262. if ( ! empty( $_GET['wc-auth-route'] ) ) {
  263. $wp->query_vars['wc-auth-route'] = wc_clean( wp_unslash( $_GET['wc-auth-route'] ) ); // WPCS: input var ok, CSRF ok.
  264. }
  265. // wc-auth endpoint requests.
  266. if ( ! empty( $wp->query_vars['wc-auth-version'] ) && ! empty( $wp->query_vars['wc-auth-route'] ) ) {
  267. $this->auth_endpoint( $wp->query_vars['wc-auth-route'] );
  268. }
  269. }
  270. /**
  271. * Auth endpoint.
  272. *
  273. * @since 2.4.0
  274. * @throws Exception When validation fails.
  275. * @param string $route Route.
  276. */
  277. protected function auth_endpoint( $route ) {
  278. ob_start();
  279. $consumer_data = array();
  280. try {
  281. $route = strtolower( wc_clean( $route ) );
  282. $this->make_validation();
  283. $data = wp_unslash( $_REQUEST ); // WPCS: input var ok, CSRF ok.
  284. // Login endpoint.
  285. if ( 'login' === $route && ! is_user_logged_in() ) {
  286. wc_get_template(
  287. 'auth/form-login.php', array(
  288. 'app_name' => wc_clean( $data['app_name'] ),
  289. 'return_url' => add_query_arg(
  290. array(
  291. 'success' => 0,
  292. 'user_id' => wc_clean( $data['user_id'] ),
  293. ), $this->get_formatted_url( $data['return_url'] )
  294. ),
  295. 'redirect_url' => $this->build_url( $data, 'authorize' ),
  296. )
  297. );
  298. exit;
  299. } elseif ( 'login' === $route && is_user_logged_in() ) {
  300. // Redirect with user is logged in.
  301. wp_redirect( esc_url_raw( $this->build_url( $data, 'authorize' ) ) );
  302. exit;
  303. } elseif ( 'authorize' === $route && ! is_user_logged_in() ) {
  304. // Redirect with user is not logged in and trying to access the authorize endpoint.
  305. wp_redirect( esc_url_raw( $this->build_url( $data, 'login' ) ) );
  306. exit;
  307. } elseif ( 'authorize' === $route && current_user_can( 'manage_woocommerce' ) ) {
  308. // Authorize endpoint.
  309. wc_get_template(
  310. 'auth/form-grant-access.php', array(
  311. 'app_name' => wc_clean( $data['app_name'] ),
  312. 'return_url' => add_query_arg(
  313. array(
  314. 'success' => 0,
  315. 'user_id' => wc_clean( $data['user_id'] ),
  316. ), $this->get_formatted_url( $data['return_url'] )
  317. ),
  318. 'scope' => $this->get_i18n_scope( wc_clean( $data['scope'] ) ),
  319. 'permissions' => $this->get_permissions_in_scope( wc_clean( $data['scope'] ) ),
  320. 'granted_url' => wp_nonce_url( $this->build_url( $data, 'access_granted' ), 'wc_auth_grant_access', 'wc_auth_nonce' ),
  321. 'logout_url' => wp_logout_url( $this->build_url( $data, 'login' ) ),
  322. 'user' => wp_get_current_user(),
  323. )
  324. );
  325. exit;
  326. } elseif ( 'access_granted' === $route && current_user_can( 'manage_woocommerce' ) ) {
  327. // Granted access endpoint.
  328. 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.
  329. throw new Exception( __( 'Invalid nonce verification', 'woocommerce' ) );
  330. }
  331. $consumer_data = $this->create_keys( $data['app_name'], $data['user_id'], $data['scope'] );
  332. $response = $this->post_consumer_data( $consumer_data, $this->get_formatted_url( $data['callback_url'] ) );
  333. if ( $response ) {
  334. wp_redirect(
  335. esc_url_raw(
  336. add_query_arg(
  337. array(
  338. 'success' => 1,
  339. 'user_id' => wc_clean( $data['user_id'] ),
  340. ), $this->get_formatted_url( $data['return_url'] )
  341. )
  342. )
  343. );
  344. exit;
  345. }
  346. } else {
  347. throw new Exception( __( 'You do not have permission to access this page', 'woocommerce' ) );
  348. }
  349. } catch ( Exception $e ) {
  350. $this->maybe_delete_key( $consumer_data );
  351. /* translators: %s: error message */
  352. wp_die( sprintf( esc_html__( 'Error: %s.', 'woocommerce' ), esc_html( $e->getMessage() ) ), esc_html__( 'Access denied', 'woocommerce' ), array( 'response' => 401 ) );
  353. }
  354. }
  355. /**
  356. * Maybe delete key.
  357. *
  358. * @since 2.4.0
  359. *
  360. * @param array $key Key.
  361. */
  362. private function maybe_delete_key( $key ) {
  363. global $wpdb;
  364. if ( isset( $key['key_id'] ) ) {
  365. $wpdb->delete( $wpdb->prefix . 'woocommerce_api_keys', array( 'key_id' => $key['key_id'] ), array( '%d' ) );
  366. }
  367. }
  368. }
  369. new WC_Auth();