AuthenticateSession.php 2.3KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697
  1. <?php
  2. namespace Illuminate\Session\Middleware;
  3. use Closure;
  4. use Illuminate\Auth\AuthenticationException;
  5. use Illuminate\Contracts\Auth\Factory as AuthFactory;
  6. class AuthenticateSession
  7. {
  8. /**
  9. * The authentication factory implementation.
  10. *
  11. * @var \Illuminate\Contracts\Auth\Factory
  12. */
  13. protected $auth;
  14. /**
  15. * Create a new middleware instance.
  16. *
  17. * @param \Illuminate\Contracts\Auth\Factory $auth
  18. * @return void
  19. */
  20. public function __construct(AuthFactory $auth)
  21. {
  22. $this->auth = $auth;
  23. }
  24. /**
  25. * Handle an incoming request.
  26. *
  27. * @param \Illuminate\Http\Request $request
  28. * @param \Closure $next
  29. * @return mixed
  30. */
  31. public function handle($request, Closure $next)
  32. {
  33. if (! $request->user() || ! $request->session()) {
  34. return $next($request);
  35. }
  36. if ($this->auth->viaRemember()) {
  37. $passwordHash = explode('|', $request->cookies->get($this->auth->getRecallerName()))[2];
  38. if ($passwordHash != $request->user()->getAuthPassword()) {
  39. $this->logout($request);
  40. }
  41. }
  42. if (! $request->session()->has('password_hash')) {
  43. $this->storePasswordHashInSession($request);
  44. }
  45. if ($request->session()->get('password_hash') !== $request->user()->getAuthPassword()) {
  46. $this->logout($request);
  47. }
  48. return tap($next($request), function () use ($request) {
  49. $this->storePasswordHashInSession($request);
  50. });
  51. }
  52. /**
  53. * Store the user's current password hash in the session.
  54. *
  55. * @param \Illuminate\Http\Request $request
  56. * @return void
  57. */
  58. protected function storePasswordHashInSession($request)
  59. {
  60. if (! $request->user()) {
  61. return;
  62. }
  63. $request->session()->put([
  64. 'password_hash' => $request->user()->getAuthPassword(),
  65. ]);
  66. }
  67. /**
  68. * Log the user out of the application.
  69. *
  70. * @param \Illuminate\Http\Request $request
  71. * @return void
  72. *
  73. * @throws \Illuminate\Auth\AuthenticationException
  74. */
  75. protected function logout($request)
  76. {
  77. $this->auth->logout();
  78. $request->session()->flush();
  79. throw new AuthenticationException;
  80. }
  81. }