From a1413782e98dd78ccd2cecb66d056d7f3917a311 Mon Sep 17 00:00:00 2001 From: Emili Castells Guasch Date: Tue, 6 Aug 2024 12:32:40 +0200 Subject: [PATCH] Invalidate cache when switching user --- .../src/Authentication/SdkClientToken.php | 15 +++++++++++++-- .../src/Authentication/UserIdToken.php | 15 +++++++++++++-- 2 files changed, 26 insertions(+), 4 deletions(-) diff --git a/modules/ppcp-api-client/src/Authentication/SdkClientToken.php b/modules/ppcp-api-client/src/Authentication/SdkClientToken.php index 2e1f3a7ca..85a447176 100644 --- a/modules/ppcp-api-client/src/Authentication/SdkClientToken.php +++ b/modules/ppcp-api-client/src/Authentication/SdkClientToken.php @@ -83,7 +83,12 @@ class SdkClientToken { */ public function sdk_client_token( string $target_customer_id = '' ): string { if ( $this->cache->has( self::CACHE_KEY ) ) { - return $this->cache->get( self::CACHE_KEY ); + $user_id = $this->cache->get( self::CACHE_KEY )['user_id'] ?? 0; + $access_token = $this->cache->get( self::CACHE_KEY )['access_token'] ?? ''; + + if ( $user_id === get_current_user_id() && $access_token ) { + return $access_token; + } } // phpcs:ignore WordPress.Security.ValidatedSanitizedInput.InputNotSanitized @@ -121,7 +126,13 @@ class SdkClientToken { } $access_token = $json->access_token; - $this->cache->set( self::CACHE_KEY, $access_token ); + + $data = array( + 'access_token' => $access_token, + 'user_id' => get_current_user_id(), + ); + + $this->cache->set( self::CACHE_KEY, $data ); return $access_token; } diff --git a/modules/ppcp-api-client/src/Authentication/UserIdToken.php b/modules/ppcp-api-client/src/Authentication/UserIdToken.php index 2d18d0507..c60801dd5 100644 --- a/modules/ppcp-api-client/src/Authentication/UserIdToken.php +++ b/modules/ppcp-api-client/src/Authentication/UserIdToken.php @@ -83,7 +83,12 @@ class UserIdToken { */ public function id_token( string $target_customer_id = '' ): string { if ( $this->cache->has( self::CACHE_KEY ) ) { - return $this->cache->get( self::CACHE_KEY ); + $user_id = $this->cache->get( self::CACHE_KEY )['user_id'] ?? 0; + $id_token = $this->cache->get( self::CACHE_KEY )['id_token'] ?? ''; + + if ( $user_id === get_current_user_id() && $id_token ) { + return $id_token; + } } $url = trailingslashit( $this->host ) . 'v1/oauth2/token?grant_type=client_credentials&response_type=id_token'; @@ -116,7 +121,13 @@ class UserIdToken { } $id_token = $json->id_token; - $this->cache->set( self::CACHE_KEY, $id_token ); + + $data = array( + 'id_token' => $id_token, + 'user_id' => get_current_user_id(), + ); + + $this->cache->set( self::CACHE_KEY, $data ); return $id_token; }