cfmgrv4 init...2

This commit is contained in:
최준흠 2024-10-08 06:38:39 +09:00
parent d18f24981c
commit 07ad2b075f
5 changed files with 52 additions and 40 deletions

View File

@ -83,6 +83,7 @@ class UserController extends FrontController
helper(['form']); helper(['form']);
$this->create_form_process(); $this->create_form_process();
$this->session->keepFlashdata(SESSION_NAMES['RETURN_URL']); $this->session->keepFlashdata(SESSION_NAMES['RETURN_URL']);
$this->google_url = getenv('socket.google.api.uri');
$this->forms = ['attributes' => ['method' => "post",], 'hiddens' => []]; $this->forms = ['attributes' => ['method' => "post",], 'hiddens' => []];
return view( return view(
$this->view_path . "login", $this->view_path . "login",
@ -120,12 +121,11 @@ class UserController extends FrontController
} }
public function google_login(): RedirectResponse|string public function google_login(): RedirectResponse|string
{ {
$this->init('login');
$this->init('login'); $this->init('login');
//Transaction Start //Transaction Start
$this->getModel()->transStart(); $this->getModel()->transStart();
try { try {
$auth = new GoogleAuth(); $auth = new GoogleAuth($this->request->getVar('code'));
$auth->setLogin($auth->checkUser()); $auth->setLogin($auth->checkUser());
$this->message = "로그인 성공"; $this->message = "로그인 성공";
$this->getModel()->transCommit(); $this->getModel()->transCommit();

View File

@ -2,37 +2,40 @@
namespace App\Libraries\MyAuth; namespace App\Libraries\MyAuth;
use \Google\Service\Oauth2; use Google\Service\Oauth2;
use App\Models\UserModel; use App\Models\UserModel;
use App\Models\SNSUserModel; use App\Models\SNSUserModel;
use App\Libraries\MySocket\GoogleSocket; use App\Libraries\MySocket\GoogleSocket;
use App\Entities\UserEntity; use App\Entities\UserEntity;
use CodeIgniter\Exceptions\PageNotFoundException;
class GoogleAuth extends MyAuth class GoogleAuth extends MyAuth
{ {
private $_mySocket = null; private ?GoogleSocket $_mySocket = null;
private $_site = "GOOGLE"; private string $_site = "GOOGLE";
private $_model = null; private ?SNSUserModel $_model = null;
public function __construct() private string $access_code = "";
public function __construct(string $access_code)
{ {
parent::__construct(); parent::__construct();
$this->access_code = $access_code;
} }
public function getMySocket(): GoogleSocket public function getMySocket(): GoogleSocket
{ {
if ($this->_mySocket === null) { if ($this->_mySocket === null) {
$this->_mySocket = new GoogleSocket(); $this->_mySocket = new GoogleSocket();
$this->_mySocket->setMyToken(); $this->_mySocket->setToken($this->access_code);
} }
return $this->_mySocket; return $this->_mySocket;
} }
public function getAuthButton() public function getAuthButton(): string
{ {
$button = ""; $button = "";
if (!$this->getMySocket()->getMyToken()) { if (!$this->getMySocket()->getToken()) {
$button = anchor( $button = anchor(
getenv("socket.google.api.url"), env("socket.google.api.url"),
ICONS['GOOGLE'], ICONS['GOOGLE'],
["target" => "_self"] ["target" => "_self"]
); );
@ -40,10 +43,10 @@ class GoogleAuth extends MyAuth
return $button; return $button;
} }
final protected function getModel(): SNSUSerModel final protected function getModel(): SNSUserModel
{ {
if ($this->_model === null) { if ($this->_model === null) {
$this->_model = new SNSUserModel(); $this->_model = model(SNSUserModel::class);
} }
return $this->_model; return $this->_model;
} }
@ -82,7 +85,7 @@ class GoogleAuth extends MyAuth
//Google 서비스 설정 //Google 서비스 설정
$service = new Oauth2($this->getMySocket()); $service = new Oauth2($this->getMySocket());
$authInfo = $service->userinfo->get(); $authInfo = $service->userinfo->get();
log_message("debug", var_export($authInfo, true)); log_message('debug', var_export($authInfo, true));
//기존 등록된 사용자가 있는지 검사 //기존 등록된 사용자가 있는지 검사
$this->getModel()->where(SNSUserModel::SITE, $this->_site); $this->getModel()->where(SNSUserModel::SITE, $this->_site);
$entity = $this->getModel()->getEntityByID($authInfo['id']); $entity = $this->getModel()->getEntityByID($authInfo['id']);
@ -102,17 +105,18 @@ class GoogleAuth extends MyAuth
if ( if (
$entity->status !== DEFAULTS['STATUS'] $entity->status !== DEFAULTS['STATUS']
) { ) {
throw new \Exception("{$this->_site}}의{$authInfo['email']}:{$authInfo['name']}님은 " . $entity->status . "입니다"); throw new PageNotFoundException("{$this->_site}}의{$authInfo['email']}:{$authInfo['name']}님은 " . $entity->status . "입니다");
} }
//local db 사용와의 연결 확인 //local db 사용와의 연결 확인
$userModel = new UserModel(); $userModel = model(UserModel::class);
$user_entity = $userModel->getEntityByID($entity->getID()); $user_entity = $userModel->getEntityByID($entity->getID());
if ($user_entity === null) { if ($user_entity === null) {
throw new \Exception("{$this->_site}{$authInfo['email']}:{$authInfo['name']}님은 아직 사용자 연결이 이루어지지 않았습니다. "); throw new PageNotFoundException("{$this->_site}{$authInfo['email']}:{$authInfo['name']}님은 아직 사용자 연결이 이루어지지 않았습니다. ");
} }
return $user_entity; return $user_entity;
} catch (\Exception $e) { } catch (\Exception $e) {
throw new \Exception("관리자에게 문의하시기 바랍니다.<BR>{$e->getMessage()}"); log_message('error', $e->getMessage());
throw new PageNotFoundException("관리자에게 문의하시기 바랍니다.<BR>{$e->getMessage()}");
} }
} }
} }

View File

@ -3,38 +3,45 @@
namespace App\Libraries\MySocket; namespace App\Libraries\MySocket;
use Google\Client; use Google\Client;
use CodeIgniter\Config\Services;
use CodeIgniter\Exceptions\ConfigException;
class GoogleSocket extends Client class GoogleSocket extends Client
{ {
private $_session = null; private $session;
private $_access_code = "";
public function __construct(string $access_code) public function __construct()
{ {
$this->_access_code = $access_code;
parent::__construct(); parent::__construct();
$this->_session = \Config\Services::session(); $this->session = Services::session();
$this->setClientId(getenv("socket.google.client.id")); $this->setClientId(env('socket.google.client.id'));
$this->setClientSecret(getenv("socket.google.client.key")); $this->setClientSecret(env('socket.google.client.key'));
$this->setRedirectUri(base_url() . getenv("socket.google.client.callback_url")); $this->setRedirectUri(base_url(env('socket.google.client.callback_url')));
$this->addScope('email'); $this->addScope('email');
$this->addScope('profile'); $this->addScope('profile');
} }
public function setMyToken(): void public function setToken(string $access_code): void
{ {
//2.토큰정보 가져오기 // 토큰 정보 가져오기
$tokenInfo = $this->fetchAccessTokenWithAuthCode($this->_access_code); $tokenInfo = $this->fetchAccessTokenWithAuthCode($access_code);
if (isset($tokenInfo['error'])) { if (isset($tokenInfo['error'])) {
throw new \Exception($tokenInfo['error']); throw new ConfigException($tokenInfo['error']);
} }
$token = $tokenInfo[getenv("socket.google.client.token_name")];
//3. Google Service에 접근하기위해 Access Token을 설정 $tokenName = env('socket.google.client.token_name');
$token = $tokenInfo[$tokenName];
// Google Service에 접근하기 위해 Access Token 설정
$this->setAccessToken($token); $this->setAccessToken($token);
//4. Google에 로그인이 했으므로 세션에 Token값 설정
$this->_session->set(getenv("socket.google.client.token_name"), $token); // 세션에 Token 값 설정
$this->session->set($tokenName, $token);
} }
public function getMyToken(): ?string
public function getToken(): ?string
{ {
return $this->_session->get(getenv("socket.google.client.token_name")); return $this->session->get(env('socket.google.client.token_name'));
} }
} }

View File

@ -14,7 +14,7 @@
</div> </div>
<div class="d-flex justify-content-between align-items-center"> <div class="d-flex justify-content-between align-items-center">
<button type="submit" class="btn btn-primary">로그인</button> <button type="submit" class="btn btn-primary">로그인</button>
<?= anchor(URLS['GOOGLE_LOGIN'], ICONS['GOOGLE'] . 'Google 로그인', ["class" => "btn btn-danger"]) ?> <?= anchor($viewDatas['google_url'], ICONS['GOOGLE'] . 'Google 로그인', ["class" => "btn btn-danger"]) ?>
<button type="button" class="btn btn-outline-primary">회원가입</button> <button type="button" class="btn btn-outline-primary">회원가입</button>
</div> </div>
<?= form_close(); ?> <?= form_close(); ?>

View File

@ -13,7 +13,7 @@
"php": "^8.3", "php": "^8.3",
"cloudflare/sdk": "^1.3", "cloudflare/sdk": "^1.3",
"codeigniter4/framework": "^4.5", "codeigniter4/framework": "^4.5",
"google/apiclient": "^2.0", "google/apiclient": "^2.15.0",
"guzzlehttp/guzzle": "^7.9", "guzzlehttp/guzzle": "^7.9",
"phpoffice/phpspreadsheet": "^1.27", "phpoffice/phpspreadsheet": "^1.27",
"symfony/css-selector": "^7.1", "symfony/css-selector": "^7.1",
@ -42,9 +42,10 @@
"config": { "config": {
"optimize-autoloader": true, "optimize-autoloader": true,
"preferred-install": "dist", "preferred-install": "dist",
"sort-packages": true "sort-packages": true,
"process-timeout": 600
}, },
"scripts": { "scripts": {
"test": "phpunit" "test": "phpunit"
} }
} }