領収証発行サービス
You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

77 lines
1.9KB

  1. <?php
  2. namespace App\Models\Ex;
  3. use App\Codes\UserRole;
  4. use App\Features\InstanceAble;
  5. use App\Models\ColumnName;
  6. use App\Models\Contract;
  7. use App\Models\User;
  8. use Illuminate\Database\Eloquent\Model;
  9. use Illuminate\Support\Facades\Auth;
  10. use Illuminate\Support\Facades\Session;
  11. use LogicException;
  12. class LoginUser
  13. {
  14. private const SESSION_KEY_CURERNT_CONTRACT_ID = self::class . "/SESSION_KEY_CURERNT_CONTRACT_ID";
  15. use InstanceAble;
  16. public function __construct(
  17. private User $user,
  18. private Contract $contract
  19. ) {
  20. }
  21. public function user(): ?User
  22. {
  23. return Auth::user();
  24. }
  25. public function checkAuthorization(array|Model $target): bool
  26. {
  27. if (app()->runningInConsole()) {
  28. return true;
  29. }
  30. if (!Auth::check()) {
  31. return false;
  32. }
  33. if ($this->user()->role === UserRole::SUPER_ADMIN) {
  34. return true;
  35. }
  36. $contractId = data_get($target, ColumnName::CONTRACT_ID);
  37. if ($contractId === null) {
  38. throw new LogicException("契約ID不正");
  39. }
  40. return $contractId === $this->user()->contract_id;
  41. }
  42. public function setCurrentContractId(?string $contractId)
  43. {
  44. $user = $this->user();
  45. if ($user && Auth::user()->role !== UserRole::SUPER_ADMIN && $contractId !== null) {
  46. throw new LogicException("スーパー管理者以外の成り代わりを検知");
  47. }
  48. Session::put(self::SESSION_KEY_CURERNT_CONTRACT_ID, $contractId);
  49. }
  50. public function getCurrentContractId(): ?string
  51. {
  52. $user = $this->user();
  53. if ($user && $user->role === UserRole::SUPER_ADMIN) {
  54. return Session::get(self::SESSION_KEY_CURERNT_CONTRACT_ID);
  55. }
  56. return data_get($user, User::COL_NAME_CONTRACT_ID);
  57. }
  58. public function getCurrentContract(): ?Contract
  59. {
  60. return Contract::find($this->getCurrentContractId());
  61. }
  62. }