auth.php 2.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115
  1. <?php namespace Laravel\Security;
  2. use Laravel\Config;
  3. use Laravel\Session\Driver;
  4. class Auth {
  5. /**
  6. * The current user of the application.
  7. *
  8. * @var object
  9. */
  10. protected $user;
  11. /**
  12. * The session driver instance.
  13. *
  14. * @var Session\Driver
  15. */
  16. protected $session;
  17. /**
  18. * The key used when storing the user ID in the session.
  19. *
  20. * @var string
  21. */
  22. const user_key = 'laravel_user_id';
  23. /**
  24. * Create a new authenticator instance.
  25. *
  26. * @param Session\Driver $session
  27. * @return void
  28. */
  29. public function __construct(Driver $session)
  30. {
  31. $this->session = $session;
  32. }
  33. /**
  34. * Determine if the current user of the application is authenticated.
  35. *
  36. * @return bool
  37. */
  38. public function check()
  39. {
  40. return ! is_null($this->user());
  41. }
  42. /**
  43. * Get the current user of the application.
  44. *
  45. * If the current user is not authenticated, NULL will be returned.
  46. *
  47. * @return object
  48. */
  49. public function user()
  50. {
  51. if ( ! is_null($this->user)) return $this->user;
  52. return $this->user = call_user_func(Config::get('auth.user'), $this->session->get(Auth::user_key));
  53. }
  54. /**
  55. * Attempt to log a user into the application.
  56. *
  57. * If the given credentials are valid, the user will be considered logged into the
  58. * application and their user ID will be stored in the session data.
  59. *
  60. * @param string $username
  61. * @param string $password
  62. * @return bool
  63. */
  64. public function attempt($username, $password = null)
  65. {
  66. if ( ! is_null($user = call_user_func(Config::get('auth.attempt'), $username, $password)))
  67. {
  68. $this->remember($user);
  69. return true;
  70. }
  71. return false;
  72. }
  73. /**
  74. * Log a user into the application.
  75. *
  76. * The user ID will be stored in the session so it is available on subsequent requests.
  77. *
  78. * @param object $user
  79. * @return void
  80. */
  81. public function remember($user)
  82. {
  83. $this->user = $user;
  84. $this->session->put(Auth::user_key, $user->id);
  85. }
  86. /**
  87. * Log the current user out of the application.
  88. *
  89. * @return void
  90. */
  91. public function logout()
  92. {
  93. call_user_func(Config::get('auth.logout'), $this->user()->id);
  94. $this->user = null;
  95. $this->session->forget(Auth::user_key);
  96. }
  97. }