首页 > 解决方案 > Laravel 5.8 自定义电子邮件和密码列

问题描述

我有一个运行 WordPress 的应用程序,我想使用一个使用 Laravel 5.8 的单独界面来访问它。(不用担心散列)

因此,我不想来回克隆密码,而是使用 Laravel 用户模型中的 user_email 和 user_pass 列。

我已经尝试过官方文档所说的:

namespace App\Http\Controllers;

use Illuminate\Http\Request;
use Illuminate\Support\Facades\Auth;

class LoginController extends Controller
{
    /**
     * Handle an authentication attempt.
     *
     * @param  \Illuminate\Http\Request $request
     *
     * @return Response
     */
    public function authenticate(Request $request)
    {
        $credentials = $request->only('user_email', 'user_pass');

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

然后我编辑了刀片文件,但无济于事。任何指针?

标签: wordpresslaravel

解决方案


Laravel 提供了一种通过覆盖某些函数来更改 auth(电子邮件、密码)的默认列的方法。

在您的用户模型中添加此函数,该函数会覆盖密码的默认列:

App/User.php

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

并且,在您的 LoginController 中,从 email 更改为 user_email

App/Http/Controllers/Auth/LoginController.php

/**
 * Get the login username to be used by the controller.
 *
 * @return string
 */
public function username()
{
    return 'user_email';
}

现在你已经覆盖了 Laravel 的 Auth 逻辑使用的默认列。但你还没有完成。

LoginController 有一个验证用户输入的函数,并且密码列是硬编码的,password所以为了改变它,你还需要在 LoginController 中添加这些函数:

App/Http/Controllers/Auth/LoginController.php

/**
 * Validate the user login request.
 *
 * @param  \Illuminate\Http\Request  $request
 * @return void
 *
 * @throws \Illuminate\Validation\ValidationException
 */
protected function validateLogin(Request $request)
{
    $request->validate([
        $this->username() => 'required|string',
        'user_pass' => 'required|string',
    ]);
}


/**
 * Get the needed authorization credentials from the request.
 *
 * @param  \Illuminate\Http\Request  $request
 * @return array
 */
protected function credentials(Request $request)
{
    return $request->only($this->username(), 'user_pass');
}

下一步是创建一个自定义提供程序,我们将其命名为CustomUserProvider将使用它而不是默认提供程序,EloquentUserProvider并且您将在其中覆盖密码字段。

App/Providers/CustomUserProvider.php

<?php
namespace App\Providers;

class CustomUserProvider extends EloquentUserProvider
{
    /**
     * Retrieve a user by the given credentials.
     *
     * @param  array  $credentials
     * @return \Illuminate\Contracts\Auth\Authenticatable|null
     */
    public function retrieveByCredentials(array $credentials)
    {
        if (empty($credentials) ||
           (count($credentials) === 1 &&
            array_key_exists('user_pass', $credentials))) {
            return;
        }

        // First we will add each credential element to the query as a where clause.
        // Then we can execute the query and, if we found a user, return it in a
        // Eloquent User "model" that will be utilized by the Guard instances.
        $query = $this->createModel()->newQuery();

        foreach ($credentials as $key => $value) {
            if (Str::contains($key, 'user_pass')) {
                continue;
            }

            if (is_array($value) || $value instanceof Arrayable) {
                $query->whereIn($key, $value);
            } else {
                $query->where($key, $value);
            }
        }

        return $query->first();
    }

    /**
     * Validate a user against the given credentials.
     *
     * @param  \Illuminate\Contracts\Auth\Authenticatable  $user
     * @param  array  $credentials
     * @return bool
     */
    public function validateCredentials(UserContract $user, array $credentials)
    {
        $plain = $credentials['user_pass'];

        return $this->hasher->check($plain, $user->getAuthPassword());
    }
}

现在你扩展了默认提供者,你需要告诉 Laravel 使用这个而不是EloquentUserProvider. 这就是你可以做到的。

App/Providers/AuthServiceProvider.php


/**
 * Register any authentication / authorization services.
 *
 * @return void
 */
public function boot()
{
    $this->registerPolicies();

    $this->app->auth->provider('custom', function ($app, $config) {
        return new CustomUserProvider($app['hash'], $config['model']);
    });
}

最后更新配置信息config/auth.php并将驱动程序从更改eloquentcustom(这就是我上面命名的方式;您可以将其更改为您想要的任何内容)。所以config/auth.php文件应该有这个位:

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

希望能帮助到你!

问候


推荐阅读