feat: add Discord facade
This commit is contained in:
@@ -24,8 +24,11 @@ namespace App\Helpers;
|
||||
|
||||
use App\Exceptions\AccountNotLinkedException;
|
||||
use App\User;
|
||||
use Carbon\Carbon;
|
||||
use Illuminate\Http\Client\RequestException;
|
||||
use Illuminate\Support\Collection;
|
||||
use Illuminate\Support\Facades\Auth;
|
||||
use Illuminate\Support\Facades\Cache;
|
||||
use Illuminate\Support\Facades\Crypt;
|
||||
use Illuminate\Support\Facades\Http;
|
||||
|
||||
@@ -50,7 +53,7 @@ class Discord
|
||||
|
||||
|
||||
public function __construct() {
|
||||
if (!is_null($this->workingGuild)) {
|
||||
if (isset($this->workingGuild)) {
|
||||
$this->setWorkingGuild(config('services.discord.home_guild'));
|
||||
}
|
||||
}
|
||||
@@ -85,6 +88,47 @@ class Discord
|
||||
throw new AccountNotLinkedException('Specified website user has not linked their Discord account yet.');
|
||||
}
|
||||
|
||||
/**
|
||||
* Obtains the current user's authentication info. Caches the data for the access_token's TTL, thus
|
||||
* preventing unnecessary API requests.
|
||||
*
|
||||
* @return object Current user's authentication info (has no sensitive fields)
|
||||
* @throws RequestException
|
||||
*/
|
||||
public function getAuthorizationInfo(): object {
|
||||
|
||||
if (Cache::has($this->user->discord_user_id)) {
|
||||
return unserialize(Cache::get($this->user->discord_user_id));
|
||||
}
|
||||
else {
|
||||
$authInfo = (object) Http::withToken($this->user->discord_token)
|
||||
->get(config('services.discord.base_url') . '/oauth2/@me')
|
||||
->throw()
|
||||
->json();
|
||||
|
||||
Cache::put($this->user->discord_user_id, serialize($authInfo), Carbon::parse($authInfo->expires));
|
||||
|
||||
return $authInfo;
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
/**
|
||||
* Checks if the user's token is close to expiring.
|
||||
* Tokens should be refreshed the day before they expire.
|
||||
*
|
||||
* @return bool Whether the user's token needs to be refreshed
|
||||
* @throws RequestException
|
||||
*/
|
||||
public function needsRefresh(): bool {
|
||||
return Carbon::parse($this->getAuthorizationInfo()->expires)->diffInDays() == 1;
|
||||
}
|
||||
|
||||
|
||||
|
||||
public function exchangeRefreshToken() {
|
||||
|
||||
}
|
||||
|
||||
|
||||
|
||||
|
Reference in New Issue
Block a user