G
G
Glory2022-01-17 23:51:00
Laravel
Glory, 2022-01-17 23:51:00

How to catch user login via token (laravel passport)?

It is necessary that if the user enters through the token stored in the browser, also catch his entrance.
I am using laravel passport and backend access via api.

To catch the moment when a user logs in with a password, it is enough to use the regular Laravel Passport event and add the code

'Laravel\Passport\Events\AccessTokenCreated' => [
      'App\Listeners\onLogin,
    ],
...


and if the user has already saved the token in the browser, how to catch it?

Alternatively, I created a separate middleware and passed it to

Passport::routes(null, ['middleware' => 'access_log']);


in AuthServiceProvider
but it didn't work. does not enter my middlewar.

and in the routes file it is not convenient to create a common group with this middle var for api.
Is there a generic way?

I just need to check users who have successfully logged in using their token saved in the browser and then do what I need to do ..

This method did not help. DOES NOT go into middleware:

3

I spend my evening thinking about how to do this myself in Laravel 6.

I create a middleware called AccessLogMiddleware
<?php

namespace App\Http\Middleware;

use App\AccessLog;
use App\User;
use Carbon\Carbon;
use Closure;
use Illuminate\Support\Facades\Hash;


class AccessLogMiddleware
{
    public function handle($request, Closure $next)
    {
        if ($request->route()->getName() === 'passport.token'){ //this the route name of the API endpoint to get the token
            $accessLog = new AccessLog([
                'username' => $request->username,
                'ip_address' => $request->getClientIp(),
                'login_time' => Carbon::now(),
            ]);

            $user = User::query()->where([
                'username' => $request->username,
            ])->first();

            if ($user) {
                $accessLog->is_valid_username = 1;
                if (Hash::check($request->password, $user->password)){
                    $accessLog->is_valid_password = 1;
                }
            };

            $accessLog->save();
        }
        return $next($request);
    }
}

Registered it on Http\Kernel
protected $routeMiddleware = [
     'access_log' => \App\Http\Middleware\AccessLogMiddleware::class,
     ....
]

Apply middleware to Passport::routes(), in my case it is in AuthServiceProvider:
Passport::routes(null, ['middleware' => 'access_log']);

Everything is ready!

Answer the question

In order to leave comments, you need to log in

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question