laravel5.2登錄驗證解析

最近在和同學參與一個創業項目,用到了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;
    }
}
最后編輯于
?著作權歸作者所有,轉載或內容合作請聯系作者
  • 序言:七十年代末,一起剝皮案震驚了整個濱河市,隨后出現的幾起案子,更是在濱河造成了極大的恐慌,老刑警劉巖,帶你破解...
    沈念sama閱讀 227,401評論 6 531
  • 序言:濱河連續發生了三起死亡事件,死亡現場離奇詭異,居然都是意外死亡,警方通過查閱死者的電腦和手機,發現死者居然都...
    沈念sama閱讀 98,011評論 3 413
  • 文/潘曉璐 我一進店門,熙熙樓的掌柜王于貴愁眉苦臉地迎上來,“玉大人,你說我怎么就攤上這事。” “怎么了?”我有些...
    開封第一講書人閱讀 175,263評論 0 373
  • 文/不壞的土叔 我叫張陵,是天一觀的道長。 經常有香客問我,道長,這世上最難降的妖魔是什么? 我笑而不...
    開封第一講書人閱讀 62,543評論 1 307
  • 正文 為了忘掉前任,我火速辦了婚禮,結果婚禮上,老公的妹妹穿的比我還像新娘。我一直安慰自己,他們只是感情好,可當我...
    茶點故事閱讀 71,323評論 6 404
  • 文/花漫 我一把揭開白布。 她就那樣靜靜地躺著,像睡著了一般。 火紅的嫁衣襯著肌膚如雪。 梳的紋絲不亂的頭發上,一...
    開封第一講書人閱讀 54,874評論 1 321
  • 那天,我揣著相機與錄音,去河邊找鬼。 笑死,一個胖子當著我的面吹牛,可吹牛的內容都是我干的。 我是一名探鬼主播,決...
    沈念sama閱讀 42,968評論 3 439
  • 文/蒼蘭香墨 我猛地睜開眼,長吁一口氣:“原來是場噩夢啊……” “哼!你這毒婦竟也來了?” 一聲冷哼從身側響起,我...
    開封第一講書人閱讀 42,095評論 0 286
  • 序言:老撾萬榮一對情侶失蹤,失蹤者是張志新(化名)和其女友劉穎,沒想到半個月后,有當地人在樹林里發現了一具尸體,經...
    沈念sama閱讀 48,605評論 1 331
  • 正文 獨居荒郊野嶺守林人離奇死亡,尸身上長有42處帶血的膿包…… 初始之章·張勛 以下內容為張勛視角 年9月15日...
    茶點故事閱讀 40,551評論 3 354
  • 正文 我和宋清朗相戀三年,在試婚紗的時候發現自己被綠了。 大學時的朋友給我發了我未婚夫和他白月光在一起吃飯的照片。...
    茶點故事閱讀 42,720評論 1 369
  • 序言:一個原本活蹦亂跳的男人離奇死亡,死狀恐怖,靈堂內的尸體忽然破棺而出,到底是詐尸還是另有隱情,我是刑警寧澤,帶...
    沈念sama閱讀 38,242評論 5 355
  • 正文 年R本政府宣布,位于F島的核電站,受9級特大地震影響,放射性物質發生泄漏。R本人自食惡果不足惜,卻給世界環境...
    茶點故事閱讀 43,961評論 3 345
  • 文/蒙蒙 一、第九天 我趴在偏房一處隱蔽的房頂上張望。 院中可真熱鬧,春花似錦、人聲如沸。這莊子的主人今日做“春日...
    開封第一講書人閱讀 34,358評論 0 25
  • 文/蒼蘭香墨 我抬頭看了看天上的太陽。三九已至,卻和暖如春,著一層夾襖步出監牢的瞬間,已是汗流浹背。 一陣腳步聲響...
    開封第一講書人閱讀 35,612評論 1 280
  • 我被黑心中介騙來泰國打工, 沒想到剛下飛機就差點兒被人妖公主榨干…… 1. 我叫王不留,地道東北人。 一個月前我還...
    沈念sama閱讀 51,330評論 3 390
  • 正文 我出身青樓,卻偏偏與公主長得像,于是被迫代替她去往敵國和親。 傳聞我的和親對象是個殘疾皇子,可洞房花燭夜當晚...
    茶點故事閱讀 47,690評論 2 370

推薦閱讀更多精彩內容

  • Spring Cloud為開發人員提供了快速構建分布式系統中一些常見模式的工具(例如配置管理,服務發現,斷路器,智...
    卡卡羅2017閱讀 134,775評論 18 139
  • 先說幾句廢話,調和氣氛。事情的起由來自客戶需求頻繁變更,偉大的師傅決定橫刀立馬的改革使用新的框架(created ...
    wsdadan閱讀 3,067評論 0 12
  • 過去做事情急,什么東西拿起來就用,不喜歡進行系統性的學習,造成在使用過程中的錯誤和低效,現在感覺自己耐心多了,用之...
    馬文Marvin閱讀 2,004評論 0 10
  • 股票投資:三個陷阱識別vs兩大選股法則 在有中國特色的股票市場中,如何進行股票投資,從而打破七虧兩平一贏?其實本質...
    布衣之子閱讀 177評論 0 0
  • 小火花
    三荷聽雨聲閱讀 275評論 0 1