@@ -62,52 +62,16 @@ public function __construct(
6262 */
6363 private function getToken (): string
6464 {
65- // Cache token to avoid hammering the auth server on every request
66- $ cacheKey = 'buerklin.oauth.token ' ;
67- $ item = $ this ->partInfoCache ->getItem ($ cacheKey );
68-
69- if ($ item ->isHit ()) {
70- $ token = $ item ->get ();
71- if (is_string ($ token ) && $ token !== '' ) {
72- return $ token ;
73- }
74- }
75-
76- // Buerklin OAuth2 password grant (ROPC)
77- $ resp = $ this ->client ->request ('POST ' , 'https://www.buerklin.com/authorizationserver/oauth/token/ ' , [
78- 'headers ' => [
79- 'Accept ' => 'application/json ' ,
80- 'Content-Type ' => 'application/x-www-form-urlencoded ' ,
81- ],
82- 'body ' => [
83- 'grant_type ' => 'password ' ,
84- 'client_id ' => $ this ->settings ->clientId ,
85- 'client_secret ' => $ this ->settings ->secret ,
86- 'username ' => $ this ->settings ->username ,
87- 'password ' => $ this ->settings ->password ,
88- ],
89- ]);
90-
91- $ data = $ resp ->toArray (false );
92-
93- if (!isset ($ data ['access_token ' ])) {
94- throw new \RuntimeException (
95- 'Invalid token response from Buerklin: HTTP ' . $ resp ->getStatusCode () . ' body= ' . $ resp ->getContent (false )
96- );
65+ //Check if we already have a token saved for this app, otherwise we have to retrieve one via OAuth
66+ if (!$ this ->authTokenManager ->hasToken (self ::OAUTH_APP_NAME )) {
67+ $ this ->authTokenManager ->retrieveROPCToken (self ::OAUTH_APP_NAME , $ this ->settings ->username , $ this ->settings ->password );
9768 }
9869
99- $ token = (string ) $ data ['access_token ' ];
100-
101- // Cache for (expires_in - 30s) if available
102- $ ttl = 300 ;
103- if (isset ($ data ['expires_in ' ]) && is_numeric ($ data ['expires_in ' ])) {
104- $ ttl = max (60 , (int ) $ data ['expires_in ' ] - 30 );
70+ $ token = $ this ->authTokenManager ->getAlwaysValidTokenString (self ::OAUTH_APP_NAME );
71+ if ($ token === null ) {
72+ throw new \RuntimeException ('Could not retrieve OAuth token for Buerklin API. ' );
10573 }
10674
107- $ item ->set ($ token );
108- $ item ->expiresAfter ($ ttl );
109- $ this ->partInfoCache ->save ($ item );
110-
11175 return $ token ;
11276 }
11377
0 commit comments