【问题标题】:Laravel 5 Captcha by mewebstudio/captchaLaravel 5 验证码由 mewebstudio/captcha 提供
【发布时间】:2018-09-26 18:09:58
【问题描述】:

我在 laravel 5.2.* 中运行,并且正在我的新网站中探索验证码。我在 github 中看到了一个名为 mewebstudio/captcha 的包。我按照他的说明安装和测试图像是否正常工作,结果很好,但是当我在我的登录页面中实现它时,我有点困惑我应该在哪里声明验证。

我输入了登录凭据,但我试图不在验证码框中输入正确的答案,令人惊讶的是,我进入了不应该的主页。你们有什么解决办法吗?谢谢。

附:对不起我的英语

表格:

 <!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="utf-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1">
    <title>LOGIN</title>
    <meta name="msapplication-TileColor" content="#da532c">
    <meta name="msapplication-TileImage" content="/mstile-144x144.png">
    <meta name="theme-color" content="#ffffff">
</head>
<body>

<div id="wrap">
    <div class="container-fluid">
        <div class="row">
            <div class="col-xs-12 col-sm-10 col-md-4 col-xs-offset-0 col-sm-offset-1 col-md-offset-4">
                <div class="main-content-login">
                    <div class="panel panel-fos" style="margin-top: 100px;">
                        <div class="panel-heading">
                            <h3> LOG IN</h3>

                        </div>

                        <div class="panel-body">
                            @if (count($errors) > 0)
                                <div class="alert alert-danger">
                                    <strong>Whoops!</strong> There were some problems with your input.<br><br>
                                    <ul style="text-align: left;">
                                        @foreach ($errors->all() as $error)
                                            <li>{{ $error }}</li>
                                        @endforeach
                                    </ul>
                                </div>
                            @endif


                                <form id="emailForm" role="form" method="POST" action="{{ url('/auth/login') }}">
                                <input type="hidden" name="_token" value="{{ csrf_token() }}">
                                <div class="form-group">
                                    <!--<div class="row">
                                        <div class="col-sm-4 col-lg-3">
                                            <label>Username:</label>
                                        </div>
                                        <div class="col-sm-8 col-lg-9">
                                            <input type="password" name="password" class="form-control login" id="password">

                                        </div>
                                    </div>-->
                                    <div class="input-group">
                                        <span class="input-group-addon glyphicon glyphicon-user"></span>
                                        <input type="email" id="email" name="email" class="form-control"  aria-describedby="inputGroupSuccess3Status" placeholder="Email Address">
                                    </div>
                                </div>
                                <div class="form-group">

                                    <div class="input-group">
                                        <span class="input-group-addon glyphicon glyphicon-lock"></span>
                                        <input type="password" class="form-control" id="password" name="password" aria-describedby="inputGroupSuccess3Status" placeholder="Password">
                                    </div>
                                </div>
                                <div class="form-group">

                                    <div class="input-group">
                                        {!! captcha_img() !!}
                                        <input type="text" name="captcha" id="captcha">
                                    </div>
                                </div>

                                <div class="row" style="margin-top: 30px;">
                                    <div class="col-xs-12 col-sm-6">
                                        <input type="submit" class="btn btn-md btn-primary btn-move-right login-btn" value="Log In"> </button>
                                    </div>
                                    <div class="col-xs-12 col-sm-6 checkbox remember" style="margin-top: 0;">
                                        <label class="remember"><input type="checkbox"> Remember me</label>
                                    </div>
                                </div>
                                <div class="row">
                                    <div class="col-xs-12">
                                        <a href="{{ url('/password/email') }}"> Forgot Password?</a>
                                    </div>
                                </div>

                                {{--<div class="row" style="margin-top: 30px;">
                                    <div class="col-xs-7 col-lg-7">
                                        <input type="submit" class="btn btn-md btn-primary btn-move-right" value="Log In"> </input> <span class="login"><a href="#" > Forgot Password?</a></span>
                                    </div>
                                    <div class="col-xs-5 col-lg-5 checkbox text-right" style="margin-top: 0;">
                                        <label class="remember"><input type="checkbox" name="remember" value="{{old('remember')}}"> Remember me</label>
                                    </div>
                                </div>--}}
                            </form>
                        </div>
                    </div>
                    <p class="text-center">An INF-SRD Project. All Rights Reserved 2015.</p>
                </div>
            </div>
        </div>
    </div>
</div>
<!--END OF WRAPPER-->

<!-- jQuery (necessary for Bootstrap's JavaScript plugins) -->
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.2/jquery.min.js"></script>
<!-- Include all compiled plugins (below), or include individual files as needed -->
<script src="<?php echo asset('js/bootstrap.min.js');?>"></script>

</body>
</html>

控制器: (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;
use Illuminate\View\Middleware\ErrorBinder;

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
     */
    private $redirectTo = '/';
    private $maxLoginAttempts = 10;

    /**
     * Create a new authentication controller instance.
     *
     * @return void
     */
    public function __construct()
    {

        $this->middleware('guest', ['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|confirmed|min:6',

        ]);
    }

    /**
     * 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']),
        ]);
    }
}

(AuthenticatesUsers.php)

<?php

namespace Illuminate\Foundation\Auth;

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

trait AuthenticatesUsers
{
    use RedirectsUsers;

    /**
     * Show the application login form.
     *
     * @return \Illuminate\Http\Response
     */
    public function getLogin()
    {
        return $this->showLoginForm();
    }

    /**
     * Show the application login form.
     *
     * @return \Illuminate\Http\Response
     */
    public function showLoginForm()
    {
        if (property_exists($this, 'loginView')) {
            return view($this->loginView);
        }

        if (view()->exists('auth.authenticate')) {
            return view('auth.authenticate');
        }

        return view('auth.login');
    }

    /**
     * Handle a login request to the application.
     *
     * @param  \Illuminate\Http\Request  $request
     * @return \Illuminate\Http\Response
     */
    public function postLogin(Request $request)
    {
        return $this->login($request);
    }

    /**
     * Handle a login request to the application.
     *
     * @param  \Illuminate\Http\Request  $request
     * @return \Illuminate\Http\Response
     */
    public function login(Request $request)
    {
        $this->validate($request, [
            $this->loginUsername() => 'required', 'password' => 'required','captcha'=>'required',
        ]);

        // If the class is using the ThrottlesLogins trait, we can automatically throttle
        // the login attempts for this application. We'll key this by the username and
        // the IP address of the client making these requests into this application.
        $throttles = $this->isUsingThrottlesLoginsTrait();

        if ($throttles && $this->hasTooManyLoginAttempts($request)) {
            return $this->sendLockoutResponse($request);
        }

        $credentials = $this->getCredentials($request);

        if (Auth::guard($this->getGuard())->attempt($credentials, $request->has('remember'))) {
            return $this->handleUserWasAuthenticated($request, $throttles);
        }

        // If the login attempt was unsuccessful we will increment the number of attempts
        // to login and redirect the user back to the login form. Of course, when this
        // user surpasses their maximum number of attempts they will get locked out.
        if ($throttles) {
            $this->incrementLoginAttempts($request);
        }

        return $this->sendFailedLoginResponse($request);
    }

    /**
     * Send the response after the user was authenticated.
     *
     * @param  \Illuminate\Http\Request  $request
     * @param  bool  $throttles
     * @return \Illuminate\Http\Response
     */
    protected function handleUserWasAuthenticated(Request $request, $throttles)
    {
        if ($throttles) {
            $this->clearLoginAttempts($request);
        }

        if (method_exists($this, 'authenticated')) {
            return $this->authenticated($request, Auth::guard($this->getGuard())->user());
        }

        return redirect()->intended($this->redirectPath());
    }

    /**
     * Get the failed login response instance.
     *
     * @param \Illuminate\Http\Request  $request
     * @return \Illuminate\Http\Response
     */
    protected function sendFailedLoginResponse(Request $request)
    {
        return redirect()->back()
            ->withInput($request->only($this->loginUsername(), 'remember'))
            ->withErrors([
                $this->loginUsername() => $this->getFailedLoginMessage(),
            ]);
    }

    /**
     * Get the failed login message.
     *
     * @return string
     */
    protected function getFailedLoginMessage()
    {
        return Lang::has('auth.failed')
                ? Lang::get('auth.failed')
                : 'These credentials do not match our records.';
    }

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

    /**
     * Log the user out of the application.
     *
     * @return \Illuminate\Http\Response
     */
    public function getLogout()
    {
        return $this->logout();
    }

    /**
     * Log the user out of the application.
     *
     * @return \Illuminate\Http\Response
     */
    public function logout()
    {
        Auth::guard($this->getGuard())->logout();

        return redirect(property_exists($this, 'redirectAfterLogout') ? $this->redirectAfterLogout : '/');
    }

    /**
     * Get the login username to be used by the controller.
     *
     * @return string
     */
    public function loginUsername()
    {
        return property_exists($this, 'username') ? $this->username : 'email';
    }

    /**
     * Determine if the class is using the ThrottlesLogins trait.
     *
     * @return bool
     */
    protected function isUsingThrottlesLoginsTrait()
    {
        return in_array(
            ThrottlesLogins::class, class_uses_recursive(get_class($this))
        );
    }

    /**
     * Get the guard to be used during authentication.
     *
     * @return string|null
     */
    protected function getGuard()
    {
        return property_exists($this, 'guard') ? $this->guard : null;
    }
}

【问题讨论】:

  • 检查您是否有带有“验证码”名称的输入元素。 dd(Input::all()) 在 Validator::make 之前,看看你是否在输入中有'captcha'
  • @PradeepSanjaya 我应该把 Validator::make 放在哪里?在 AuthenticatesUser.php 中?
  • 请发布您的表单和控制器操作。
  • 先生。 @PradeepSanjaya 我现在编辑了我的描述

标签: php laravel captcha


【解决方案1】:

可以更好地检查这个包以进行recaptcha

https://github.com/anhskohbo/no-captcha

您可以在验证规则中检查 recapcha

在您的包裹中可以检查例如规则

 $rules = ['captcha' => 'required|captcha'];
            $validator = Validator::make(Input::all(), $rules);
            if ($validator->fails())
            {
                echo '<p style="color: #ff0000;">Incorrect!</p>';
            }
            else
            {
                echo '<p style="color: #00ff30;">Matched :)</p>';
            }

【讨论】:

    猜你喜欢
    • 2016-04-18
    • 1970-01-01
    • 2016-01-22
    • 1970-01-01
    • 2017-07-26
    • 1970-01-01
    • 2022-11-10
    • 1970-01-01
    • 2015-07-26
    相关资源
    最近更新 更多