mabyassine
mabyassine

Reputation: 11

Multi Auth Laravel 5.4 using two middleware only

I want to create two middleware to redirect the authenticated user, if it is an admin it will be redirected to the backoffice otherwise it will be redirected to a simple dashboard for simple users.

But I want to use only the users table without adding another table for the admins.

RedirectIfAuthenticated.php

<?php

 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)
{
    if (Auth::guard($guard)->check()) {
        if (Auth::user()->role_id == 1)
        {
            return redirect('/admin/home');
        }
        return redirect('/dashboard');
    }

    return $next($request);
}
}

DashboardController.php

class DashboardController extends Controller
{

/**
 * Display a listing of the resource.
 *
 * @return \Illuminate\Http\Response
 */
public function index()
{
    return view('authFront.layoutAuthenticatedUser.dashboard');
}


}

web.php

    Route::get('/us-admin', function () { return redirect('/admin/home');    })->name('admin.dashboard');

   // Authentication Routes...
   $this->get('login',    'Auth\LoginController@showLoginForm')->name('auth.login');
    $this->post('login', 'Auth\LoginController@login')->name('auth.login');
   $this->post('register', 'Auth\RegisterController@register')->name('auth.register');

   $this->post('logout', 'Auth\LoginController@logout')->name('auth.logout');


   // Change Password Routes...
   $this->get('change_password',   'Auth\ChangePasswordController@showChangePasswordForm')->name('auth.change_password');
   $this->patch('change_password', 'Auth\ChangePasswordController@changePassword')->name('auth.change_password');

   // Password Reset Routes...
   $this->get('password/reset', 'Auth\ForgotPasswordController@showLinkRequestForm')->name('auth.password.reset');
   $this->post('password/email', 'Auth\ForgotPasswordController@sendResetLinkEmail')->name('auth.password.reset');
  $this->get('password/reset/{token}', 'Auth\ResetPasswordController@showResetForm')->name('password.reset');
  $this->post('password/reset', 'Auth\ResetPasswordController@reset')->name('auth.password.reset');

   Route::group(['middleware' => ['auth'], 'prefix' => 'admin', 'as' => 'admin.'], function () {
    Route::get('/home', 'HomeController@index');

});
   Route::get('/dashboard', 'DashboardController@index');

Upvotes: 0

Views: 895

Answers (2)

Adeeb basheer
Adeeb basheer

Reputation: 1490

You can simply check roles in RedirectIfAuthenticated middleware which do already exist by default and restrict the routes by creating an admin middleware

In app/Http/Middleware/RedirectIfAuthenticated.php

<?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)
    {
        if (Auth::guard($guard)->check()) {
            if (Auth::user()->role_id == 1)
            {
                return redirect('/admin/home');    
            }
            return redirect('/dashboard');
        }

        return $next($request);
    }
}

In app/Http/Middleware/AuthenticateAdmin.php

<?php

namespace App\Http\Middleware;

use Closure;
use Auth;

class AuthenticateAdmin
{
    /**
     * Handle an incoming request.
     *
     * @param  \Illuminate\Http\Request  $request
     * @param  \Closure  $next
     * @return mixed
     */
    public function handle($request, Closure $next)
    {
        if (!Auth::check() || Auth::user()->role_id != 1)
        {
            if ($request->ajax())
            {
                return response('Unauthorized.', 401);
            }
            else
            {
                return redirect()->guest('login');
            }
        }
        return $next($request);
    }
}

In app/Http/Kernal.php add this line in $routeMiddleware array

'admin' => \App\Http\Middleware\AuthenticateAdmin::class,

In routes/web.php

Route::middleware('admin')->prefix('admin')->group(function() {
    Route::get('/home', 'HomeController@index')->name('admin.home');
});

In app/Http/Controllers/Auth/LoginController.php add this function

protected function authenticated(Request $request, $user)
{
    if ($user->role_id == 1) {
        return redirect()->intended(route('admin.home'));
    }
    return redirect()->intended(route('dashboard'));
}   

Hope this helps you

Upvotes: 0

user320487
user320487

Reputation:

You need to establish user roles in this case, or have an optional boolean field on the users table for is_admin. Then in middleware it would simply be something like:

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 = null)
    {
        if (!Auth::user()->admin()) {
            return redirect()->to('user-dashboard');
        }
        return $next($request);
    }
}

So in your case I would create a separate middleware for each role post-authorization. Then you would apply AdminMiddleware to all routes prefixed with 'admin', SimpleUserMiddleware to all other routes, for example.

Upvotes: 1

Related Questions