laravel5.2登錄驗(yàn)證解析

最近在和同學(xué)參與一個創(chuàng)業(yè)項(xiàng)目淋淀,用到了laravel震鹉,仔細(xì)研究了一下纲爸,發(fā)現(xiàn)laravel封裝了很多開箱即用的方法亥鸠,通過traits實(shí)現(xiàn)引入后,就可以使用這些方法识啦,今天我們來分析一下<code>AuthenticatesAndRegistersUsers ThrottlesLogins</code>负蚊,這兩個類,第一個是內(nèi)部封裝了<code>getLogin postLogin getRegister postRegister getLogout</code>的一個類颓哮,通過使用<code>traits AuthenticatesAndRegistersUsers</code>就可以實(shí)現(xiàn)把<code>AuthenticatesAndRegistersUsers</code>引入到<code>authController<code>中家妆,具體實(shí)現(xiàn)稍后會有代碼來說明。<code>ThrottlesLogins</code>是內(nèi)部封裝了一個限制登錄次數(shù)的一個類冕茅。下面來通過代碼說明伤极。<p>
明白這些內(nèi)容,需要明白laravel的多用戶認(rèn)證系統(tǒng)姨伤,稍后有時(shí)間我會寫一篇哨坪,把自己項(xiàng)目分析一下。<p>

//先展示一個登錄驗(yàn)證的路由乍楚,兩種方法
//第一種是通過Route::group實(shí)現(xiàn)路由組
Route::group(['middleware=>['web']],function(){
      Route::resource('/article','ArticleController');
//登錄
      Route::get('auth/login','Auth\AuthController@getLogin');
      Route::post('auth/login','Auth\AuthController@postLogin');
//認(rèn)證
      Route::get('auth/register','Auth\AuthController@getRegister');
      Route::post('auth/register','Auth\AuthController@postRegister');
//登出
      Route::get('auth/logout','Auth\AuthController@getLogout');
})
//第二種是通過Route::group實(shí)現(xiàn)路由組
Route::controllers([
    'auth'=>'Auth\AuthController';
    ''password'=>'Auth\PasswordController'
])

(1)上面這些在laravel 5.2里面都是要包含在web這個中間件的<code>['middleware' => ['web']</code> </li>
(2)login 和 register是在“保護(hù)”內(nèi)的当编,而logout則不是,具體可以看AuthController.php徒溪,主要是因?yàn)閘ogout比較隨意忿偷,也不能用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,不在中間件保護(hù)范圍內(nèi)
      }
      protected function validator(array $data)//這里自帶了一個驗(yàn)證邏輯臊泌,request的驗(yàn)證有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缺虐,在函數(shù)體里面就是用了model的create方法芜壁,直接在數(shù)據(jù)庫生成數(shù)據(jù)
    {
        return User::create([
            'name' => $data['name'],
            'email' => $data['email'],
            'password' => bcrypt($data['password']),
        ]);
    }
}

在<code>AuthenticatesAndRegistersUsers</code>看到了<code>use AuthenticatesUsers, RegistersUsers </code>這里是重點(diǎn),使用了兩個類高氮,一個是驗(yàn)證用戶慧妄,一個是注冊用戶。<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();//調(diào)用本類的showLoginForm方法
    }

    /**
     * Show the application login form.
     *
     * @return \Illuminate\Http\Response
     */
    public function showLoginForm()//供getLogin調(diào)用
    {
        $view = property_exists($this, 'loginView')//判斷本類是否存在loginView屬性剪芍,存在就調(diào)用塞淹,否則調(diào)用auth.authenticate
                    ? $this->loginView : 'auth.authenticate';

        if (view()->exists($view)) {//如果存在就調(diào)用
            return view($view);//調(diào)用view這個視圖模板
        }

        return view('auth.login');//如果不存在就調(diào)用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);//調(diào)用login,request是參數(shù)
    }

    /**
     * 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驗(yàn)證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();//判斷是否限制登錄次數(shù)

        if ($throttles && $lockedOut = $this->hasTooManyLoginAttempts($request)) {//hasTooManyLoginAttempts來判斷登錄次數(shù)罪裹,系統(tǒng)默認(rèn)五次饱普。
            $this->fireLockoutEvent($request);//觸發(fā)鎖定登錄运挫,一分鐘。

            return $this->sendLockoutResponse($request);
        }
        $credentials = $this->getCredentials($request);//調(diào)用getCredentials驗(yàn)證
        if (Auth::guard($this->getGuard())->attempt($credentials, $request->has('remember'))) {//使用auth::guard來訪問指定的guard實(shí)例套耕,
            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)//驗(yàn)證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)//單獨(dú)獲取部分輸入數(shù)據(jù)
    {
        return $request->only($this->loginUsername(), 'password');//單獨(dú)獲取部分輸入數(shù)據(jù)
    }
    /**
     * 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 : '/');//判斷是否有登出后跳轉(zhuǎn)這個選項(xiàng)
    }
    /**
     * 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;
    }
}

因?yàn)槁酚缮峡吹揭幚韌etlogin匈挖,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')) {//如果設(shè)置了注冊頁面择膝,就進(jìn)去
            return view($this->registerView);
        }

        return view('auth.register');//否則調(diào)用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());//驗(yàn)證request

        if ($validator->fails()) {
            $this->throwValidationException(
                $request, $validator
            );
        }

        Auth::guard($this->getGuard())->login($this->create($request->all()));//先訪問指定的guard實(shí)例,然后登入到一個指定的用戶上

        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;
    }
}
最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
  • 序言:七十年代末检激,一起剝皮案震驚了整個濱河市肴捉,隨后出現(xiàn)的幾起案子,更是在濱河造成了極大的恐慌呵扛,老刑警劉巖每庆,帶你破解...
    沈念sama閱讀 217,826評論 6 506
  • 序言:濱河連續(xù)發(fā)生了三起死亡事件,死亡現(xiàn)場離奇詭異今穿,居然都是意外死亡缤灵,警方通過查閱死者的電腦和手機(jī),發(fā)現(xiàn)死者居然都...
    沈念sama閱讀 92,968評論 3 395
  • 文/潘曉璐 我一進(jìn)店門蓝晒,熙熙樓的掌柜王于貴愁眉苦臉地迎上來腮出,“玉大人,你說我怎么就攤上這事芝薇∨叱埃” “怎么了?”我有些...
    開封第一講書人閱讀 164,234評論 0 354
  • 文/不壞的土叔 我叫張陵洛二,是天一觀的道長馋劈。 經(jīng)常有香客問我,道長晾嘶,這世上最難降的妖魔是什么妓雾? 我笑而不...
    開封第一講書人閱讀 58,562評論 1 293
  • 正文 為了忘掉前任,我火速辦了婚禮垒迂,結(jié)果婚禮上械姻,老公的妹妹穿的比我還像新娘。我一直安慰自己机断,他們只是感情好,可當(dāng)我...
    茶點(diǎn)故事閱讀 67,611評論 6 392
  • 文/花漫 我一把揭開白布。 她就那樣靜靜地躺著换棚,像睡著了一般。 火紅的嫁衣襯著肌膚如雪陶耍。 梳的紋絲不亂的頭發(fā)上,一...
    開封第一講書人閱讀 51,482評論 1 302
  • 那天浸颓,我揣著相機(jī)與錄音物臂,去河邊找鬼旺拉。 笑死产上,一個胖子當(dāng)著我的面吹牛,可吹牛的內(nèi)容都是我干的蛾狗。 我是一名探鬼主播晋涣,決...
    沈念sama閱讀 40,271評論 3 418
  • 文/蒼蘭香墨 我猛地睜開眼,長吁一口氣:“原來是場噩夢啊……” “哼沉桌!你這毒婦竟也來了谢鹊?” 一聲冷哼從身側(cè)響起,我...
    開封第一講書人閱讀 39,166評論 0 276
  • 序言:老撾萬榮一對情侶失蹤留凭,失蹤者是張志新(化名)和其女友劉穎佃扼,沒想到半個月后,有當(dāng)?shù)厝嗽跇淞掷锇l(fā)現(xiàn)了一具尸體蔼夜,經(jīng)...
    沈念sama閱讀 45,608評論 1 314
  • 正文 獨(dú)居荒郊野嶺守林人離奇死亡兼耀,尸身上長有42處帶血的膿包…… 初始之章·張勛 以下內(nèi)容為張勛視角 年9月15日...
    茶點(diǎn)故事閱讀 37,814評論 3 336
  • 正文 我和宋清朗相戀三年,在試婚紗的時(shí)候發(fā)現(xiàn)自己被綠了求冷。 大學(xué)時(shí)的朋友給我發(fā)了我未婚夫和他白月光在一起吃飯的照片瘤运。...
    茶點(diǎn)故事閱讀 39,926評論 1 348
  • 序言:一個原本活蹦亂跳的男人離奇死亡,死狀恐怖匠题,靈堂內(nèi)的尸體忽然破棺而出拯坟,到底是詐尸還是另有隱情,我是刑警寧澤韭山,帶...
    沈念sama閱讀 35,644評論 5 346
  • 正文 年R本政府宣布郁季,位于F島的核電站,受9級特大地震影響钱磅,放射性物質(zhì)發(fā)生泄漏梦裂。R本人自食惡果不足惜,卻給世界環(huán)境...
    茶點(diǎn)故事閱讀 41,249評論 3 329
  • 文/蒙蒙 一续搀、第九天 我趴在偏房一處隱蔽的房頂上張望塞琼。 院中可真熱鬧,春花似錦禁舷、人聲如沸彪杉。這莊子的主人今日做“春日...
    開封第一講書人閱讀 31,866評論 0 22
  • 文/蒼蘭香墨 我抬頭看了看天上的太陽派近。三九已至攀唯,卻和暖如春,著一層夾襖步出監(jiān)牢的瞬間渴丸,已是汗流浹背侯嘀。 一陣腳步聲響...
    開封第一講書人閱讀 32,991評論 1 269
  • 我被黑心中介騙來泰國打工, 沒想到剛下飛機(jī)就差點(diǎn)兒被人妖公主榨干…… 1. 我叫王不留谱轨,地道東北人戒幔。 一個月前我還...
    沈念sama閱讀 48,063評論 3 370
  • 正文 我出身青樓,卻偏偏與公主長得像土童,于是被迫代替她去往敵國和親诗茎。 傳聞我的和親對象是個殘疾皇子,可洞房花燭夜當(dāng)晚...
    茶點(diǎn)故事閱讀 44,871評論 2 354

推薦閱讀更多精彩內(nèi)容

  • Spring Cloud為開發(fā)人員提供了快速構(gòu)建分布式系統(tǒng)中一些常見模式的工具(例如配置管理献汗,服務(wù)發(fā)現(xiàn)敢订,斷路器,智...
    卡卡羅2017閱讀 134,656評論 18 139
  • 先說幾句廢話罢吃,調(diào)和氣氛楚午。事情的起由來自客戶需求頻繁變更,偉大的師傅決定橫刀立馬的改革使用新的框架(created ...
    wsdadan閱讀 3,053評論 0 12
  • 過去做事情急尿招,什么東西拿起來就用矾柜,不喜歡進(jìn)行系統(tǒng)性的學(xué)習(xí),造成在使用過程中的錯誤和低效泊业,現(xiàn)在感覺自己耐心多了把沼,用之...
    馬文Marvin閱讀 1,981評論 0 10
  • 股票投資:三個陷阱識別vs兩大選股法則 在有中國特色的股票市場中,如何進(jìn)行股票投資吁伺,從而打破七虧兩平一贏饮睬?其實(shí)本質(zhì)...
    布衣之子閱讀 173評論 0 0
  • 小火花
    三荷聽雨聲閱讀 273評論 0 1