<?php
|
namespace JVBase\integrations;
|
|
use JVBase\meta\Meta;
|
use JVBase\registrar\Registrar;
|
|
if (!defined('ABSPATH')) {
|
exit;
|
}
|
|
trait UserConnection {
|
use _Base;
|
protected function determineUser():void
|
{
|
if (current_user_can('manage_options')) {
|
$this->switchUser();
|
}
|
$this->switchUser(get_current_user_id());
|
}
|
public function switchUser(?int $userID = null):bool
|
{
|
if (!$this->userCanConnect($userID)) {
|
return false;
|
}
|
$this->clearUser();
|
$this->userID = $userID;
|
$this->initializeRateLimiters();
|
return true;
|
}
|
protected function determineUserID(int $userID):bool|int
|
{
|
if (!$this->userCanConnect($userID)) {
|
return false;
|
}
|
return $userID;
|
}
|
protected function clearUser():void
|
{
|
$this->userID = false;
|
$this->credentials = [];
|
if (property_exists($this, 'rateLimiter')) {
|
$this->requestLimiter?->saveHistory();
|
$this->requestLimiter = null;
|
}
|
if (property_exists($this, 'oathLimiter')) {
|
$this->oauthLimiter?->saveHistory();
|
$this->oauthLimiter = null;
|
}
|
}
|
|
public function userCanConnect(?int $userID):bool
|
{
|
if (current_user_can('manage_options')) {
|
return true;
|
}
|
|
$user = get_userdata($userID);
|
if (!$user || is_wp_error($user)) {
|
return false;
|
}
|
$role = jvbUserRole($userID);
|
$registrar = Registrar::getInstance($role);
|
if (!$registrar || !$registrar->hasIntegration($this->service_name)) {
|
return false;
|
}
|
|
return (bool) Meta::forUser($userID)->get('integration_'.$this->service_name.'_connected');
|
}
|
|
}
|