Сброс пароля не возвращает сообщения об ошибках при проверке - PullRequest
0 голосов
/ 10 мая 2019

После сброса пароля пользователь получает электронное письмо со ссылкой для сброса пароля и токеном. При открытии этой ссылки пользователю предоставляется форма сброса пароля (просмотр).

До этого момента все работало замечательно ... но всякий раз, когда я передаю неправильное электронное письмо, чтобы вызвать предупреждение об ошибке " email not valid ", оно ничего не дает.

enter image description here

Проверка C:\Users\richa\Projects\globeguru\cms\vendor\laravel\framework\src\Illuminate\Foundation\Auth\ResetsPasswords.php Я наткнулся на функцию ответа в строке 3:

PHP

public function reset(Request $request)
{
    $request->validate($this->rules(), $this->validationErrorMessages());

    // Here we will attempt to reset the user's password. If it is successful we
    // will update the password on an actual user model and persist it to the
    // database. Otherwise we will parse the error and return the response.
    $response = $this->broker()->reset(
        $this->credentials($request), function ($user, $password) {
            $this->resetPassword($user, $password);
        }
    );

    // If the password was successfully reset, we will redirect the user back to
    // the application's home authenticated view. If there is an error we can
    // redirect them back to where they came from with their error message.
    return $response == Password::PASSWORD_RESET
                ? $this->sendResetResponse($request, $response)
                : $this->sendResetFailedResponse($request, $response);
}

Эта строка:

$request->validate($this->rules(), $this->validationErrorMessages());

Что подводит меня к этой функции:

protected function validationErrorMessages()
{
    return [];
}

У меня вопрос - как я могу вызвать сообщение об ошибке и вернуть его через функцию validationErrorMessages()?

[Изменено] В соответствии с просьбой, здесь есть форма сброса HTML

@section('reset-form')
    <div class="alert-container" >
        @if (session('status'))
            <div class="alert alert-success alert-dismissible fade show" role="alert">
                <p><strong>Success!</strong></p>
                <p>{{ session('alert') }}</p>
                <button type="button" class="close" data-dismiss="alert" aria-label="Close">
                    <span aria-hidden="true">&times;</span>
                </button>
            </div>
        @endif

        @error('email')
        <div class="alert alert-danger alert-dismissible fade show" role="alert">
            <p><strong>Error!</strong></p>
            <p>{{ $message }}</p>
            <button type="button" class="close" data-dismiss="alert" aria-label="Close">
                <span aria-hidden="true">&times;</span>
            </button>
        </div>
        @enderror

        @error('password')
        <div class="alert alert-danger alert-dismissible fade show" role="alert">
            <p><strong>Error!</strong></p>
            <p>{{ $message }}</p>
            <button type="button" class="close" data-dismiss="alert" aria-label="Close">
                <span aria-hidden="true">&times;</span>
            </button>
        </div>
        @enderror

        @error('password_confirmation')
        <div class="alert alert-danger alert-dismissible fade show" role="alert">
            <p><strong>Error!</strong></p>
            <p>{{ $message }}</p>
            <button type="button" class="close" data-dismiss="alert" aria-label="Close">
                <span aria-hidden="true">&times;</span>
            </button>
        </div>
        @enderror
    </div>

    <div class="gg-login-wrap">
        <div class="modal-dialog" role="document">
            <div class="modal-content">
                <div class="modal-header">
                    <h5 class="modal-title">{{ __('auth.reset_title') }}</h5>
                </div>
                <div class="modal-body">
                    <form class="gg-login" method="POST" action="{{ route('password.update') }}">
                        @csrf

                        <div class="form-group edit-input-wrap">
                            <input id="email" type="email" class="form-control edit-input @error('email') is-invalid @enderror" name="email" value="{{ old('email') }}" required autocomplete="email">
                            <label for="email">{{ __('auth.email') }}</label>

                            @error('email')
                                <span class="invalid-feedback" role="alert">
                                    <strong>{{ $message }}</strong>
                                </span>
                            @enderror
                        </div>
                        <div class="form-group edit-input-wrap">
                            <input id="password" type="password" class="form-control edit-input @error('password') is-invalid @enderror" name="password" required autocomplete="current-password">
                            <label for="password">{{ __('auth.password') }}</label>

                            @error('password')
                                <span class="invalid-feedback" role="alert">
                                    <strong>{{ $message }}</strong>
                                </span>
                            @enderror
                        </div>
                        <div class="form-group edit-input-wrap">
                            <input id="password_confirmation" type="password" class="form-control" name="password_confirmation" required autocomplete="password_confirmation">
                            <label for="password_confirmation">{{ __('auth.password_repeat') }}</label>

                            @error('password_confirmation')
                            <span class="invalid-feedback" role="alert">
                                    <strong>{{ $message }}</strong>
                                </span>
                            @enderror
                        </div>
                        <input type="submit" class="btn btn-primary" value="{{ __('auth.reset') }}">
                    </form>
                </div>
            </div>
        </div>
    </div>
@endsection

Также сбрасывает $errors я получаю следующий ответ:

{"token":["The token field is required."]} 

Предоставляется @csrf, поэтому я не знаю, что еще может вызвать это.

ОБНОВЛЕНИЕ № 2

Хорошо, я просто запаниковал и положил dump на каждый шаг в функции reset, и когда я ставлю его перед проверкой, как здесь:

 public function reset(Request $request)
    {
        dump($request); // <-------------------------
        $request->validate($this->rules(), $this->validationErrorMessages());

        // Here we will attempt to reset the user's password. If it is successful we
        // will update the password on an actual user model and persist it to the
        // database. Otherwise we will parse the error and return the response.
        $response = $this->broker()->reset(
            $this->credentials($request), function ($user, $password) {
                $this->resetPassword($user, $password);
            }
        );

        // If the password was successfully reset, we will redirect the user back to
        // the application's home authenticated view. If there is an error we can
        // redirect them back to where they came from with their error message.
        return $response == Password::PASSWORD_RESET
                    ? $this->sendResetResponse($request, $response)
                    : $this->sendResetFailedResponse($request, $response);
    }

возвращает страницу с дампом Request и выдает следующее сообщение: Redirecting to http://localhost:8000/password/reset/a98f717fd25f4c5b32e2ee81e1276058e294ea6536509d1a223d131bcc0dd12c., которое ясно показывает, что между проверкой и сбросом существует перенаправление.

Если я дам дамп после этого, он ничего не вернет, поэтому он ясно показывает, что он сломался во время $request->validate($this->rules(), $this->validationErrorMessages()); этого шага.

Вот ссылка на обсуждение Laracasts: https://laracasts.com/discuss/channels/laravel/password-reset-not-returning-error-messages-on-validation?page=1#reply=510638

1 Ответ

0 голосов
/ 12 мая 2019

Хорошо, я исправил это, изменив html с этого:

<form class="gg-login" method="POST" action="{{ route('password.update') }}">
                        @csrf 

на это:

<form class="gg-login" method="POST" action="{{ route('password.update') }}">
                        @csrf
                        <input type="hidden" name="token" value="{{ $token }}">

dump($request->all()) возвращает:

array:5 [▼
  "_token" => "RlwpqsSHcN42PaEWvIMHCYjjowAnox8ApTA9eeUV"
  "token" => "2fb28348a08eac8386a2276be5a7ed5a2847adef39b4ed769157e2213bc208c9"
  "email" => "admin@demo.com"
  "password" => "password"
  "password_confirmation" => "password"
]

Redirecting to http://localhost:8000/login. 

Тактеперь это работает, и хотя я понимаю, что token и _token отличаются, и один используется для качания, а другой для сброса пароля, я все еще не понимаю, как мое решение отличается от оригинального Laravel Auth, где есть просто @csrfвызывается и затем компилируется Blade, возвращая все необходимые скрытые входные данные.

...