cfmgrv4/app/Libraries/MySocket/GoogleSocketAPI.php
2024-10-10 15:21:27 +09:00

89 lines
2.4 KiB
PHP

<?php
namespace App\Libraries\MySocket;
use CodeIgniter\Config\Services;
use CodeIgniter\Exceptions\ConfigException;
use Google\Client;
use Google\Service\Oauth2;
class GoogleSocketAPI extends Client
{
private $session;
private string $_access_token = "";
private string $_token_name = "access_token";
public function __construct()
{
parent::__construct();
$this->setClientId(env('socket.google.client.id'));
$this->setClientSecret(env('socket.google.client.key'));
$this->setRedirectUri(base_url(env('socket.google.client.callback_url')));
$this->addScope(Oauth2::USERINFO_EMAIL);
$this->addScope(Oauth2::USERINFO_PROFILE);
// $this->setPrompt('select_account consent');
// $this->setAccessType('offline');
// SSL 검증 비활성화
$this->setHttpClient(new \GuzzleHttp\Client(['verify' => false]));
// 사용자 정의 CA 번들 사용
// $this->setHttpClient(new \GuzzleHttp\Client(['verify' => '/path/to/cacert.pem']));
$this->session = Services::session();
}
public function setToken(string $access_code): void
{
// 토큰 정보 가져오기
$tokenInfo = $this->fetchAccessTokenWithAuthCode($access_code);
if (isset($tokenInfo['error'])) {
throw new ConfigException($tokenInfo['error']);
}
// dd($tokenInfo);
$this->_access_token = $tokenInfo[$this->_token_name];
// Google Service에 접근하기 위해 Access Token 설정
$this->setAccessToken([
'access_token' => $this->_access_token,
'expires_in' => 3600,
'created' => time(),
]);
// 세션에 Token 값 설정
$this->session->set($this->_token_name, $this->_access_token);
}
public function getToken(): string
{
return $this->session->get($this->_token_name);
}
public function isAccessTokenValid(): bool
{
// 액세스 토큰이 없으면 유효하지 않음
if (empty($this->getAccessToken())) {
return false;
}
// 토큰의 만료 시간 확인
$expirationTime = $this->getTokenExpirationTime();
if ($expirationTime === null) {
return false;
}
// 현재 시간과 비교하여 유효성 확인
return $expirationTime > time();
}
private function getTokenExpirationTime(): ?int
{
// 토큰 정보 디코딩
$tokenParts = explode('.', $this->getToken());
if (count($tokenParts) !== 3) {
return null;
}
$payload = json_decode(base64_decode($tokenParts[1]), true);
if (!isset($payload['exp'])) {
return null;
}
return $payload['exp'];
}
}