領収証発行サービス
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.

80 lines
1.7KB

  1. <?php
  2. namespace App\Models\Ex;
  3. use App\Codes\UserRole;
  4. use App\Models\ColumnName;
  5. use App\Models\Contract;
  6. use App\Models\User;
  7. use Illuminate\Database\Eloquent\Model;
  8. use Illuminate\Support\Facades\Auth;
  9. use LogicException;
  10. class LoginUser
  11. {
  12. private const SESSION_KEY_SADMIN_CONTRACT_ID = 'SESSION_KEY_SADMIN_CONTRACT_ID';
  13. public function __construct(
  14. private User $user,
  15. private Contract $contract
  16. ) {
  17. }
  18. public function user(): ?User
  19. {
  20. return Auth::user();
  21. }
  22. public function contract(): ?Contract
  23. {
  24. if (!Auth::check()) {
  25. return null;
  26. }
  27. if ($this->contract->isNotSavedModel()) {
  28. $this->contract = $this->user()->contract;
  29. }
  30. return $this->contract;
  31. }
  32. public function checkAuthorization(array|Model $target): bool
  33. {
  34. if (app()->runningInConsole()) {
  35. return true;
  36. }
  37. if (!Auth::check()) {
  38. return false;
  39. }
  40. if ($this->user()->role === UserRole::SUPER_ADMIN) {
  41. return true;
  42. }
  43. $contractId = data_get($target, ColumnName::CONTRACT_ID);
  44. if ($contractId === null) {
  45. throw new LogicException("契約ID不正");
  46. }
  47. return $contractId === $this->user()->contract_id;
  48. }
  49. public function getContractId(): ?string
  50. {
  51. if ($this->user()->role === UserRole::SUPER_ADMIN) {
  52. $session = request()->session();
  53. if ($session->exists(self::SESSION_KEY_SADMIN_CONTRACT_ID)) {
  54. return $session->get(self::SESSION_KEY_SADMIN_CONTRACT_ID);
  55. }
  56. return $this->contract()->id;
  57. }
  58. return data_get($this->contract(), Contract::COL_NAME_ID);
  59. }
  60. }