1
votes

I have a three logins with three different view and routes. whenever i hit a localhost:8080/admin/login its shows error ERR_TOO_MANY_REDIRECTS. when i hit admin/ for dashboard its successfully redirects me to admin/login.

In AdminController when i replace $this->middleware('auth:admin'); with $this->middleware('guest:admin'); in __constructor function, redirects problem gets solved but when i go to admin/home it does't redirect to admin/login.

I am using latest laravel 5.7.xx and i am not using its inbuild auth view. Its my customized.

config/auth.php code

'guards' => [
        'web' => [
            'driver' => 'session',
            'provider' => 'users',
        ],
        'api' => [
            'driver' => 'token',
            'provider' => 'users',
        ],

        'admin' => [
            'driver' => 'session',
            'provider' => 'admins',
        ],
        'admin-api' => [
            'driver' => 'token',
            'provider' => 'admins',
        ],

        'trainer' => [
            'driver' => 'session',
            'provider' => 'trainer',
        ],
        'trainer-api' => [
            'driver' => 'token',
            'provider' => 'trainer',
        ],
    ],

'providers' => [
        'users' => [
            'driver' => 'eloquent',
            'model' => App\User::class,
        ],
        'admins' => [
            'driver' => 'eloquent',
            'model' => App\Admin::class,
        ],
        'trainer' => [
            'driver' => 'eloquent',
            'model' => App\Trainer::class,
        ],

        // 'users' => [
        //     'driver' => 'database',
        //     'table' => 'users',
        // ],
    ],

'passwords' => [
        'users' => [
            'provider' => 'users',
            'table' => 'password_resets',
            'expire' => 60,
        ],
        'admins' => [
            'provider' => 'admins',
            'table' => 'password_resets',
            'expire' => 60,
        ],
        'trainer' => [
            'provider' => 'trainer',
            'table' => 'password_resets',
            'expire' => 60,
        ],
    ],

app/Admin.php

<?php

namespace App;

use Illuminate\Notifications\Notifiable;
use Illuminate\Contracts\Auth\MustVerifyEmail;
use Illuminate\Foundation\Auth\User as Authenticatable;

class Admin extends Authenticatable
{
    use Notifiable;

    protected $guard = 'admin';

    /**
     * The attributes that are mass assignable.
     *
     * @var array
     */
    protected $fillable = [
        'name', 'email', 'password',
    ];

    /**
     * The attributes that should be hidden for arrays.
     *
     * @var array
     */
    protected $hidden = [
        'password', 'remember_token',
    ];
}

Below is my Exceptions/Handler.php code

<?php

namespace App\Exceptions;

use Exception;
use Illuminate\Foundation\Exceptions\Handler as ExceptionHandler;

use Request;
use Illuminate\Auth\AuthenticationException;
use Response;

class Handler extends ExceptionHandler
{
    /**
     * A list of the exception types that are not reported.
     *
     * @var array
     */
    protected $dontReport = [
        //
    ];

    /**
     * A list of the inputs that are never flashed for validation exceptions.
     *
     * @var array
     */
    protected $dontFlash = [
        'password',
        'password_confirmation',
    ];

    /**
     * Report or log an exception.
     *
     * @param  \Exception  $exception
     * @return void
     */
    public function report(Exception $exception)
    {
        parent::report($exception);
    }

    /**
     * Render an exception into an HTTP response.
     *
     * @param  \Illuminate\Http\Request  $request
     * @param  \Exception  $exception
     * @return \Illuminate\Http\Response
     */
    public function render($request, Exception $exception)
    {
        return parent::render($request, $exception);
    }

    public function unauthenticated($request, AuthenticationException $exception)
    {
        if ($request->expectsJson()) {
            return response()->json(['error' => 'Unauthenticated.'], 401);
        }

        $guard = array_get($exception->guards(),0);

        switch ($guard) {
            case 'admin':
                $login = 'admin.login';
                break;
            case 'trainer':
                $login = 'trainer.login';
                break;
            case 'user':
                $login = 'user.login';
                break;
            default:
                $login = 'laravel';
                break;
        }

        return redirect()->guest(route($login));
    }
}

Http/Controllers/AdminController.php code

<?php

namespace App\Http\Controllers;

use Illuminate\Http\Request;
// use Illuminate\Support\Facades\Auth;
use Auth;
use Validator;

class AdminController extends Controller
{
    public function __construct()
    {
        $this->middleware('auth:admin');
    }

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

    // admin login
    public function login(Request $requests)
    {
        // Validate the form data
        $this->validate($request, [
            'email' => 'required|email',
            'password' => 'required'
        ]);

        // Attempt to log the user in
        if(Auth::guard('admin')->attempt(['email' => $request->email,'password' => $request->password,'usertype' => 1,'status' => 1])){
            // if success
            return redirect()->intended(route('admin.home'));
        }

        // if failed
        return redirect()->back()->withInput($request->only('email'));
    }

    // admin logout
    public function logout()
    {
        Auth::guard('admin')->logout();
        return redirect()->intended(route('admin.login'));
    }

    // base
    public function base()
    {
        return view('admin.base');
    }

    // dashboard
    public function home()
    {
        return view('admin.home');
    }
}

Http/Middleware/RedirectIfAuthenticated.php code

<?php

namespace App\Http\Middleware;

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

class RedirectIfAuthenticated
{
    /**
     * Handle an incoming request.
     *
     * @param  \Illuminate\Http\Request  $request
     * @param  \Closure  $next
     * @param  string|null  $guard
     * @return mixed
     */
    public function handle($request, Closure $next, $guard = null)
    {
        switch ($guard) {
            case 'admin':
                if (Auth::guard($guard)->check()) {
                    return redirect(route('admin.home'));
                }
                break;
            case 'trainer':
                if (Auth::guard($guard)->check()) {
                    return redirect(route('trainer.home'));
                }
                break;
            case 'user':
                if (Auth::guard($guard)->check()) {
                    return redirect(route('user.home'));
                }
                break;
            default:
                return redirect(route('laravel'));
                break;
        }

        return $next($request);
    }
}

routes/web.php

Auth::routes();

/* Admin */
Route::prefix('admin')->group(function(){
    Route::get('/login','AdminController@index')->name('admin.login');
    // Route::post('/login','AdminController@login')->name('admin.login.submit');
    // Route::post('/logout','AdminController@logout')->name('admin.logout');
    Route::get('/base','AdminController@base')->name('admin.base');
    Route::get('/','AdminController@home')->name('admin.home');
});

/* Trainer */
Route::prefix('trainer')->group(function(){
    Route::get('/login','TrainerController@index')->name('trainer.login');
    Route::post('/login','TrainerController@login')->name('trainer.login.submit');
    Route::post('/logout','TrainerController@logout')->name('trainer.logout');
    Route::get('/base','TrainerController@base')->name('trainer.base');
    Route::get('/','TrainerController@home')->name('trainer.home');
});
1
You code is redirecting to often. For example you're accessing admin/login.php but it redirects you to user/login.php which redirects you to /login.php and so on.Sebastian Waldbauer
@SebastianWaldbauer What should i do? Where should i change the code so it does't redirect too many times. And i will have three different login page like admin/login for Admins, trainer/login for Trainers and may be /login for usersAavin
In Exceptions/Handler.php you redirect all unauthed clients to custom routes. But in Http/Controllers/AdminController.php you redirect them again. Checked your input data? Check your routes. How you can login right now? Does this only happens after initial login?Sebastian Waldbauer
@SebastianWaldbauer As i have said i am stuck on admin/login page because of too many redirects error, I am unable to check if login functionality is working or not.Aavin
Replace in Http/Controllers/AdminController.php following return redirect()->intended(route('admin.home')); to echo "Login correct!";Sebastian Waldbauer

1 Answers

0
votes

The reason is because of the $this->middleware('auth:admin') you dedicated the whole AdminController for authenticated users. So, when you hit the admin url the app keeps redirecting forth and back. To fix this add the except method to the middleware to exclude the index method from middle ware protection. It Should be $this->middleware('auth:admin')->except(['index']);