auth.php 1.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105
  1. <?php namespace System;
  2. class Auth {
  3. /**
  4. * The current user of the application.
  5. *
  6. * @var object
  7. */
  8. public static $user;
  9. /**
  10. * The key used to store the user ID in the session.
  11. *
  12. * @var string
  13. */
  14. private static $key = 'laravel_user_id';
  15. /**
  16. * Determine if the current user of the application is authenticated.
  17. *
  18. * @return bool
  19. */
  20. public static function check()
  21. {
  22. return ( ! is_null(static::user()));
  23. }
  24. /**
  25. * Get the current user of the application.
  26. *
  27. * The user will be loaded using the user ID stored in the session.
  28. *
  29. * @return object
  30. */
  31. public static function user()
  32. {
  33. if (Config::get('session.driver') == '')
  34. {
  35. throw new \Exception("You must specify a session driver before using the Auth class.");
  36. }
  37. $model = static::model();
  38. if (is_null(static::$user) and Session::has(static::$key))
  39. {
  40. static::$user = $model::find(Session::get(static::$key));
  41. }
  42. return static::$user;
  43. }
  44. /**
  45. * Attempt to login a user.
  46. *
  47. * If the user credentials are valid. The user ID will be stored in the session
  48. * and will be considered "logged in" on subsequent requests to the application.
  49. *
  50. * @param string $username
  51. * @param string $password
  52. */
  53. public static function login($username, $password)
  54. {
  55. $model = static::model();
  56. $user = $model::where(Config::get('auth.username'), '=', $username)->first();
  57. if ( ! is_null($user))
  58. {
  59. if ($user->password === Hash::make($password, $user->salt)->value)
  60. {
  61. static::$user = $user;
  62. Session::put(static::$key, $user->id);
  63. return true;
  64. }
  65. }
  66. return false;
  67. }
  68. /**
  69. * Logout the user of the application.
  70. *
  71. * @return void
  72. */
  73. public static function logout()
  74. {
  75. Session::forget(static::$key);
  76. static::$user = null;
  77. }
  78. /**
  79. * Get the authentication model.
  80. *
  81. * @return string
  82. */
  83. private static function model()
  84. {
  85. return '\\'.Config::get('auth.model');
  86. }
  87. }