Home > database >  Why doesn't this dashboard route follow my middleware logic?
Why doesn't this dashboard route follow my middleware logic?

Time:02-22

I am working on a Laravel 8 app that uses Microsoft Azure for user management (login included).

I began by following this tutorial on their website.

I have these routes "under" the dashboard route, that I want to protect with a piece of custom middleware:

// Dashboard routes
Route::get('/dashboard', [DashboardContoller::class, 'index'])->name('dashboard');

Route::group(['prefix' => 'dashboard' , 'middleware' => ['checkSignedIn']], function() {
    Route::get('/users', [UsersContoller::class, 'index']);
    Route::get('/create-user', [UsersContoller::class, 'create']);
    Route::get('/delete-user/{id}', [UsersContoller::class, 'delete']);
});

The conditions for a user to be allowed to the application's dashboard are:

  1. They sign in with a valid Microsoft account

  2. Their email is inside an aray of alowed emails:

    private $allowedEmails = [
        '[email protected]',
        '[email protected]',
        '[email protected]',
    ];
    

For this purpose, I have done the flollowing:

Created a CheckSignedIn middleware, with php artisan make:middleware CheckSignedIn.

Registered the above middleware in app\Http\Kernel.php:

protected $routeMiddleware = [
    // More middleware
    'checkSignedIn' => \App\Http\Middleware\CheckSignedIn::class,
];

In app\Http\Middleware\CheckSignedIn.php I have:

namespace App\Http\Middleware;
use Closure;
use Illuminate\Http\Request;

class CheckSignedIn {
/**
 * Handle an incoming request.
 *
 * @param  \Illuminate\Http\Request  $request
 * @param  \Closure(\Illuminate\Http\Request): (\Illuminate\Http\Response|\Illuminate\Http\RedirectResponse)  $next
 * @return \Illuminate\Http\Response|\Illuminate\Http\RedirectResponse
 */

private $allowedEmails = [
    '[email protected]',
    '[email protected]',
    '[email protected]',
];


public function handle(Request $request, Closure $next) {
  $isSignedIn = null !== session('userName') && in_array(session('userEmail'), $this->allowedEmails);
  
      if (!$isSignedIn) {
          return redirect('/');
      }
      
      return $next($request);
    }
}

The problem

Evan if I am not logged in I can still see the dashboard (the /dashboard route).

Shouldn't this line deal with the /dashboard route too?

Route::group(['prefix' => 'dashboard' , 'middleware' => ['checkSignedIn']], function() {

What am I doing wrong?

CodePudding user response:

Change your routes like this:


// Dashboard routes
Route::group(['prefix' => 'dashboard', 'middleware' => ['checkSignedIn']], function() {
    Route::get('/', [DashboardContoller::class, 'index'])->name('dashboard');
    Route::get('/users', [UsersContoller::class, 'index']);
    Route::get('/create-user', [UsersContoller::class, 'create']);
    Route::get('/delete-user/{id}', [UsersContoller::class, 'delete']);
});

  • Related