0

I want to auto redirect to dashboard page by pass login page if client ip address are match ip address 192.168.1.154. But in my Dashboard page i already put session by Auth

My Middleware in kernel:

protected $routeMiddleware = [
        'auth' => \Illuminate\Auth\Middleware\Authenticate::class,
        'auth.basic' => \Illuminate\Auth\Middleware\AuthenticateWithBasicAuth::class,
        'bindings' => \Illuminate\Routing\Middleware\SubstituteBindings::class,
        'can' => \Illuminate\Auth\Middleware\Authorize::class,
        'guest' => \App\Http\Middleware\RedirectIfAuthenticated::class,
        'throttle' => \Illuminate\Routing\Middleware\ThrottleRequests::class,           
        'ipcheck' => \App\Http\Middleware\IpMiddleware::class,
    ];

My IpMiddleware code:

<?php

namespace App\Http\Middleware;

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

class IpMiddleware
{
    /**
     * Handle an incoming request.
     *
     * @param  \Illuminate\Http\Request $request
     * @param  \Closure $next
     * @return mixed
     */
    public function handle($request, Closure $next)
    {
        // $ip = \Request::ip();
        if ($request->ip() == "192.168.1.154") {               
            return redirect('home');
        }
        return $next($request);
    }
}

My Route login:

Route::get('/', ['middleware' => ['ipcheck'], function () {
    return view('auth.login');
}]);

My Route home:

Route::get('home', function () {

    if (Auth::guest()) {
        return back()->withInput();
    } else (Auth::user()->role_id == 1) {

        return view('dashboard');
    } 

});

i got an error :

This webpage has a redirect loop

ERR_TOO_MANY_REDIRECTS

What can i do now?

The Rock
  • 393
  • 3
  • 12
  • 29

1 Answers1

3

You need to make auto login/session in you middleware not in dashboard

Let say if you want autologin for id 1 then it should be like this

public function handle($request, Closure $next)
{
// $ip = \Request::ip();
    if ($request->ip() == "192.168.1.154") {               
        $user_id = 1;//
        Auth::loginUsingId($user_id);
        return redirect('home');
    }
    return $next($request);
}

In your home route your check Auth which true for guest not for logged in user so it again redirect to auth.login because auth.login has middleware to redirect to home then home check for guest or Auth ..... and its make cicle and you got error

This webpage has a redirect loop

ERR_TOO_MANY_REDIRECTS

Niklesh Raut
  • 34,013
  • 16
  • 75
  • 109