1. 程式人生 > 實用技巧 >Laravel 自動生成驗證的例項講解:login / logout

Laravel 自動生成驗證的例項講解:login / logout

Laravel 自動授權講解

看到這部分文件,經常看見的一句話就是php artisan make:auth,經常好奇這段程式碼到底幹了什麼,現在就來扒一扒。

路由

路由檔案中會新加入以下內容:

Auth::routes();
Route::get('/home','HomeController@index')->name('home');

首先先是Auth::route();,這句程式碼等於以下全部設定(檔案位置是\Illuminate\Routing\Router.php):

/**
  * Register the typical authentication routes for an application.
  *
  * @return void
  */
 public function auth()
 {
  // Authentication Routes...
  $this->get('login', 'Auth\LoginController@showLoginForm')->name('login');
  $this->post('login', 'Auth\LoginController@login');
  $this->post('logout', 'Auth\LoginController@logout')->name('logout');

  // Registration Routes...
  $this->get('register', 'Auth\RegisterController@showRegistrationForm')->name('register');
  $this->post('register', 'Auth\RegisterController@register');

  // Password Reset Routes...
  $this->get('password/reset', 'Auth\ForgotPasswordController@showLinkRequestForm')->name('password.request');
  $this->post('password/email', 'Auth\ForgotPasswordController@sendResetLinkEmail')->name('password.email');
  $this->get('password/reset/{token}', 'Auth\ResetPasswordController@showResetForm')->name('password.reset');
  $this->post('password/reset', 'Auth\ResetPasswordController@reset');
 }

這一部分先講註冊,首先,可以看到登入(login)的路由指向的是Auth\LoginController@showLoginForm,這個控制器是app\Http\Auth\LoginController.php,這裡貼一下他的程式碼:

class LoginController extends Controller
{
 /*
 |--------------------------------------------------------------------------
 | Login Controller
 |--------------------------------------------------------------------------
 |
 | This controller handles authenticating users for the application and
 | redirecting them to your home screen. The controller uses a trait
 | to conveniently provide its functionality to your applications.
 |
 */

 use AuthenticatesUsers;

 /**
  * Where to redirect users after login.
  *
  * @var string
  */
 protected $redirectTo = '/home';

 /**
  * Create a new controller instance.
  *
  * @return void
  */
 public function __construct()
 {
  $this->middleware('guest')->except('logout');
 }
}

而其中並沒有設定showLoginForm方法,該方法被儲存在trait AuthenticatesUsers中,該方法的程式碼如下:

public function showLoginForm()
 {
  return view('auth.login');
 }

就是返回一個檢視,下面我們來看該檢視:

<form class="form-horizontal" method="POST" action="{{ route('login') }}">
</form>

而其中最重要的就是看這個表單被提交到了哪裡,結合上面的路由表,可以看到是

public function login(Request $request)
 {
  $this->validateLogin($request);
  /**
  *
  protected function validateLogin(Request $request)
 {
  $this->validate($request, [
   $this->username() => 'required|string',
   'password' => 'required|string',
  ]);
 }
  其中 $this->username() 就是 return 'email';
  **/
  // 限制請求次數,防止暴力破解的
  if ($this->hasTooManyLoginAttempts($request)) {
   $this->fireLockoutEvent($request);

   return $this->sendLockoutResponse($request);
  }
  /**
  // 關於 attempt 的介紹可以看我上一篇部落格
  protected function attemptLogin(Request $request)
 {
  return $this->guard()->attempt(
   $this->credentials($request), $request->has('remember')
  );
 }
 **/
  // 如果驗證通過的話
  if ($this->attemptLogin($request)) {
   return $this->sendLoginResponse($request);
  }
  // 否則的話增加驗證的統計次數
  $this->incrementLoginAttempts($request);
  // 返回錯誤資訊
  return $this->sendFailedLoginResponse($request);
 }

可以看到驗證的重點還是Auth::attempt()函式,而且預設是使用email進行驗證。

退出操作的程式碼如下:

public function logout(Request $request)
 {
  $this->guard()->logout();

  $request->session()->invalidate();

  return redirect('/');
 }

$this->guard()的程式碼如下:

protected function guard()
 {
  return Auth::guard();
 }

logout的具體的執行程式碼如下,別問我怎麼找到的,PHPStorm的全專案文字搜尋不解釋:\Illuminate\Auth\SessionGuard.php:

public function logout()
 {
  $user = $this->user();

  $this->clearUserDataFromStorage();

  if (! is_null($this->user)) {
   $this->cycleRememberToken($user);
  }

  if (isset($this->events)) {
   $this->events->dispatch(new Events\Logout($user));
  }

  // Once we have fired the logout event we will clear the users out of memory
  // so they are no longer available as the user is no longer considered as
  // being signed into this application and should not be available here.
  $this->user = null;

  $this->loggedOut = true;
 }

其中牽扯很多,那麼我換種角度考慮,假設我們不考慮logout()的具體實現,而是思考如何製作自己的退出設定,那麼該如何修改原始碼呢?好像直接修改成下面的形式就可以了:

public function logout(Request $request)
 {
  Auth::guard()->logout();

  $request->session()->invalidate();
  // 自定義重定向地址
  return redirect('/');
 }

其中的很多內容都跟我們的設定無關,全自動的呼叫,所以我們的退出按鈕就只需要執行上述程式碼即可。本人請測有效。

以上這篇Laravel 自動生成驗證的例項分析:login / logout就是小編分享給大家的全部內容了,希望能給大家一個參考,也希望大家多多支援碼農教程。