cfmgrv4/app/Services/Auth/AuthService.php
2024-11-01 12:38:43 +09:00

107 lines
2.5 KiB
PHP

<?php
namespace App\Services\Auth;
use App\Entities\UserEntity;
use App\Models\UserModel;
use App\Services\CommonService;
use CodeIgniter\Session\Session;
// 참고:https://github.com/SyntaxPhoenix/iloclient
abstract class AuthService extends CommonService
{
private ?Session $_session = null;
public function __construct() {}
final public function getSession(): Session
{
if ($this->_session == null) {
$this->_session = \Config\Services::session();
}
return $this->_session;
}
final protected function getModel(): UserModel
{
if ($this->_model === null) {
$this->_model = new UserModel();
}
return $this->_model;
}
final public function getAuthInfo(string $key = ""): array|string
{
if ($key) {
return isset($this->getSession()->get(SESSION_NAMES['AUTH'])[$key]) ? $this->getSession()->get(SESSION_NAMES['AUTH'])[$key] : "";
}
return $this->getSession()->get(SESSION_NAMES['AUTH']);
}
final public function isLoggedIn(): bool
{
return $this->getSession()->has(SESSION_NAMES['ISLOGIN']);
}
final public function isAccessRole(array $roles): bool
{
if ($this->getAuthInfo('role') === "") {
return false;
}
$myRoles = explode(DEFAULTS['DELIMITER_ROLE'], $this->getAuthInfo('role'));
// 교집합이 없으면 false
if (empty(array_intersect($myRoles, $roles))) {
return false;
}
return true;
}
final public function pushCurrentUrl(string $url): void
{
$this->getSession()->set('url_stack', $url);
}
final public function popPreviousUrl(): string
{
$url = $this->getSession()->get('url_stack') ?? "";
if (!empty($url)) {
$this->pushCurrentUrl("");
return $url;
}
return '/'; // 기본 URL
}
final public function login(UserEntity $entity): void
{
$this->getSession()->set(SESSION_NAMES['ISLOGIN'], true);
$this->getSession()->set(SESSION_NAMES['AUTH'], [
'uid' => $entity->getPK(),
'id' => $entity->getID(),
'name' => $entity->getTitle(),
'role' => $entity->role
]);
}
final public function logout(): void
{
// 세션 데이터 삭제
$this->getSession()->remove(SESSION_NAMES['ISLOGIN']);
$this->getSession()->remove(SESSION_NAMES['AUTH']);
// 모든 세션 데이터 삭제
$this->getSession()->destroy();
// 세션 쿠키 삭제
if (ini_get("session.use_cookies")) {
$params = session_get_cookie_params();
setcookie(
session_name(),
'',
time() - 42000,
$params["path"],
$params["domain"],
$params["secure"],
$params["httponly"]
);
}
// 세션 재생성
session_start();
$this->getSession()->regenerate(true);
}
}