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,所以我们可以通过抛出这个异常来终止我们的应用程序并跳转

    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();

        }

    }    

 

你可能感兴趣的:(laravel)