|
- <?php
-
- namespace App\Models\Ex;
-
- use App\Codes\UserRole;
- use App\Models\ColumnName;
- use App\Models\Contract;
- use App\Models\User;
- use Illuminate\Database\Eloquent\Model;
- use Illuminate\Support\Facades\Auth;
- use Illuminate\Support\Facades\Session;
- use LogicException;
-
- class LoginUser
- {
- private const SESSION_KEY_CURERNT_CONTRACT_ID = self::class . "/SESSION_KEY_CURERNT_CONTRACT_ID";
-
-
- public function __construct(
- private User $user,
- private Contract $contract
- ) {
- }
-
- public function user(): ?User
- {
- return Auth::user();
- }
-
- public function checkAuthorization(array|Model $target): bool
- {
- if (app()->runningInConsole()) {
- return true;
- }
-
- if (!Auth::check()) {
- return false;
- }
-
- if ($this->user()->role === UserRole::SUPER_ADMIN) {
- return true;
- }
-
- $contractId = data_get($target, ColumnName::CONTRACT_ID);
- if ($contractId === null) {
- throw new LogicException("契約ID不正");
- }
-
- return $contractId === $this->user()->contract_id;
- }
-
- public function setCurrentContractId(?string $contractId)
- {
- $user = $this->user();
- if ($user && Auth::user()->role !== UserRole::SUPER_ADMIN && $contractId !== null) {
- throw new LogicException("スーパー管理者以外の成り代わりを検知");
- }
- Session::put(self::SESSION_KEY_CURERNT_CONTRACT_ID, $contractId);
- }
-
- public function getCurrentContractId(): ?string
- {
- $user = $this->user();
- if ($user && $user->role === UserRole::SUPER_ADMIN) {
- return Session::get(self::SESSION_KEY_CURERNT_CONTRACT_ID);
- }
- return data_get($user, User::COL_NAME_CONTRACT_ID);
- }
-
- public function getCurrentContract(): ?Contract
- {
- return Contract::find($this->getCurrentContractId());
- }
- }
|