Eric Evans Eric Evans - 3 months ago 24
Ajax Question

Ajax successful when laravel authentication fails

I have a problem I have two forms on regular form and one ajax processed form. The regular form works as needed but the ajax form passes as successful even when authentication of the server side fells.

My loginHandler function is below

public function handleLogin(Request $request) {

// init auth boolean to false
$auth = false;

// run validation rules
$validator = User::validation($request->all(), User::$login_validation_rules, User::$login_error_messages);

// get credentials
$credentials = $request->only('email','password');

if($validator->fails()) {
return back()
->withErrors($validator)
->withInput();
}

$credentials = array_merge($credentials,['activated' => 1]);

// get remember from request
$remember = $request->has('remember');


if (\Auth::attempt($credentials, $remember)) {
$auth = true;
}

if($request->ajax()) {
$response = response()->json([
'auth' => $auth,
'intended' => \URL::route('home')
]);

return $response;
}

return redirect()->intended('/');

}


My ajax code is this

$('#login-nav').validate({
rules : {
email : {
required : true,
email : true
},
password : {
required : true
}
},
messages : {
email : {
required : '<div class="alert-danger alert-validation">Email is a required field.</div>',
email : '<div class="alert-danger alert-validation">Please enter a valid Email.</div>'
},
password : {
required : '<div class="alert-danger alert-validation">Password is a required field.</div>'
}
},
submitHandler: function (form){
$.ajax({
headers: {
'X-CSRF-TOKEN': $('meta[name="_token"]').attr('value')
},
type: $(form).attr('method'),
url: $(form).attr('action'),
data: $(form).serialize(),
dataType: 'json',
success: function (data) {
var html = '<div class="alert alert-success">Login Successful</div>';
$('#loginMsg').html(html);
return window.location = '/';
},
error: function (data) {
var html = '<div class="alert alert-danger">Email/Password is invalid</div>';
$('#loginMsg').html(html);
}
});

return false;
}


I would like to have the same behavior as my regular non ajax form. but instead of going to error in my ajax it's going to success. Any help would be greatly appreciated.

Answer

Auth::attempt will return you true or false, by default if you return a response()->json() without the 2nd parameter, it will be default to 200 (success). So based on the Auth::attempt you should either return 400 if it fails to login, then it should go into your ajax's error function.

$auth = \Auth::attempt($credentials, $remember);

if($request->ajax()) {
    $responseCode = 200;
    if( ! $auth) {
       $responseCode = 400;
    }
    $response = response()->json([
        'auth' => $auth,
        'intended' => \URL::route('home')
    ], $responseCode);

    return $response;
}