4
votes

How would I log failed login attempts with laravel 5.2 I have the auth scaffolding installed.

I have added the following to my EventsServiceProvider.php

 protected $listen = [
    'Illuminate\Auth\Events\Attempting' => [
        'App\Listeners\LogAuthenticationAttempt',
    ],

    'Illuminate\Auth\Events\Login' => [
        'App\Listeners\LogSuccessfulLogin',
    ],

    'Illuminate\Auth\Events\Logout' => [
        'App\Listeners\LogSuccessfulLogout',
    ],

    'Illuminate\Auth\Events\Lockout' => [
        'App\Listeners\LogLockout',
    ],
];

And in my app/Listeners/LogAuthenticationAttempt.php

I have

    $log = new Access_Log();
    $log->ip_address = Request::getClientIp();
    $log->is_success = 0;
    $log->save();

But this just logs that an login attempt has been made> I can log a successful login attempt using the LogSuccessfulLogin Listener but I cant see how to log a failed login attempt.

It has occurred to me that I could just update the is_success value on the log entry in the LogSuccessfulLogin Listener but what can I use to persist between LogAuthenticationAttempt and LogSuccessfulLogin to identify this as the same login attempt?

2
It looks like there exists a separate "failed" event, though not in the docs. Might be worth testing, as it seems it would do exactly what you need: laravel.com/api/5.2/Illuminate/Auth/Events/Failed.html - Pevara
I found this. I think not the best aproach, but you can try it: laravel-recipes.com/recipes/220/… - Santiago Mendoza Ramirez
@Pevara You are correct it works fine. Don't understand why this inst in the docs. - user794846
@user794846 good question, Laravel is a great framework, but when it comes to the docs there is room for improvement... - Pevara

2 Answers

8
votes

Turns out there was a failed event it just wasn't in the docs I was following. See Pervara's comment.

I added this to the EventsServiceProvider.php:

    'Illuminate\Auth\Events\Failed' => [
        'App\Listeners\LogFailedAuthenticationAttempt',
    ],

And created app/Listeners/LogFailedAuthenticationAttempt.php with the following code:

     /**
 * Handle the event.
 *
 * @param  Failed  $event
 * @return void
 */
public function handle(Failed $event)
{
    $log = new Access_Log();
    $log->user_id = $event->user->id;
    $log->ip_address = Request::getClientIp();
    $log->event = 'Login Failed';
    $log->is_success = 0;
    $log->save();
}

Works perfectly.

0
votes

You have to first check if the user exists, e.g if($event->user != null){ ...then log }