0
votes

I want to create a custom middleware that only if the user is authenticated and the email is a certain email to access the /admin page.

Although, when I specify my custom route and then a redirect it always says too many redirects..

Short Explanation.

  1. User Logs in -> redirected to /home. (Works)
  2. If user tries to access /admin and their email isn't like the one specified in the middleware, redirect to /home.
  3. If its true, let them in /admin

My middleware is called 'admin.verify'

Routes File:

Route::get('/admin', 'AdminController@index')->name('admin.index');

AdminController:

<?php

namespace App\Http\Controllers;

use Illuminate\Http\Request;

class AdminController extends Controller
{
    public function __construct(){
      $this->middleware(['auth', 'admin.verify']);
    }


    public function index(){
      return view('admin.test');
    }
}

Middleware:

 public function handle($request, Closure $next)
    {

      if (Auth::check() && Auth::User()->email == '[email protected]') {
        return $next($request);
      } else {
        return redirect()->route('home');
      }

My Home Route:

 GET|HEAD | home | home| App\Http\Controllers\HomeController@index | web,auth

Home Controller:

class HomeController extends Controller
{
    /**
     * Create a new controller instance.
     *
     * @return void
     */
    public function __construct()
    {
        $this->middleware('auth');
    }

    /**
     * Show the application dashboard.
     *
     * @return \Illuminate\Http\Response
     */
    public function index()
    {
        return view('home');
    }
}
2
Show the definition of your home route.Camilo
Your middleware should be within the Routes file not in the ControllerOption
@Option Why do you say that? Adding a middleware to a controller is valid.Camilo
Added more info to questionPegasus
Where is the auth middleware redirecting to if the user is not authenticated? Could it be that is redirecting to the same home route?Camilo

2 Answers

1
votes

Use $this->middleware ('admin.verify') instead of $this->middleware(['auth, admin.verify]');. You are getting too many redirects error because both the admin middleware and the constructor are checking if the user is authenticated.

0
votes

The problem is that when you access home route auth.verify method is called and when it fails it is redirected to home itself creating a loop hence too many redirects error.

Change else condition in auth.verify middleware to redirect to another page like /login