Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Log failed login attempts with Laravel 5.2

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?

like image 480
user794846 Avatar asked Feb 06 '23 19:02

user794846


1 Answers

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.

like image 171
user794846 Avatar answered Feb 10 '23 08:02

user794846