最近在和同學參與一個創業項目,用到了laravel,仔細研究了一下,發現laravel封裝了很多開箱即用的方法,通過traits實現引入后,就可以使用這些方法,今天我們來分析一下<code>AuthenticatesAndRegistersUsers ThrottlesLogins</code>,這兩個類,第一個是內部封裝了<code>getLogin postLogin getRegister postRegister getLogout</code>的一個類,通過使用<code>traits AuthenticatesAndRegistersUsers</code>就可以實現把<code>AuthenticatesAndRegistersUsers</code>引入到<code>authController<code>中,具體實現稍后會有代碼來說明。<code>ThrottlesLogins</code>是內部封裝了一個限制登錄次數的一個類。下面來通過代碼說明。<p>
明白這些內容,需要明白laravel的多用戶認證系統,稍后有時間我會寫一篇,把自己項目分析一下。<p>
//先展示一個登錄驗證的路由,兩種方法
//第一種是通過Route::group實現路由組
Route::group(['middleware=>['web']],function(){
Route::resource('/article','ArticleController');
//登錄
Route::get('auth/login','Auth\AuthController@getLogin');
Route::post('auth/login','Auth\AuthController@postLogin');
//認證
Route::get('auth/register','Auth\AuthController@getRegister');
Route::post('auth/register','Auth\AuthController@postRegister');
//登出
Route::get('auth/logout','Auth\AuthController@getLogout');
})
//第二種是通過Route::group實現路由組
Route::controllers([
'auth'=>'Auth\AuthController';
''password'=>'Auth\PasswordController'
])
(1)上面這些在laravel 5.2里面都是要包含在web這個中間件的<code>['middleware' => ['web']</code> </li>
(2)login 和 register是在“保護”內的,而logout則不是,具體可以看AuthController.php,主要是因為logout比較隨意,也不能用session來限制其訪問</li>
下面是Authcontroller的代碼
namespace App\Http\Controllers\Auth;
use App\Models\User;
use App\Http\Controllers\Controller;
use Illuminate\Foundation\Auth\ThrottlesLogins;
use Illuminate\Foundation\Auth\AuthenticatesUsers;
class AuthController extends Controller{
use AuthenticatesUsers, ThrottlesLogins;//通過traits引入
/** * Create a new authentication controller instance. */
public function __construct(){
$this->middleware('guest', ['except' => 'getLogout']);//排除了logout,不在中間件保護范圍內
}
protected function validator(array $data)//這里自帶了一個驗證邏輯,request的驗證有2種方法,一種是寫request文件,一種就是用validator
{
return Validator::make($data, [
'name' => 'required|max:255',
'email' => 'required|email|max:255|unique:users',
'password' => 'required|min:6|confirmed',
]);
}
protected function create(array $data)//這個就是create,在函數體里面就是用了model的create方法,直接在數據庫生成數據
{
return User::create([
'name' => $data['name'],
'email' => $data['email'],
'password' => bcrypt($data['password']),
]);
}
}
在<code>AuthenticatesAndRegistersUsers</code>看到了<code>use AuthenticatesUsers, RegistersUsers </code>這里是重點,使用了兩個類,一個是驗證用戶,一個是注冊用戶。<p>
下面是AuthenticatesUsers
namespace Illuminate\Foundation\Auth;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Auth;
use Illuminate\Support\Facades\Lang;
trait AuthenticatesUsers
{
use RedirectsUsers;
/**
* Show the application login form.
*
* @return \Illuminate\Http\Response
*/
public function getLogin()
{
return $this->showLoginForm();//調用本類的showLoginForm方法
}
/**
* Show the application login form.
*
* @return \Illuminate\Http\Response
*/
public function showLoginForm()//供getLogin調用
{
$view = property_exists($this, 'loginView')//判斷本類是否存在loginView屬性,存在就調用,否則調用auth.authenticate
? $this->loginView : 'auth.authenticate';
if (view()->exists($view)) {//如果存在就調用
return view($view);//調用view這個視圖模板
}
return view('auth.login');//如果不存在就調用auth文件夾下的login模板
}
/**
* Handle a login request to the application.
*
* @param \Illuminate\Http\Request $request
* @return \Illuminate\Http\Response
*/
public function postLogin(Request $request)//這里有了request請求
{
return $this->login($request);//調用login,request是參數
}
/**
* Handle a login request to the application.
*
* @param \Illuminate\Http\Request $request
* @return \Illuminate\Http\Response
*/
public function login(Request $request)//IOC注入request
{
$this->validateLogin($request);//通過本類validateLogin驗證request
// If the class is using the ThrottlesLogins trait, we can automatically throttle
// the login attempts for this application. We'll key this by the username and
// the IP address of the client making these requests into this application.
$throttles = $this->isUsingThrottlesLoginsTrait();//判斷是否限制登錄次數
if ($throttles && $lockedOut = $this->hasTooManyLoginAttempts($request)) {//hasTooManyLoginAttempts來判斷登錄次數,系統默認五次。
$this->fireLockoutEvent($request);//觸發鎖定登錄,一分鐘。
return $this->sendLockoutResponse($request);
}
$credentials = $this->getCredentials($request);//調用getCredentials驗證
if (Auth::guard($this->getGuard())->attempt($credentials, $request->has('remember'))) {//使用auth::guard來訪問指定的guard實例,
return $this->handleUserWasAuthenticated($request, $throttles);
}
// If the login attempt was unsuccessful we will increment the number of attempts
// to login and redirect the user back to the login form. Of course, when this
// user surpasses their maximum number of attempts they will get locked out.
if ($throttles && ! $lockedOut) {
$this->incrementLoginAttempts($request);
}
return $this->sendFailedLoginResponse($request);
}
/**
* Validate the user login request.
*
* @param \Illuminate\Http\Request $request
* @return void
*/
protected function validateLogin(Request $request)//驗證request
{
$this->validate($request, [
$this->loginUsername() => 'required', 'password' => 'required',
]);
}
/**
* Send the response after the user was authenticated.
*
* @param \Illuminate\Http\Request $request
* @param bool $throttles
* @return \Illuminate\Http\Response
*/
protected function handleUserWasAuthenticated(Request $request, $throttles)
{
if ($throttles) {
$this->clearLoginAttempts($request);
}
if (method_exists($this, 'authenticated')) {
return $this->authenticated($request, Auth::guard($this->getGuard())->user());
}
return redirect()->intended($this->redirectPath());
}
/**
* Get the failed login response instance.
*
* @param \Illuminate\Http\Request $request
* @return \Illuminate\Http\Response
*/
protected function sendFailedLoginResponse(Request $request)
{
return redirect()->back()
->withInput($request->only($this->loginUsername(), 'remember'))
->withErrors([
$this->loginUsername() => $this->getFailedLoginMessage(),
]);
}
/**
* Get the failed login message.
*
* @return string
*/
protected function getFailedLoginMessage()
{
return Lang::has('auth.failed')
? Lang::get('auth.failed')
: 'These credentials do not match our records.';
}
/**
* Get the needed authorization credentials from the request.
*
* @param \Illuminate\Http\Request $request
* @return array
*/
protected function getCredentials(Request $request)//單獨獲取部分輸入數據
{
return $request->only($this->loginUsername(), 'password');//單獨獲取部分輸入數據
}
/**
* Log the user out of the application.
*
* @return \Illuminate\Http\Response
*/
public function getLogout()
{
return $this->logout();
}
/**
* Log the user out of the application.
*
* @return \Illuminate\Http\Response
*/
public function logout()
{
Auth::guard($this->getGuard())->logout();//判斷是否是其他用戶登出
return redirect(property_exists($this, 'redirectAfterLogout') ? $this->redirectAfterLogout : '/');//判斷是否有登出后跳轉這個選項
}
/**
* Get the guest middleware for the application.
*/
public function guestMiddleware()//判斷哪種中間件
{
$guard = $this->getGuard();
return $guard ? 'guest:'.$guard : 'guest';
}
/**
* Get the login username to be used by the controller.
*
* @return string
*/
public function loginUsername()//判斷是否存在username屬性,存在就獲取,否則獲取email
{
return property_exists($this, 'username') ? $this->username : 'email';
}
/**
* Determine if the class is using the ThrottlesLogins trait.
*
* @return bool
*/
protected function isUsingThrottlesLoginsTrait()
{
return in_array(
ThrottlesLogins::class, class_uses_recursive(static::class)
);
}
/**
* Get the guard to be used during authentication.
*
* @return string|null
*/
protected function getGuard()//判斷是否存在guard屬性,判斷哪個用戶
{
return property_exists($this, 'guard') ? $this->guard : null;
}
}
因為路由上看到要處理getlogin,postlogin,getregister,postregister,而AuthenticatesUsers就是主要處理getlogin,postlogin的。<p>
再看RegistersUsers.php
namespace Illuminate\Foundation\Auth;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Auth;
trait RegistersUsers
{
use RedirectsUsers;
/**
* Show the application registration form.
*
* @return \Illuminate\Http\Response
*/
public function getRegister()//注冊
{
return $this->showRegistrationForm();
}
/**
* Show the application registration form.
*
* @return \Illuminate\Http\Response
*/
public function showRegistrationForm()//展示注冊頁面
{
if (property_exists($this, 'registerView')) {//如果設置了注冊頁面,就進去
return view($this->registerView);
}
return view('auth.register');//否則調用auth.register的頁面
}
/**
* Handle a registration request for the application.
*
* @param \Illuminate\Http\Request $request
* @return \Illuminate\Http\Response
*/
public function postRegister(Request $request)
{
return $this->register($request);
}
/**
* Handle a registration request for the application.
*
* @param \Illuminate\Http\Request $request
* @return \Illuminate\Http\Response
*/
public function register(Request $request)
{
$validator = $this->validator($request->all());//驗證request
if ($validator->fails()) {
$this->throwValidationException(
$request, $validator
);
}
Auth::guard($this->getGuard())->login($this->create($request->all()));//先訪問指定的guard實例,然后登入到一個指定的用戶上
return redirect($this->redirectPath());
}
/**
* Get the guard to be used during registration.
*
* @return string|null
*/
protected function getGuard()
{
return property_exists($this, 'guard') ? $this->guard : null;
}
}