dbms/app/Services/Auth/AuthService.php
2025-05-09 18:46:54 +09:00

116 lines
2.8 KiB
PHP

<?php
namespace App\Services\Auth;
use App\Entities\UserEntity;
use App\Services\CommonService;
use CodeIgniter\HTTP\IncomingRequest;
use CodeIgniter\Session\Session;
// 참고:https://github.com/SyntaxPhoenix/iloclient
abstract class AuthService extends CommonService
{
private ?Session $_session = null;
public function __construct(?IncomingRequest $request = null)
{
parent::__construct($request);
}
public function getClassName(): string
{
return "Auth" . DIRECTORY_SEPARATOR;
}
//Index,FieldForm관련
final public function getSession(): Session
{
if (!$this->_session) {
$this->_session = \Config\Services::session();
}
return $this->_session;
}
private function getAuthInfo(string $key = ""): array|string
{
$authInfo = $this->getSession()->get(SESSION_NAMES['AUTH']);
if ($key) {
return $authInfo[$key] ?? "";
}
return $authInfo;
}
final public function getUIDByAuthInfo(): string
{
return $this->getAuthInfo('uid');
}
final public function getIDByAuthInfo(): string
{
return $this->getAuthInfo('id');
}
final public function getNameByAuthInfo(): string
{
return $this->getAuthInfo('name');
}
final public function getRoleByAuthInfo(): string
{
return $this->getAuthInfo('role');
}
final public function isLoggedIn(): bool
{
return $this->getSession()->has(SESSION_NAMES['ISLOGIN']);
}
final public function isAccessRole(array $roles): bool
{
$role = $this->getRoleByAuthInfo();
if ($role === "") {
return false;
}
// 교집합이 없으면 false
return !empty(array_intersect(explode(DEFAULTS['DELIMITER_ROLE'], $role), $roles));
}
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
}
public function login(UserEntity $entity): UserEntity
{
$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]);
return $entity;
}
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);
}
}