20150720-laravel login verification hit the pit

Source: Internet
Author: User
Keep track of the pits you've stepped on, and you'll have fewer pits in the future ...

First build the table:

phpartisanmigrate:make_admin_table

Then, in the new file, write the column settings for the table.


   Phpuse Illuminate\Database\Schema\Blueprint;use Illuminate\Database\Migrations\Migration;class Createadmintable extends Migration {/** * Run the migrations. * * @return void * * Publicfunction up () {Schema:: Create(' admin ', Function ($table)        {$table -Increments (' id ');$table -string(' Staff_code ', +) -Nullable ();//Employee number$table -string(' login_name ', +) -Nullable ();//Login name$table -string(' Password ', +) -Nullabele ();//Login Password$table -string(' Mail ', +) -Nullable ();//E-mail$table -string(' Staff_name ', +) -Nullable ();//Employee name$table -string(' Sex ',Ten) -Nullable ();//Gender$table -string(' belong_to ', +) -Nullable ();//Department$table -string(' Jobs ', +) -Nullable ();//Post$table -string(' Telephone ', +) -Nullable ();//fixed telephone$table -string(' Mobile ', +) -Nullable ();//Mobile phone number}); }/** * Reverse the migrations. * * @return void * * Publicfunction down () {Schema::d ropifexists(' admin '); }}

To build the Model admin:

generate modle Admin

and add it in the generated file.


    UseIlluminate\Auth\usertrait; UseIlluminate\Auth\userinterface; UseIlluminate\Auth\Reminders\remindabletrait; UseIlluminate\Auth\Reminders\Remindableinterface; classAdminextends \Eloquentimplements  UserInterface, remindableinterface { Useusertrait,remindabletrait;protected$fillable= [];protected$table=' admin ';//Specify Table nameprotected$primaryKey=' id ';//Specify primary Key nameprotected$hidden=Array(' Password ');//password field Public$timestamps=false;//Turn off automatic maintenance of creation time and update time Public functiongetremembertoken(){return$this->remembertoken; } Public functionsetremembertoken($value){$this->remembertoken =$value; } Public functiongetremembertokenname(){return$this->reminder; }}

Explain that because login verification is required, Laravel comes with auth so you need to add use and inherit UserInterface and Remindableinterface interface and write some methods
Specifically, these are the words.

 UseIlluminate\Auth\usertrait; UseIlluminate\Auth\userinterface; UseIlluminate\Auth\Reminders\remindabletrait; UseIlluminate\Auth\Reminders\Remindableinterface; classAdminextends \Eloquentimplements  UserInterface, remindableinterface { Useusertrait,remindabletrait;/******* The following code omits *******/ Public functiongetremembertoken(){return$this->remembertoken; } Public functionsetremembertoken($value){$this->remembertoken =$value; } Public functiongetremembertokenname(){return$this->reminder; }    }

And then I went on to find the settings for the Auth file. Modify the table you need to use
app/config/auth.php
Locate the following fields and modify them to the table you specified


   
    returnarray('driver' => 'eloquent', //验证方式,有database和eloquent两种'model' => 'Admin', //所使用的model名'table' => 'admin', //对应的表名'reminder' => array(        'email' => 'emails.auth.reminder',        'table' => 'password_reminders',        'expire' => 60,    ),);

Then add the Controller method:

//Get login page Publicfunction Get_web_login () {returnView:: make(' Web.web_login '); }//Login Verification Publicfunction Post_login () {if(Auth:: Attempt(Array(' login_name '=Input:: Get(' login_name '),' Password '=Input:: Get(' Password '))) {Notification:: Success(' Login successful ');returnRedirect:: to('/web/index ') - with(' message ',' successful login '); }Else{Notification:: Warning(' User name password is incorrect ');returnRedirect:: to('/web/login ') - with(' message ',' User name password is incorrect ') -Withinput (); }    }

Then the view file login.blade.php:

@section('title'@parent@stop@section('nav_1')    
  • class="active">"#">登录@stop@section('selection') "login"class="login"> @stop

    Last update route

    Route::get('/web/index'array('as''web.web_index''uses''App\Controllers\Api\WebController@get_web_index'));//登录页面Route::get('/web/login'array('as''web.web_login''uses''App\Controllers\Api\WebController@get_web_login'));Route::post('/web/login'array('as''web.web_login.post''uses''App\Controllers\Api\WebController@post_login'));

    Finish the above work, I will fart on the back of the Open database to plug a user data into, try to log in, and then the problem comes

    No matter how I try, the account password is wrong.

    Baidu Google a bit, but did not find any results
    Helpless under can only see the source of Laravel
    The first call is the attempt method to verify the user name password so i jump into this function to see the next

    /**         * Attempt to authenticate a user using the given credentials.         *         * @param array $credentials         * @param bool $remember         * @param bool $login         * @return bool          * @static         */publicstaticattemptfalsetrue){            return \Illuminate\Auth\Guard::attempt($credentials, $remember, $login);        }

    It's not hard to see that she just returned the results of the Guar::attempt method, then I went in to see

    /** * Attempt to authenticate a user using the given credentials. * * @param array $credentials * @param bool $remember * @param BOOL $login * @return BOOL */
         Publicfunction attempt (Array$credentials=Array(),$remember=false,$login=true)    {$this -Fireattemptevent ($credentials,$remember,$login);$this -lastattempted=$user=$this -Provider -Retrievebycredentials ($credentials);//If An implementation of UserInterface is returned, we ' ll ask the provider//To validate the user against the given credentials, and if they is in//Fact valid we ' ll log the users into the application and return true.if($this -Hasvalidcredentials ($user,$credentials))        {if($login)$this -Login$user,$remember);returntrue; }returnfalse; }

    Here, you can probably know that the login results should be the result of the return of the Hasvalidcredentials method to control, then how it is implemented internally? Go inside and see.

    /**     * Determine if the user matches the credentials.     *     * @param  mixed  $user     * @param  array  $credentials     * @return bool     */protectedhasValidCredentials($user, $credentials)    {        return ! is_null($user) && $this->provider->validateCredentials($user, $credentials);    }

    But here's just a simple decision on whether there are $user parameters, so I'm going to go into the Validatecredentials method

    /**     * Validate a user against the given credentials.     *     * @param  \Illuminate\Auth\UserInterface  $user     * @param  array  $credentials     * @return bool     */publicvalidateCredentials(UserInterface $user, array $credentials);

    Here beginner Laravel I can not understand what the meaning, so can only continue to Google, and then really found me some relevant information
    Extended Auth Features
    After reading this post, add the above code to understand
    Along the list it says
    /vender/laravel/framework/src/illuminate/auth
    So I found eloquentuserprovider.php this file.
    The concrete implementation of the Validatecredentials method is found in its interior.

    /**     * Validate a user against the given credentials.     *     * @param  \Illuminate\Auth\UserInterface  $user     * @param  array  $credentials     * @return bool     */publicvalidateCredentials(UserInterface $user, array $credentials)    {        $plain = $credentials['password'];        return $this->hasher->check($plain, $user->getAuthPassword());    }

    This is clear.

    Laravel when verifying the password, the input password is hashed and then compared with the password stored in the database.

    However, I am directly in the database to add the plaintext password, so the display password is not correct is rightfully
    Therefore, when storing the password field, it is important to remember to use

    Hash::make("$passowrd");

    To generate a hash string for the corresponding password ...
    Then I use this method to write password hash string to the database when the error, check a look, originally set the password field is too short, so the password field length to 1024 words to solve the problem
    This pit has been tossing me all morning ... Record it for your reference, and avoid the pit like me again.
    _ (: З"∠) _

    Also found an article Bolg, said how to laravel the default encryption method for the custom MD5 encryption methods should be used later, paste here for future reference laravel change the default password encryption method of login

    Finish

    Copyright NOTICE: This article for Bo Master original article, without Bo Master permission not reproduced.

    The above describes the 20150720-laravel login to verify the pit, including the aspects of the content, I hope that the PHP tutorial interested in a friend helpful.

  • Contact Us

    The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

    If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

    A Free Trial That Lets You Build Big!

    Start building with 50+ products and up to 12 months usage for Elastic Compute Service

    • Sales Support

      1 on 1 presale consultation

    • After-Sales Support

      24/7 Technical Support 6 Free Tickets per Quarter Faster Response

    • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.