How can I made login_history feature on laravel app including remember me authentication

34 Views Asked by At

I have a laravel 8.75 project and I made a login_history feature like this :

class LoginEvent
{
    use Dispatchable, InteractsWithSockets, SerializesModels;

    public $id;

    /**
     * Create a new event instance.
     *
     * @return void
     */
    public function __construct($id)
    {
        $this->id = $id;
    }

    /**
     * Get the channels the event should broadcast on.
     *
     * @return \Illuminate\Broadcasting\Channel|array
     */
    public function broadcastOn()
    {
        return new PrivateChannel('channel-name');
    }
}

class LoginListener
{
    /**
     * Create the event listener.
     *
     * @return void
     */
    public function __construct()
    {
        //
    }

    /**
     * Handle the event.
     *
     * @param  object  $event
     * @return void
     */
    public function handle(LoginEvent $event)
    {
        $time = Carbon::now()->toDateTimeString();
        $id = $event->id;
        LoginHistory::create([
            'user_id' => $id,
        ]);
    }
}

And I add the LoginEvent call into App\Http\Requests\Auth\LoginRequest@authenticate :

    public function authenticate()
    {
        $this->ensureIsNotRateLimited();

        if (! Auth::attempt($this->only('email', 'password'), $this->boolean('remember'))) {
            RateLimiter::hit($this->throttleKey());

            throw ValidationException::withMessages([
                'email' => trans('auth.failed'),
            ]);
        }

        $user = Auth::user();

        event(new LoginEvent($user->id));

        RateLimiter::clear($this->throttleKey());
    }

When a user submit the login form and authenticate it inserts correctly into login_history table.

However I have a "remember me" feature and I want to insert into login_history even if the authentication is done with remember token.

How can I do that?

1

There are 1 best solutions below

0
Petitemo On

I succeed with a middleware called on each route web route :


    public function handle(Request $request, Closure $next)
    {
        if(Auth::check() && !Auth::viaRemember()) {
            $user = Auth::user();
            $currentRememberToken = $user->getRememberToken();

            if(!Session::has('remember_me_event_logged')) {

                if($currentRememberToken !== $request->cookie(Auth::getRecallerName())) {
                    Event::dispatch(new LoginEvent($user->id));
                    Session::put('remember_me_event_logged', true);
                }
            }
        }
        return $next($request);
    }
}