auth.php 2.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108
  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. * Create a new authenticator instance.
  19. *
  20. * @param Session\Driver $session
  21. * @return void
  22. */
  23. public function __construct(Driver $session)
  24. {
  25. $this->session = $session;
  26. }
  27. /**
  28. * Determine if the current user of the application is authenticated.
  29. *
  30. * @return bool
  31. */
  32. public function check()
  33. {
  34. return ! is_null($this->user());
  35. }
  36. /**
  37. * Get the current user of the application.
  38. *
  39. * If the current user is not authenticated, NULL will be returned.
  40. *
  41. * @return object
  42. */
  43. public function user()
  44. {
  45. if ( ! is_null($this->user)) return $this->user;
  46. return $this->user = call_user_func(Config::get('auth.user'), $this->session->get('laravel_user_id'));
  47. }
  48. /**
  49. * Attempt to log a user into the application.
  50. *
  51. * If the given credentials are valid, the user will be considered logged into the
  52. * application and their user ID will be stored in the session data.
  53. *
  54. * @param string $username
  55. * @param string $password
  56. * @return bool
  57. */
  58. public function attempt($username, $password = null)
  59. {
  60. if ( ! is_null($user = call_user_func(Config::get('auth.attempt'), $username, $password)))
  61. {
  62. $this->remember($user);
  63. return true;
  64. }
  65. return false;
  66. }
  67. /**
  68. * Log a user into the application.
  69. *
  70. * The user ID will be stored in the session so it is available on subsequent requests.
  71. *
  72. * @param object $user
  73. * @return void
  74. */
  75. public function remember($user)
  76. {
  77. $this->user = $user;
  78. $this->session->put('laravel_user_id', $user->id);
  79. }
  80. /**
  81. * Log the current user out of the application.
  82. *
  83. * @return void
  84. */
  85. public function logout()
  86. {
  87. call_user_func(Config::get('auth.logout'), $this->user()->id);
  88. $this->user = null;
  89. $this->session->forget('laravel_user_id');
  90. }
  91. }