Laravel 5.6:在验证错误后防止输入字段重新填充

时间:2018-06-05 11:10:44

标签: php laravel laravel-5.6

我使用Laravel 5.6和HTML collective来构建表单。我有一个处理表单验证的请求类,当验证失败时,表单输入将重新填充已提交的值。我想防止这种情况发生在google2fa字段上,尽管它总是空白而且不会重新填充。有没有办法做到这一点?

控制器:

public function login()
{
    return View::make('auth/login');
}

public function handle_login(UserLoginRequest $request)
{
    // login successful
}

请求

<?php

namespace App\Http\Requests;

use Illuminate\Foundation\Http\FormRequest;
use Validator;
use App\Models\User;
use Auth;
use Guzzle;
use Hash;
use Google2FA;

class UserLoginRequest extends FormRequest
{
    /**
     * Determine if the user is authorized to make this request.
     *
     * @return bool
     */
    public function authorize()
    {
        return true;
    }

    /**
     * Get the validation rules that apply to the request.
     *
     * @return array
     */
    public function rules()
    {
        // check email and password combination is valid
        Validator::extend('valid_login', function($attribute, $value, $parameters)
        {
            $user = User::where('email', '=', $value)->first();
            if($user) {
                return Hash::check($parameters[0], $user->password);
            } else {
                return false;
            }
            return Auth::attempt(['email' => $value, 'password' => $parameters[0]], !is_null($parameters[1]));
        });

        // check recaptcha 
        Validator::extend('notBot', function($attribute, $value, $parameters)
        {
            $client = new \GuzzleHttp\Client;
            try {
                $response = $client->post('https://www.google.com/recaptcha/api/siteverify', [
                    'form_params' => [
                        'secret' => config('services.recaptcha.secret'),
                        'response' => $value,
                        'remoteip' => $this->ip()
                    ]
                ]);
                $result = json_decode($response->getBody()->getContents());

                if($result->success) {
                    return true;
                } else {
                    $this->recaptcha_errors = implode(', ', $result->{'error-codes'});
                    return false;
                }
            } catch(Exception $e) {
                return false;
            }
        });

        // check the two factor authentication
        Validator::extend('2fa_valid', function($attribute, $value, $parameters)
        {
            $user = User::where('email', '=', $this->email)->first();

            if(is_null($user)) {
                return true;
            }

            return Google2FA::verifyKey($user->google2fa_secret, $value);
        });

        Validator::replacer('notBot', function($message, $attribute, $rule, $parameters) {
            return str_replace(':errors', $this->recaptcha_errors, $message);
        });

        return [
            //'g-recaptcha-response' => ['bail', 'required', 'notBot'],
            'email' => ['bail', 'required', 'exists:users,email', 'valid_login:'.$this->password.','.$this->remember_me],
            'password' => ['required'],
            'google2fa' => ['required', '2fa_valid']
        ];
    }

    public function messages()
    {
        return [
            'email.valid_login' => 'The password is incorrect.',
            'email.is_user' => 'The email address is not recognised.',
            'not_bot' => 'Recaptcha error: :errors',
            'g-recaptcha-response.required' => 'You must prove you are not a robot',
            'google2fa.2fa_valid' => 'The 2 factor auth code is invalid',
            'google2fa.required' => 'You must enter a 2 factor auth code'
        ];
    }
}

查看

@extends('layouts.app')

@section('meta_title')
    Login
@stop

@section('content')

    {{ Form::open(['route' => 'login.submit', 'id' => 'user-login', 'class' => 'form-horizontal', 'method' => 'POST']) }}
        <div class="row justify-content-center">
            <div class="col-md-6">
                <h2>Please Login</h2>
                <hr>
            </div>
        </div>
        <div class="row justify-content-center">
            <div class="col-md-6">
                <div class="form-group has-danger">
                    <label class="sr-only" for="email">E-Mail Address</label>
                    <div class="input-group mb-3">
                        <div class="input-group-prepend">
                            <span class="input-group-text" id="basic-addon1"><i class="fa fa-at"></i></span>
                        </div>
                        {{ Form::email('email', null, ['class' => 'form-control', 'id' => 'email', 'required', 'autofocus', 'placeholder' => 'Email address...' ]) }}
                    </div>
                </div>
            </div>
        </div>
        <div class="row justify-content-center">
            <div class="col-md-6">
                <div class="form-group">
                    <label class="sr-only" for="password">Password</label>
                    <div class="input-group mb-3">
                        <div class="input-group-prepend">
                            <span class="input-group-text" id="basic-addon1"><i class="fa fa-key"></i></span>
                        </div>
                        {{ Form::password('password', ['class' => 'form-control', 'id' => 'password', 'required', 'placeholder' => 'Password...']) }}
                    </div>
                </div>
            </div>
        </div>
        <div class="row justify-content-center">
            <div class="col-md-6">
                <div class="form-group">
                    <label class="sr-only" for="password">2 Factor Auth Code</label>
                    <div class="input-group mb-3">
                        <div class="input-group-prepend">
                            <span class="input-group-text"><i class="fa fa-lock"></i></span>
                        </div>
                        {{ Form::text('google2fa', '', ['class' => 'form-control', 'required', 'placeholder' => '2 Factor Auth Code...']) }}
                        <div class="input-group-append">
                            <span class="input-group-text"><button type="button" class="btn btn-sm rounded-circle" data-toggle="popover" data-trigger="focus" data-placement="bottom" title="What is 2 factor authentication?" data-content="2 factor authentication is an extra layer of security to protect your account from unauthorised access. <br><br><a href='{{ route('login.setup_2fa') }}' class='btn btn-primary btn-block'>Setup 2 Factor Authentication</a>"><i class="fa fa-info"></i></button></span>
                        </div>
                    </div>
                </div>
            </div>
        </div>
        {{--
        <div class="row justify-content-center">
            <div class="col-md-6">
                <div class="g-recaptcha" data-sitekey="6LeZAFgUAAAAAKYQAqxk5Vt2TiaR9ryk7VsIA_0F"></div>
            </div>
        </div>
        --}}
        <div class="row justify-content-center">
            <div class="col-md-6" style="padding-top: .35rem">
                <div class="form-check mb-2 mr-sm-2 mb-sm-0">
                    <label class="form-check-label">
                        {{ Form::checkbox('remember', 1, false, ['class' => 'form-check-input']) }}
                        <span style="padding-bottom: .15rem">Remember me</span>
                    </label>
                </div>
            </div>
        </div>
        <div class="row justify-content-center" style="padding-top: 1rem">
            <div class="col-md-6">
                <button type="submit" class="btn btn-primary"><i class="fa fa-sign-in"></i> Login</button>
                <a class="btn btn-link" href="{{ route('login.forgotten_password') }}">Forgot Your Password?</a>
            </div>
        </div>
    {{ Form::close() }}

@stop

@section('scripts')
    {{-- <script src='https://www.google.com/recaptcha/api.js'></script> --}}
    <script type="text/javascript">
        jQuery(document).ready(function($) {
            $('[data-toggle="popover"]').popover({
                html: true
            })
        });
    </script>
@endsection

1 个答案:

答案 0 :(得分:0)

您可以使用&#39; autocomplete =&#34; off&#34; &#39;在该输入上,您可以阅读有关此属性here

的更多信息
{{ Form::text('google2fa', '', ['class' => 'form-control', 'required', 'placeholder' => '2 Factor Auth Code...', 'autocomplete' => 'off']) }}