laravel5經過auth.attempt事件加入登錄驗證碼

<?php namespace WangDong\Http\Controllers\Auth;

use Illuminate\Http\Exception\HttpResponseException;
use Illuminate\Http\Request;
use WangDong\Http\Controllers\Controller;
use Illuminate\Contracts\Auth\Guard;
use Illuminate\Contracts\Auth\Registrar;
use Illuminate\Foundation\Auth\AuthenticatesAndRegistersUsers;

class AuthController extends Controller {

    /*
    |--------------------------------------------------------------------------
    | Registration & Login Controller
    |--------------------------------------------------------------------------
    |
    | This controller handles the registration of new users, as well as the
    | authentication of existing users. By default, this controller uses
    | a simple trait to add these behaviors. Why don't you explore it?
    |
    */

    use AuthenticatesAndRegistersUsers;

    /**
     * Create a new authentication controller instance.
     *
     * @param  \Illuminate\Contracts\Auth\Guard  $auth
     * @param  \Illuminate\Contracts\Auth\Registrar  $registrar
     * @return void
     */
    public function __construct(Guard $auth, Registrar $registrar,Request $request)
    {
        $this->auth = $auth;
        $this->registrar = $registrar;
        //註冊auth.attemp事件
        //加入驗證碼的驗證
        $this->auth->attempting(function()use($request){
            $phrase = \Session::get('phrase');
            if($request->input('phrase') != $phrase){
                throw new HttpResponseException(
                    redirect('/auth/login')->withInput($request->input())->withErrors(['phrase'=>'驗證碼錯誤'])
                );
            }
        });
        $this->middleware('guest', ['except' => 'getLogout']);
    }

}

須要特別說明的是HttpResponseException這個異常,這個異常接收一個Response做爲參數,在Illuminate\Routing\Route的run方法中會捕獲這個異常並返回設置的Response,因此咱們能夠經過拋出這個異常來終止咱們的應用程序並跳轉php

    public function run(Request $request)
    {
        $this->container = $this->container ?: new Container;

        try
        {
            if ( ! is_string($this->action['uses']))
                return $this->runCallable($request);

            if ($this->customDispatcherIsBound())
                return $this->runWithCustomDispatcher($request);

            return $this->runController($request);
        }
        catch (HttpResponseException $e)
        {
            return $e->getResponse();
        }
    }    
相關文章
相關標籤/搜索