Location of auth:api Middleware

Pankaj picture Pankaj · Dec 11, 2018 · Viewed 9.7k times · Source

Can somebody please tell the location of auth:api middleware?

As per the auth:api middleware, the api routes are protected by not null users.

I have a boolean field in user table called Is_Admin_Url_Accessible. I want to add a condition in the auth:api middleware for some routes to make user that only those user access such routes whoever are permitted to access the admin area.

I checked the class here but could not help.

\app\Http\Middleware\Authenticate.php

Answer

FGDeveloper picture FGDeveloper · Dec 19, 2018

You can add a middleware that makes control user accessible, and you can set it as middleware to your route group like auth:api

Please run php artisan make:middleware UserAccessible on your terminal.

After run above artisan command, you will see generated a file named UserAccessible.php in the App/Http/Middleware folder.

UserAccessible.php Contents

    namespace App\Http\Middleware;

    use Closure;
    use Illuminate\Support\Facades\Auth;

    class UserAccessible
    {
        /**
         * Handle an incoming request.
         *
         * @param  \Illuminate\Http\Request  $request
         * @param  \Closure  $next
         * @return mixed
         */
        public function handle($request, Closure $next)
        {
            $user = Auth::user();

            if(!$user->accesible){
                // redirect page or error.
            }

            return $next($request);
        }
    }

Then, you must define a route middleware via App/Http/Kernel.php

Kernel.php Contents

    /**
     * The application's route middleware.
     *
     * These middleware may be assigned to groups or used individually.
     *
     * @var array
     */
    protected $routeMiddleware = [
        ...
        'user_accessible' => \App\Http\Middleware\UserAccessible::class
    ];

And finally, you can define route middleware to your route group;

api.php Contents

    Route::group(['middleware' => ['auth:api', 'user_accessible']], function () {
        // your protected routes.
    });

I hope this solve your problem.