Load API IDs in Settings constructor

Make sure auth token is correct for Client ID
Add a one-time 404 auth_refresh and retry
This commit is contained in:
Justin Foell
2019-09-21 17:59:40 -05:00
parent bfca681199
commit 9d8e071f96
4 changed files with 41 additions and 14 deletions
+19 -11
View File
@@ -81,8 +81,9 @@ class WPStrava_API {
* @author Justin Foell <justin@foell.org>
*/
public function get( $uri, $args = null ) {
$url = self::STRAVA_V3_API;
static $retry = true;
$url = self::STRAVA_V3_API;
$url .= $uri;
if ( ! empty( $args ) ) {
@@ -101,11 +102,22 @@ class WPStrava_API {
}
$response = wp_remote_get( $url, $get_args );
if ( is_wp_error( $response ) ) {
throw WPStrava_Exception::from_wp_error( $response );
}
// Try *one* real-time token refresh if 404.
if ( $retry && 404 == $response['response']['code'] ) {
$retry = false;
$auth = WPStrava::get_instance()->auth;
if ( $auth instanceof WPStrava_AuthRefresh ) {
$auth->auth_refresh();
}
return $this->get( $uri, $args );
} else {
$retry = true;
}
if ( 200 != $response['response']['code'] ) { // phpcs:ignore WordPress.PHP.StrictComparisons.LooseComparison
// See if there's useful info in the body.
@@ -138,21 +150,17 @@ class WPStrava_API {
* @since 2.0.0
*/
private function get_access_token() {
static $access_token = null;
// If client_id not set (OAuth set-up), don't even look.
if ( ! $this->client_id ) {
return null;
}
if ( ! $access_token ) {
$settings = WPStrava::get_instance()->settings;
$info = $settings->info;
$settings = WPStrava::get_instance()->settings;
$info = $settings->info;
if ( ! empty( $info[ $this->client_id ]->access_token ) ) {
$access_token = $info[ $this->client_id ]->access_token;
}
if ( ! empty( $info[ $this->client_id ]->access_token ) ) {
return $info[ $this->client_id ]->access_token;
}
return $access_token;
return null;
}
}
+1 -1
View File
@@ -65,7 +65,7 @@ class WPStrava_AuthRefresh extends WPStrava_Auth {
'client_id' => $client_id,
'redirect_uri' => $this->get_redirect_param(),
'approval_prompt' => 'auto',
'scope' => 'read,activity:read',
'scope' => 'activity:read,read',
),
$this->auth_url
);
+11 -1
View File
@@ -16,6 +16,17 @@ class WPStrava_Settings {
private $option_page = 'wp-strava-settings-group';
private $adding_athlete = true;
/**
* Settings constructor.
*
* @author Justin Foell <justin@foell.org>
* @since 2.0
*/
public function __construct() {
$this->ids = $this->get_ids();
}
/**
* Register actions & filters for menus and authentication.
*
@@ -54,7 +65,6 @@ class WPStrava_Settings {
add_settings_section( 'strava_api', __( 'Strava API', 'wp-strava' ), array( $this, 'print_api_instructions' ), 'wp-strava' );
$this->adding_athlete = $this->is_adding_athlete();
$this->ids = $this->get_ids();
if ( $this->ids_empty( $this->ids ) ) {
register_setting( $this->option_page, 'strava_client_id', array( $this, 'sanitize_client_id' ) );