auth.php 1.67 KB
Newer Older
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31
<?php namespace System;

class Auth {

	/**
	 * The current user of the application.
	 *
	 * @var object
	 */
	public static $user;

	/**
	 * The key used to store the user ID in the session.
	 *
	 * @var string
	 */
	private static $key = 'laravel_user_id';

	/**
	 * Determine if the current user of the application is authenticated.
	 *
	 * @return bool
	 */
	public static function check()
	{
		return ( ! is_null(static::user()));
	}

	/**
	 * Get the current user of the application.
	 *
32 33
	 * The user will be loaded using the user ID stored in the session.
	 *
34 35 36 37 38 39 40 41 42 43 44
	 * @return object
	 */
	public static function user()
	{
		if (Config::get('session.driver') == '')
		{
			throw new \Exception("You must specify a session driver before using the Auth class.");
		}

		if (is_null(static::$user) and Session::has(static::$key))
		{
45
			static::$user = call_user_func(Config::get('auth.by_id'), Session::get(static::$key));
46 47 48 49 50 51 52 53
		}

		return static::$user;
	}

	/**
	 * Attempt to login a user.
	 *
54 55 56
	 * If the user credentials are valid. The user ID will be stored in the session
	 * and will be considered "logged in" on subsequent requests to the application.
	 *
57 58 59 60 61
	 * @param  string  $username
	 * @param  string  $password
	 */
	public static function login($username, $password)
	{
62
		if ( ! is_null($user = call_user_func(Config::get('auth.by_username'), $username)))
63
		{
64
			if (Hash::check($password, $user->password))
65 66 67 68 69 70 71 72 73 74 75 76 77
			{
				static::$user = $user;

				Session::put(static::$key, $user->id);

				return true;
			}
		}

		return false;
	}

	/**
78
	 * Logout the user of the application.
79 80 81 82 83 84
	 *
	 * @return void
	 */
	public static function logout()
	{
		Session::forget(static::$key);
Taylor Otwell committed
85

86 87 88 89
		static::$user = null;
	}

}