From 14d1c60da8ec753f308537fb8d662bb2e0839a44 Mon Sep 17 00:00:00 2001 From: Sibin Grasic Date: Sat, 1 Feb 2025 20:59:36 +0100 Subject: [PATCH] feat: Various features and tweaks --- .gitignore | 1 + Functions/API_Key.php | 72 ++++++++++++++++++++++++++++++++++++++++++ composer.json | 5 ++- xwc-helper-fns-api.php | 31 ++++++++++++++++++ 4 files changed, 108 insertions(+), 1 deletion(-) create mode 100644 Functions/API_Key.php create mode 100644 xwc-helper-fns-api.php diff --git a/.gitignore b/.gitignore index 987e2a2..cca7621 100644 --- a/.gitignore +++ b/.gitignore @@ -1,2 +1,3 @@ composer.lock vendor +xwc-helper-fns.php diff --git a/Functions/API_Key.php b/Functions/API_Key.php new file mode 100644 index 0000000..ec157d4 --- /dev/null +++ b/Functions/API_Key.php @@ -0,0 +1,72 @@ +ID; + + if ( $user_id && ! \current_user_can( 'edit_user', $user_id ) && \get_current_user_id() !== $user_id ) { + throw new \InvalidArgumentException( + \esc_html__( + 'You do not have permission to assign API Keys to the selected user.', + 'woocommerce', + ), + ); + } + + return $user_id; + } + + private static function get_permissions( string $permissions ): string { + return \in_array( $permissions, array( 'read', 'write', 'read_write' ), true ) + ? \sanitize_text_field( $permissions ) + : 'read'; + } + + public static function create( int|WP_User $user, string $description, string $permissions, ?string $meta_key ): array { + $user_id = self::get_user_id( $user ); + $permissions = self::get_permissions( $permissions ); + $description = \wc_trim_string( $description, 200 ); + $consumer_key = 'ck_' . \wc_rand_hash(); + $consumer_secret = 'cs_' . \wc_rand_hash(); + + //phpcs:disable SlevomatCodingStandard.Arrays.AlphabeticallySortedByKeys.IncorrectKeyOrder + $data = array( + 'user_id' => $user_id, + 'description' => $description, + 'permissions' => $permissions, + 'consumer_key' => \wc_api_hash( $consumer_key ), + 'consumer_secret' => $consumer_secret, + 'truncated_key' => \substr( $consumer_key, -7 ), + ); + //phpcs:enable SlevomatCodingStandard.Arrays.AlphabeticallySortedByKeys.IncorrectKeyOrder + + global $wpdb; + + $wpdb->insert( + $wpdb->prefix . 'woocommerce_api_keys', + $data, + array( '%d', '%s', '%s', '%s', '%s', '%s' ), + ); + + if ( 0 === $wpdb->insert_id ) { + throw new \Exception( \esc_html__( 'There was an error generating your API Key.', 'woocommerce' ) ); + } + + if ( null !== $meta_key ) { + \update_user_meta( $user_id, $meta_key, $wpdb->insert_id ); + } + + return array( + 'ck' => $consumer_key, + 'cs' => $consumer_secret, + 'id' => $wpdb->insert_id, + ); + } +} diff --git a/composer.json b/composer.json index 1ff4d63..fa7c84d 100644 --- a/composer.json +++ b/composer.json @@ -27,6 +27,9 @@ "autoload": { "psr-4": { "XWC\\": "" - } + }, + "files": [ + "xwc-helper-fns-api.php" + ] } } diff --git a/xwc-helper-fns-api.php b/xwc-helper-fns-api.php new file mode 100644 index 0000000..a506174 --- /dev/null +++ b/xwc-helper-fns-api.php @@ -0,0 +1,31 @@ +