【问题标题】:Modify Laravel 5.2 Authentication修改 Laravel 5.2 认证
【发布时间】:2016-08-29 22:55:49
【问题描述】:

谁能帮我修改Laravel 5.2 身份验证。我不知道如何正确调整默认数据库迁移和配置身份验证的某些部分。我已经迁移了数据库并生成了身份验证的视图来测试身份验证。然后,我尝试回滚更改,因为我需要做的是更改 password_resetsusers 表的名称以及两个表字段的相同名称。我需要为password_resetsusers 的所有字段添加前缀。我研究了如何做到这一点并对其进行了测试。但是,每次我提交表单时总是会出错,因为我修改了表格结构。在调整数据库后,我需要了解我应该在哪里修改以及还应该修改什么。有人可以指导我吗?我真的很感激。我是Laravel 的新手,我真的很想学习这个框架。

这是我的进步:

所以我重命名了这些表。我将前缀 emr_ 添加到 userspassword_resets 然后,对于emr_users 表的字段,我为带有usr_ 的字段添加了前缀,对于emr_password_resets,我添加了ps_

用户表: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

密码重置表: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

使用php artisan migrate 迁移数据库并运行php artisan serve 后一切看起来都很好,但是当我测试登录表单并提交它时,我收到以下错误:

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)
...

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

我通过编辑/config/auth.php 文件解决了上述错误。默认情况下,该文件第 73 到 76 行中的代码块被注释掉。我取消注释代码块并在第 75 行将 'table' => 'users' 更改为 'table' => 'emr_users',结果如下:

<?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,
        ],
    ],

];

因此错误消失并识别emr_users 表。但是当我尝试从登录表单再次提交时会产生另一个错误:

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)
...

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

email 字段更改为 usr_email 字段,这就是显示上述错误的原因。

这是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');
        }
    }

}

我想了解如何正确配置这些表和字段以及 Laravel 5.2 的身份验证设计或结构,以确定要修改的位置和内容。

请帮忙。谢谢

【问题讨论】:

  • 分享您的尝试和遇到的错误?
  • 谢谢您的回复先生。我编辑了我的帖子,请再次检查。

标签: php database authentication laravel-5.2


【解决方案1】:

好的,首先你们使用 laravel 提供的默认 postLogin 函数。这很好,但如果您需要对身份验证过程进行更多控制,您可以覆盖此功能。

因此,您将在 AuthController 中创建一个名为 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');
      }
      ....
    }

}

现在为您的 App\User Model 添加以下功能

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

现在对于您的密码重置表,只需在 passwords.users.table 的 config/auth.php 文件中更改表的名称

 /*
|--------------------------------------------------------------------------
| 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,
    ],
],

【讨论】:

  • 我试过你的答案,但我仍然得到错误: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)。仍然无法识别相同的 usr_email 字段。
  • 显示你的控制器代码
  • 您还必须从 config/auth.php 'users' =&gt; [ 'driver' =&gt; 'database', 'table' =&gt; 'emr_users', ], 中删除它
  • 我编辑了我的帖子我添加了我的AuthController.php 内容。好心检查。好的,我会将其从 config/auth.php 中删除。谢谢
  • $attempt_request = [ 'usr_email' => $request->email, 'password' => $request->password ];
【解决方案2】:

您没有电子邮件的列,因此出现错误。

检查用户表的迁移,

你可能需要添加

$table->string('email')->unique();

然后运行,php artisan migrate。插入字段

【讨论】:

    猜你喜欢
    • 2016-04-23
    • 2017-01-08
    • 2016-06-23
    • 2016-06-11
    • 2016-06-24
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多