| | |
| | | trait OAuth |
| | | { |
| | | use _Base, Admin; |
| | | protected bool $hasOAuth = true; |
| | | protected OAuthURLs $oauth; |
| | | /** |
| | | * Child classes must set this (e.g. 'https://api.example.com/v1/') |
| | |
| | | protected int $oauthTTL = 300; |
| | | protected array $oathScopes = []; |
| | | |
| | | protected ?RateLimits $oauthLimiter; |
| | | |
| | | protected function initializeOAuthRateLimiter():void |
| | | { |
| | | $key = $this->service_name; |
| | | if (!is_null($this->userID)) { |
| | | $key .= '_'.$this->userID; |
| | | } |
| | | $key .= '_oauth'; |
| | | $this->oauthLimiter = new RateLimits($key, ['s' => 1, 'm' => 10, 'h' => 100]); |
| | | } |
| | | /** |
| | | * @return array Defaults to the base getRequestHeaders, but can optionally be overridden |
| | | */ |
| | |
| | | $this->addAction($a['name'], $a['action'], $a['slug']??null, $a['icon']??null, $a['label']??null); |
| | | } |
| | | } |
| | | public function hasOAuthCredentials(?int $userID = null):bool |
| | | { |
| | | if ($userID !== $this->userID) { |
| | | $this->switchUser($userID); |
| | | } |
| | | return $this->hasValidOAuth(); |
| | | } |
| | | public function handleOAuthConnect():array |
| | | { |
| | | if (!$this->hasOAuth) { |
| | | return $this->response(false, 'Not an OAuth service'); |
| | | } |
| | | $url = $this->getOAuthUrl(); |
| | | if ($url) { |
| | | return [ |
| | |
| | | |
| | | public function revokeOAuth():bool |
| | | { |
| | | if (!$this->hasOAuth) { |
| | | return false; |
| | | } |
| | | if (empty($this->oauth['revoke'])) { |
| | | error_log('No revoke url set for '.$this->service_name); |
| | | return false; |
| | |
| | | |
| | | public function getOAuthURL(?string $return_url = null):string |
| | | { |
| | | if (!$this->hasOAuth) { |
| | | return ''; |
| | | } |
| | | |
| | | $credentials = $this->loadCredentials(); |
| | | if (empty($this->oauth['authorize'])) { |
| | | $this->logError('getOAuthUrl', 'OAuth authorize URL not configured'); |
| | |
| | | |
| | | protected function getRedirectUri():string |
| | | { |
| | | if ($this->hasOAuth) { |
| | | return admin_url('admin-ajax.php?action='.BASE . $this->service_name . '_oauth_callback'); |
| | | } |
| | | return rest_url('jvb/v1/oauth/callback?service=' . $this->service_name); |
| | | return admin_url('admin-ajax.php?action='.BASE . $this->service_name . '_oauth_callback'); |
| | | } |
| | | |
| | | /**************************************************** |
| | | * UTILITY |
| | | ****************************************************/ |
| | | protected function getAccessToken():string |
| | | { |
| | | return $this->loadCredentials()['access_token']??''; |
| | | } |
| | | } |