doutun1875 2016-05-04 13:10
浏览 54

修改Laravel 5.2身份验证

Can someone help me modify Laravel 5.2 authentication. I can't figure out how to properly tweak the default database migration and some part of configuring the authentication. I have already migrated the database and generated the views of the authentication to test the auth. Then, I tried to rollback changes because what I need to do is to change the names for both password_resets and users tables and the same thing with both of the tables fields. I need to add prefixes to all fields of password_resets and users. I researched ways on how to do it and tested it. But, I always get an error every time I submit a form because I modified the tables structures. I need to understand where and what else should I modify after tweaking the database. Can someone guide me with this? I would really appreciate it. I'm very new to Laravel and I really want to learn the framework.

Here's my progress:

So I renamed the tables. I added the prefix emr_ to both users and password_resets then, for the fields of emr_users table i added prefix to the fields with usr_ and for emr_password_resets I added ps_.

users table: 2014_10_12_000000_create_users_table

    //some codes

    Schema::create('emr_users', function (Blueprint $table) {
        $table->increments('usr_id');
        $table->string('usr_name');
        $table->string('usr_email')->unique();
        $table->string('usr_password');
        $table->rememberToken();
        $table->timestamps();
    });

    //some codes

password_resets table: 2014_10_12_100000_create_password_resets_table

    //some codes

    Schema::create('emr_password_resets', function (Blueprint $table) {
        $table->string('ps_email')->index();
        $table->string('ps_token')->index();
        $table->timestamp('ps_created_at');
    });

    //some codes

After migrating the database using php artisan migrate and running php artisan serve everything looks fine but when I test the login form and submit it i get the following errors:

2/2 QueryException in Connection.php line 673:
SQLSTATE[42S02]: Base table or view not found: 1146 Table 'emr.users' doesn't exist (SQL: select * from `users` where `email` = admin@sample.com limit 1)
...

and

1/2 PDOException in Connection.php line 333:
SQLSTATE[42S02]: Base table or view not found: 1146 Table 'emr.users' doesn't exist
...

I solved the above errors by editing /config/auth.php file. By default a block of code is comment out in this file in lines 73 to 76. I uncomment the block of code and change 'table' => 'users' to 'table' => 'emr_users' in line 75 which result to:

<?php

return [

    /*
    |--------------------------------------------------------------------------
    | Authentication Defaults
    |--------------------------------------------------------------------------
    |
    | This option controls the default authentication "guard" and password
    | reset options for your application. You may change these defaults
    | as required, but they're a perfect start for most applications.
    |
    */

    'defaults' => [
        'guard' => 'web',
        'passwords' => 'users',
    ],

    /*
    |--------------------------------------------------------------------------
    | Authentication Guards
    |--------------------------------------------------------------------------
    |
    | Next, you may define every authentication guard for your application.
    | Of course, a great default configuration has been defined for you
    | here which uses session storage and the Eloquent user provider.
    |
    | All authentication drivers have a user provider. This defines how the
    | users are actually retrieved out of your database or other storage
    | mechanisms used by this application to persist your user's data.
    |
    | Supported: "session", "token"
    |
    */

    'guards' => [
        'web' => [
            'driver' => 'session',
            'provider' => 'users',
        ],

        'api' => [
            'driver' => 'token',
            'provider' => 'users',
        ],
    ],

    /*
    |--------------------------------------------------------------------------
    | User Providers
    |--------------------------------------------------------------------------
    |
    | All authentication drivers have a user provider. This defines how the
    | users are actually retrieved out of your database or other storage
    | mechanisms used by this application to persist your user's data.
    |
    | If you have multiple user tables or models you may configure multiple
    | sources which represent each model / table. These sources may then
    | be assigned to any extra authentication guards you have defined.
    |
    | Supported: "database", "eloquent"
    |
    */

    'providers' => [
        'users' => [
            'driver' => 'eloquent',
            'model' => App\User::class,
        ],

        'users' => [                      /* line 73 */
            'driver' => 'database',
            'table' => 'emr_users',       /* line 75 */
        ],                                /* line 76 */
    ],

    /*
    |--------------------------------------------------------------------------
    | Resetting Passwords
    |--------------------------------------------------------------------------
    |
    | Here you may set the options for resetting passwords including the view
    | that is your password reset e-mail. You may also set the name of the
    | table that maintains all of the reset tokens for your application.
    |
    | You may specify multiple password reset configurations if you have more
    | than one user table or model in the application and you want to have
    | separate password reset settings based on the specific user types.
    |
    | The expire time is the number of minutes that the reset token should be
    | considered valid. This security feature keeps tokens short-lived so
    | they have less time to be guessed. You may change this as needed.
    |
    */

    'passwords' => [
        'users' => [
            'provider' => 'users',
            'email' => 'auth.emails.password',
            'table' => 'password_resets',
            'expire' => 60,
        ],
    ],

];

So the errors goes away and recognizes the emr_users table. But produces another error when I try to submit again from the login form:

2/2 QueryException in Connection.php line 673:
SQLSTATE[42S22]: Column not found: 1054 Unknown column 'email' in 'where clause' (SQL: select * from `emr_users` where `email` = admin@sample.com limit 1)
...

and

1/2 PDOException in Connection.php line 333:
SQLSTATE[42S22]: Column not found: 1054 Unknown column 'email' in 'where clause'

The email field is changed to usr_email field that's why the error above shows.

Here's the content of AuthController.php

<?php

namespace App\Http\Controllers\Auth;

use App\User;
use Validator;
use App\Http\Controllers\Controller;
use Illuminate\Foundation\Auth\ThrottlesLogins;
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,
    ThrottlesLogins;

    /**
     * Where to redirect users after login / registration.
     *
     * @var string
     */
    protected $redirectTo = '/';

    /**
     * Create a new authentication controller instance.
     *
     * @return void
     */
    public function __construct() {
        $this->middleware($this->guestMiddleware(), ['except' => 'logout']);
    }

    /**
     * Get a validator for an incoming registration request.
     *
     * @param  array  $data
     * @return \Illuminate\Contracts\Validation\Validator
     */
    protected function validator(array $data) {
        return Validator::make($data, [
                    'name' => 'required|max:255',
                    'email' => 'required|email|max:255|unique:users',
                    'password' => 'required|min:6|confirmed',
        ]);
    }

    /**
     * Create a new user instance after a valid registration.
     *
     * @param  array  $data
     * @return User
     */
    protected function create(array $data) {
        return User::create([
                    'name' => $data['name'],
                    'email' => $data['email'],
                    'password' => bcrypt($data['password']),
        ]);
    }

    /**
     * Handle a login request to the application.
     *
     * @param \Illuminate\Http\Request $request
     * @return \Illuminate\Http\Response
     * 
     * Overrides AuthenticateUsers.php postLogin function
     */
    public function postLogin(Request $request) {
        $attempt_request = [
            'usr_email' => $request->email,
            'usr_password' => $request->password
        ];

        if (Auth::attempt($attempt_request)) {
            // Authentication passed...
            return redirect()->intended('dashboard');
        }
    }

}

I want to understand how to properly configure these tables and fields together with the authentication design or structure of Laravel 5.2 to identify where and what to modify.

Please help. Thanks

  • 写回答

2条回答 默认 最新

  • drhzc64482 2016-05-05 06:46
    关注

    OK first of you are using the default postLogin function provided by laravel. Which is great but if you need to have more control over the auth process you can override this function.

    So in your AuthController you will create a function called postLogin

    <?php
    
    /**
     * Class AuthController
     * @package App\Http\Controllers\Auth
     */
    class AuthController extends Controller 
    {
      ....
    
        /**
         * Handle a login request to the application.
         *
         * @param \Illuminate\Http\Request $request
         * @return \Illuminate\Http\Response
         */
        public function postLogin(Request $request) 
        {
           if (Auth::attempt(['usr_email' => $request->email, 'password' => $request->password]) {
            // Authentication passed...
            return redirect()->intended('dashboard');
          }
          ....
        }
    
    }
    

    Now to you App\User Model add the following function

    /**
     * Get the password for the user.
     *
     * @return string
     */
    public function getAuthPassword()
    {
        return $this->usr_password;
    }
    

    Now for your password reset table just change the name of the table in the config/auth.php file at passwords.users.table

     /*
    |--------------------------------------------------------------------------
    | Resetting Passwords
    |--------------------------------------------------------------------------
    |
    | Here you may set the options for resetting passwords including the view
    | that is your password reset e-mail. You may also set the name of the
    | table that maintains all of the reset tokens for your application.
    |
    | You may specify multiple password reset configurations if you have more
    | than one user table or model in the application and you want to have
    | separate password reset settings based on the specific user types.
    |
    | The expire time is the number of minutes that the reset token should be
    | considered valid. This security feature keeps tokens short-lived so
    | they have less time to be guessed. You may change this as needed.
    |
    */
    
    'passwords' => [
        'users' => [
            'provider' => 'users',
            'email' => 'auth.emails.password',
            'table' => 'emr_password_resets',
            'expire' => 60,
        ],
    ],
    
    评论

报告相同问题?

悬赏问题

  • ¥15 Oracle中如何从clob类型截取特定字符串后面的字符
  • ¥15 想通过pywinauto自动电机应用程序按钮,但是找不到应用程序按钮信息
  • ¥15 MATLAB中streamslice问题
  • ¥15 如何在炒股软件中,爬到我想看的日k线
  • ¥15 seatunnel 怎么配置Elasticsearch
  • ¥15 PSCAD安装问题 ERROR: Visual Studio 2013, 2015, 2017 or 2019 is not found in the system.
  • ¥15 (标签-MATLAB|关键词-多址)
  • ¥15 关于#MATLAB#的问题,如何解决?(相关搜索:信噪比,系统容量)
  • ¥500 52810做蓝牙接受端
  • ¥15 基于PLC的三轴机械手程序