Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Location of auth:api Middleware

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
like image 477
Pankaj Avatar asked Dec 11 '18 03:12

Pankaj


People also ask

How do you check authentication in middleware?

try it : if (Auth::check()) { // The user is logged in... } Make sure the StartSessions middleware is enabled before your middleware. If you haven't started sessions before calling Auth::user() , it will return null.

Where is middleware located in Laravel?

All middleware in Laravel are created in the Middleware folder, located inside the `app/HTTP` folder.

What is middleware authentication?

Authentication middleware This middleware checks for a valid identity using the hasIdentity() method of AuthenticationService . If no identity is present, we redirect the redirect configuration value.


1 Answers

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.

like image 187
FGDeveloper Avatar answered Oct 18 '22 04:10

FGDeveloper