Как расширить или сделать собственный метод sendResetLink () PasswordBroker в Laravel 5.8? - PullRequest
0 голосов
/ 30 апреля 2019

В настоящее время логика сброса пароля заключается в том, что пользователь должен предоставить действительное / зарегистрированное электронное письмо для получения электронного письма для восстановления пароля.

В моем случае я не хочу проверять, является ли электронное письмозарегистрирован или нет из-за проблем безопасности, и я хочу просто выполнить проверку в бэк-энде и сказать пользователю, что «если он предоставил зарегистрированную электронную почту, он должен вскоре получить электронную почту восстановления».

ЧтоЯ сделал для достижения этого редактируется в vendor\laravel\framework\src\Illuminate\Auth\Passwords\PasswordBroker.php sendResetLink() метод из этого:

 /**
     * Send a password reset link to a user.
     *
     * @param  array  $credentials
     * @return string
     */
    public function sendResetLink(array $credentials)
    {
        // First we will check to see if we found a user at the given credentials and
        // if we did not we will redirect back to this current URI with a piece of
        // "flash" data in the session to indicate to the developers the errors.
        $user = $this->getUser($credentials);

        if (is_null($user)) {
            return static::INVALID_USER;
        }

        // Once we have the reset token, we are ready to send the message out to this
        // user with a link to reset their password. We will then redirect back to
        // the current URI having nothing set in the session to indicate errors.
        $user->sendPasswordResetNotification(
            $this->tokens->create($user)
        );

        return static::RESET_LINK_SENT;
    }

к этому:

 /**
     * Send a password reset link to a user.
     *
     * @param  array  $credentials
     * @return string
     */
    public function sendResetLink(array $credentials)
    {
        // First we will check to see if we found a user at the given credentials and
        // if we did not we will redirect back to this current URI with a piece of
        // "flash" data in the session to indicate to the developers the errors.
        $user = $this->getUser($credentials);

//        if (is_null($user)) {
//            return static::INVALID_USER;
//        }

        // Once we have the reset token, we are ready to send the message out to this
        // user with a link to reset their password. We will then redirect back to
        // the current URI having nothing set in the session to indicate errors.
        if(!is_null($user)) {
            $user->sendPasswordResetNotification(
                $this->tokens->create($user)
            );
        }

        return static::RESET_LINK_SENT;
    }

Этот жестко закодированный вариант не является лучшимрешение, потому что оно исчезнет после обновления .. поэтому Я хотел бы знать, как я могу расширить или реализовать это изменение в рамках проекта в папке App , чтобы сохранить это изменение в любое время?

PS Я попробовал решение, упомянутое здесь: Laravel 5.3 Настройка брокера паролей , но оно не сработало .. также дерево каталогов отличается, и я не мог понять, куда поместить новый PasswordBroker.php файл.

ThaНКС заранее!

Ответы [ 2 ]

3 голосов
/ 30 апреля 2019

Вот шаги, которые необходимо выполнить.

Создать новый пользовательский PasswordResetsServiceProvider. У меня есть папка (пространство имен) с именем Extensions, куда я помещу этот файл:

<?php

namespace App\Extensions\Passwords;

use Illuminate\Auth\Passwords\PasswordResetServiceProvider as BasePasswordResetServiceProvider;

class PasswordResetServiceProvider extends BasePasswordResetServiceProvider
{
    /**
     * Indicates if loading of the provider is deferred.
     *
     * @var bool
     */
    protected $defer = true;

    /**
     * Register the service provider.
     *
     * @return void
     */
    public function register()
    {
        $this->registerPasswordBroker();
    }

    /**
     * Register the password broker instance.
     *
     * @return void
     */
    protected function registerPasswordBroker()
    {
        $this->app->singleton('auth.password', function ($app) {
            return new PasswordBrokerManager($app);
        });

        $this->app->bind('auth.password.broker', function ($app) {
            return $app->make('auth.password')->broker();
        });
    }
}

Как видите, этот провайдер расширяет базовый провайдер сброса пароля. Единственное, что меняется, это то, что мы возвращаем пользовательский PasswordBrokerManager из метода registerPasswordBroker. Давайте создадим собственный менеджер брокера в том же пространстве имен:

<?php

namespace App\Extensions\Passwords;

use Illuminate\Auth\Passwords\PasswordBrokerManager as BasePasswordBrokerManager;

class PasswordBrokerManager extends BasePasswordBrokerManager
{
    /**
     * Resolve the given broker.
     *
     * @param  string  $name
     * @return \Illuminate\Contracts\Auth\PasswordBroker
     *
     * @throws \InvalidArgumentException
     */
    protected function resolve($name)
    {
        $config = $this->getConfig($name);

        if (is_null($config)) {
            throw new InvalidArgumentException(
                "Password resetter [{$name}] is not defined."
            );
        }

        // The password broker uses a token repository to validate tokens and send user
        // password e-mails, as well as validating that password reset process as an
        // aggregate service of sorts providing a convenient interface for resets.
        return new PasswordBroker(
            $this->createTokenRepository($config),
            $this->app['auth']->createUserProvider($config['provider'] ?? null)
        );
    }
}

Опять же, этот PasswordBrokerManager расширяет базовый менеджер от laravel. Единственное отличие здесь - это новый метод разрешения, который возвращает новый и пользовательский PasswordBroker из того же пространства имен. Итак, последний файл, который мы создадим для пользовательского PasswordBroker в том же пространстве имен:

<?php

namespace App\Extensions\Passwords;

use Illuminate\Auth\Passwords\PasswordBroker as BasePasswordBroker;

class PasswordBroker extends BasePasswordBroker
{
 /**
     * Send a password reset link to a user.
     *
     * @param  array  $credentials
     * @return string
     */
    public function sendResetLink(array $credentials)
    {
        // First we will check to see if we found a user at the given credentials and
        // if we did not we will redirect back to this current URI with a piece of
        // "flash" data in the session to indicate to the developers the errors.
        $user = $this->getUser($credentials);

//        if (is_null($user)) {
//            return static::INVALID_USER;
//        }

        // Once we have the reset token, we are ready to send the message out to this
        // user with a link to reset their password. We will then redirect back to
        // the current URI having nothing set in the session to indicate errors.
        if(!is_null($user)) {
            $user->sendPasswordResetNotification(
                $this->tokens->create($user)
            );
        }

        return static::RESET_LINK_SENT;
    }
}

Как видите, мы расширяем класс PasswordBroker по умолчанию из Laravel и переопределяем только тот метод, который нам нужен.

Последний шаг - просто заменить брокера Laravel Default PasswordReset нашим. В файле config/app.php измените строку, в которой регистрируется поставщик, следующим образом:

'providers' => [
...
// Illuminate\Auth\Passwords\PasswordResetServiceProvider::class,
   App\Extensions\Passwords\PasswordResetServiceProvider::class,
...
]

Это все, что вам нужно, чтобы зарегистрировать свой брокер паролей. Надеюсь, это поможет.

1 голос
/ 30 апреля 2019

Самым простым решением здесь было бы поместить ваш настроенный код в app\Http\Controllers\Auth\ForgotPasswordController - это контроллер, который использует черту SendsPasswordResetEmails.

Ваш метод переопределяет метод, предоставленный этой чертой, поэтому он будет вызываться вместо метода, который входит в черту. Вы можете переопределить весь метод sendResetLinkEmail своим кодом, чтобы всегда возвращать один и тот же ответ независимо от успеха.

public function sendResetLinkEmail(Request $request)
{
    $this->validateEmail($request);

    // We will send the password reset link to this user. Once we have attempted
    // to send the link, we will examine the response then see the message we
    // need to show to the user. Finally, we'll send out a proper response.
    $response = $this->broker()->sendResetLink(
        $request->only('email')
    );

    return back()->with('status', "If you've provided registered e-mail, you should get recovery e-mail shortly.");
}
Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...