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

75 lines
1.9KB

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