Login throttles in laravel 5.1 with ajax

- 1 answer

Ad

I'm working on a login form which uses ajax and I can't setup login throttling. ThrottlesLogins trait redirects somewhere but I don't need that. How can I return number of seconds when user fails password n times? Controller:

<?php

namespace App\Http\Controllers\Login;

use Illuminate\Http\Request;

use App\Http\Requests;
use App\Http\Controllers\Controller;
use Illuminate\Foundation\Auth\ThrottlesLogins;
use Illuminate\Foundation\Auth\AuthenticatesAndRegistersUsers;
use Auth;

class LoginController extends Controller
{
    use AuthenticatesAndRegistersUsers, ThrottlesLogins;

    public function index()
    {
        if (Auth::check()) return redirect(url('/dashboard'));
        else return view('admin.login');
    }

    public function login(Request $request) {
        $this->validate($request, [
            'username' => 'required', 'password' => 'required',
        ]);

        $credentials = $request->only('username', 'password');

        $throttles = $this->isUsingThrottlesLoginsTrait();

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

        if (Auth::attempt($credentials, $request->has('remember')))
        {
            return $this->handleUserWasAuthenticated($request, $throttles);
            //return response()->json(['code' => 1, 'redirect' => url('/dashboard')]);
        }
        //else return response()->json(['code' => 0]);

        if ($throttles) {
            $this->incrementLoginAttempts($request);
        }
    }
}

routes.php

/* Login */
Route::group(array('prefix' => 'login', 'namespace' => 'Login', 'middleware' => 'guest'), function() {
    Route::get('/', '[email protected]');
    Route::post('/', '[email protected]');
});
Ad

Answer

Ad

You can change:

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

into

if ($throttles && $this->hasTooManyLoginAttempts($request)) {
    if ($request->ajax()) {
        return response()->json(['lockout_time' => $this->lockoutTime()]);
    }
    else {
       return $this->sendLockoutResponse($request);
    }
}
Ad
source: stackoverflow.com
Ad