RequestGuard.php 2.1KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788
  1. <?php
  2. namespace Illuminate\Auth;
  3. use Illuminate\Http\Request;
  4. use Illuminate\Contracts\Auth\Guard;
  5. use Illuminate\Support\Traits\Macroable;
  6. use Illuminate\Contracts\Auth\UserProvider;
  7. class RequestGuard implements Guard
  8. {
  9. use GuardHelpers, Macroable;
  10. /**
  11. * The guard callback.
  12. *
  13. * @var callable
  14. */
  15. protected $callback;
  16. /**
  17. * The request instance.
  18. *
  19. * @var \Illuminate\Http\Request
  20. */
  21. protected $request;
  22. /**
  23. * Create a new authentication guard.
  24. *
  25. * @param callable $callback
  26. * @param \Illuminate\Http\Request $request
  27. * @param \Illuminate\Contracts\Auth\UserProvider|null $provider
  28. * @return void
  29. */
  30. public function __construct(callable $callback, Request $request, UserProvider $provider = null)
  31. {
  32. $this->request = $request;
  33. $this->callback = $callback;
  34. $this->provider = $provider;
  35. }
  36. /**
  37. * Get the currently authenticated user.
  38. *
  39. * @return \Illuminate\Contracts\Auth\Authenticatable|null
  40. */
  41. public function user()
  42. {
  43. // If we've already retrieved the user for the current request we can just
  44. // return it back immediately. We do not want to fetch the user data on
  45. // every call to this method because that would be tremendously slow.
  46. if (! is_null($this->user)) {
  47. return $this->user;
  48. }
  49. return $this->user = call_user_func(
  50. $this->callback, $this->request, $this->getProvider()
  51. );
  52. }
  53. /**
  54. * Validate a user's credentials.
  55. *
  56. * @param array $credentials
  57. * @return bool
  58. */
  59. public function validate(array $credentials = [])
  60. {
  61. return ! is_null((new static(
  62. $this->callback, $credentials['request'], $this->getProvider()
  63. ))->user());
  64. }
  65. /**
  66. * Set the current request instance.
  67. *
  68. * @param \Illuminate\Http\Request $request
  69. * @return $this
  70. */
  71. public function setRequest(Request $request)
  72. {
  73. $this->request = $request;
  74. return $this;
  75. }
  76. }