Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

routing issue #50

Closed
han-huang opened this issue Dec 26, 2016 · 8 comments
Closed

routing issue #50

han-huang opened this issue Dec 26, 2016 · 8 comments

Comments

@han-huang
Copy link

han-huang commented Dec 26, 2016

I found a routing issue.
e.g. http://domain.app:8016/admin/home (not login yet) -> http://domain.app:8016/login
The correct redirecting url is /admin/login , not /login.

I modify the following code. It can redirect correct url and fix auth.blade.php.

app/Providers/RouteServiceProvider.php

    protected function mapAdminRoutes()
    {
        Route::group([
-            'middleware' => ['web', 'admin', 'auth:admin'],
+            'middleware' => ['web', 'admin'],
            'prefix' => 'admin',
            'as' => 'admin.',
            'namespace' => $this->namespace,
        ], function ($router) {
            require base_path('routes/admin.php');
        });
    }

resources/views/admin/layout/auth.blade.php

                 <!-- Right Side Of Navbar -->
                 <ul class="nav navbar-nav navbar-right">
                     <!-- Authentication Links -->
-                    @if (Auth::guest())
+                    @if (Auth::guard('admin')->guest())
                         <li><a href="{{ url('/admin/login') }}">Login</a></li>
                         <li><a href="{{ url('/admin/register') }}">Register</a></li>
                     @else
                         <li class="dropdown">
                             <a href="#" class="dropdown-toggle" data-toggle="dropdown" role="button" aria-expanded="false">
-                                {{ Auth::user()->name }} <span class="caret"></span>
+                                {{ Auth::guard('admin')->user()->name }} <span class="caret"></span>
                             </a>

I hope this is useful.

@ghost
Copy link

ghost commented Dec 26, 2016

I'm using both the native Laravel auth and hesto's multi-auth. Would this work for me?

@ankurk91
Copy link

@han-huang

Add these lines to your unauthenticated function in app/Exceptions/Handler.php

// This is a workaround
        if ($request->is('admin/*')) {
            return redirect()->guest('/admin/login');
        }

Above lines should come before return redirect()->guest('/login');

@han-huang
Copy link
Author

@ankurk91

I want to explain my opinion .
It should execute redirect('admin/login') in app/Http/Middleware/RedirectIfNotAdmin.php, but it doesn't.
I think it would be better to fix in multi-auth:install command , not to add workround.
Thanks.

app/Http/Middleware/RedirectIfNotAdmin.php

<?php

namespace App\Http\Middleware;

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

class RedirectIfNotAdmin
{
        /**
         * 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 = 'admin')
        {
            if (!Auth::guard($guard)->check()) {
                return redirect('admin/login');
            }

            return $next($request);
        }
}

@han-huang
Copy link
Author

Difference between 'middleware' => ['web', 'admin', 'auth:admin'] and 'middleware' => ['web', 'admin']

Add Exception to Debug

  • app/Exceptions/Handler.php
    protected function unauthenticated($request, AuthenticationException $exception)
    {
        if ($request->expectsJson()) {
            return response()->json(['error' => 'Unauthenticated.'], 401);
        }

+        throw new \Exception("forDebug", 1);
        return redirect()->guest('login');
    }
  • app/Http/Middleware/RedirectIfNotAdmin.php
    public function handle($request, Closure $next, $guard = 'admin')
    {
        if (!Auth::guard($guard)->check()) {
+            throw new \Exception("forDebug", 1); 
            return redirect('admin/login');
        }

        return $next($request);
    }

Compare information of debug, find out the division of runtime

  • 'middleware' => ['web', 'admin', 'auth:admin'] :

    • at Pipeline->handleException(object(Request), object(AuthenticationException)) in Pipeline.php line 35
  • 'middleware' => ['web', 'admin'] :

    • at Pipeline->Illuminate\Pipeline{closure}(object(Request)) in Pipeline.php line 33
  • vendor/laravel/framework/src/Illuminate/Routing/Pipeline.php
    protected function getSlice()
    {
        return function ($stack, $pipe) {
            return function ($passable) use ($stack, $pipe) {
                try {
                    $slice = parent::getSlice();
                    $callable = $slice($stack, $pipe);

                    return $callable($passable);  //line 33
                } catch (Exception $e) {
                    return $this->handleException($passable, $e);  //line 35
                } catch (Throwable $e) {
                    return $this->handleException($passable, new FatalThrowableError($e));
                }
            };
        };
    }

@ankurk91
Copy link

ankurk91 commented Dec 29, 2016

@han-huang
I manually applied your patch into my application and it worked.
No workaround required.
Now i can access admin user like this -

# get logged-in user email
auth('admin')->user()->email

# check if admin use is logged-in
auth('admin')->check()

Don't know if this is correct way.

@Hesto
Is it possible to remove auth:admin from middle-ware array?
This change was introduced in v1.0.6.
Is there any caveats ?

PS: This issue is related to #29

@han-huang
Copy link
Author

@ankurk91

I think it is ok.
https://laravel.com/docs/5.3/helpers#method-auth

Or you can use Auth::guard('admin')->user()->email .

@chamamme
Copy link

In other not for your changes to interfere with other packages such as Bouncer its will be better to edit you your Authenticate class in app/Http/Middleware to this

namespace App\Http\Middleware;

use Illuminate\Auth\Middleware\Authenticate as Middleware;

class Authenticate extends Middleware
{
    /**
     * Get the path the user should be redirected to when they are not authenticated.
     *
     * @param  \Illuminate\Http\Request  $request
     * @return string
     */
    protected function redirectTo($request)
    {
        if ($request->is('admin/*')) {
            return route('admin.login');
        }
        return route('login');
    }
}

Thanks you !

@AdmiinX
Copy link

AdmiinX commented Feb 24, 2019

this fix worked for me
removed auth:admin from middleware array
app\Providers\RouteServiceProvider.php

Route::group([
    'middleware' => ['web', 'admin'],
    'prefix' => 'admin',
    'as' => 'admin.',
    'namespace' => $this->namespace,
], function ($router) {
    require base_path('routes/admin.php');
});

changed the middleware admin to handle authentication and redirect
app/Http/Middleware/RedirectIfNotAdmin.php

use Illuminate\Auth\Middleware\Authenticate as Middleware;
use Closure;

class RedirectIfNotAdmin extends Middleware
{
    /**
     * Handle an incoming request.
     *
     * @param  \Illuminate\Http\Request  $request
     * @param  \Closure  $next
     * @param  string[]  ...$guards
     * @return mixed
     *
     * @throws \Illuminate\Auth\AuthenticationException
     */
    public function handle($request, Closure $next, ...$guards)
    {
        $this->authenticate($request, ['admin']);
        return $next($request);
    }

   /**
     * Get the path the user should be redirected to when they are not authenticated.
     *
     * @param  \Illuminate\Http\Request  $request
     * @return string
     */
    protected function redirectTo($request)
    {
        if (!$request->expectsJson()) {
            return route('admin.login');
        }
    }
}

so any route use the middleware admin will be authenticate with the admin guard and if failed will be redirect to route('admin.login')
for more info check Authenticate class

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

5 participants