|
- <?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 LogicException;
-
- class LoginUser
- {
- private const SESSION_KEY_SADMIN_CONTRACT_ID = 'SESSION_KEY_SADMIN_CONTRACT_ID';
-
-
- public function __construct(
- private User $user,
- private Contract $contract
- ) {
- }
-
- public function user(): ?User
- {
- return Auth::user();
- }
-
- public function contract(): ?Contract
- {
-
- if (!Auth::check()) {
- return null;
- }
-
- if ($this->contract->isNotSavedModel()) {
- $this->contract = $this->user()->contract;
- }
-
- return $this->contract;
- }
-
- 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 getContractId(): ?string
- {
- if ($this->user()->role === UserRole::SUPER_ADMIN) {
-
- $session = request()->session();
-
- if ($session->exists(self::SESSION_KEY_SADMIN_CONTRACT_ID)) {
- return $session->get(self::SESSION_KEY_SADMIN_CONTRACT_ID);
- }
- return $this->contract()->id;
- }
-
- return data_get($this->contract(), Contract::COL_NAME_ID);
- }
- }
|