Question

I am logging in the system successfully but I want that the user whose role is 'Administrator' can only go to all the routes and user having role as 'Manager' can go to 'Home' and 'GetDocumentDetails' else the other login users will be restricted to home page and the guest to Login page. My route and filter files are as follows:


Routes:

Route::post('/login', function()
{
    $user = array(
    'username' => Input::get('username'),
    'password' => Input::get('password'));
    // verify user credentials  
    if (Auth::attempt($user,true))
    {   
        $role= Auth::user()->userrole;
        return Redirect::route('home');
    }
}
// Route for getting document details using get method
Route::get('GetDocumentDetailsById',array('as'=>'GetDocumentDetailsById','uses'=>'DocumentController@GetDocumentDetailsById'));

// Route for guest user 
Route::filter('guest', function()
{
    if (Auth::check()) 
    return Redirect::route('home')->with('flash_notice', 'You are already logged in!');
    // Redirect Log-in user to his home page
});

Filters:

/* Filter to redirect guest user to login page */
Route::filter('auth', function()
{
    $role=Auth::user();
    if (Auth::guest()) return Redirect::guest('login');
});


Route::filter('auth.basic', function()
{
    return Auth::basic('username');
});

Route::filter('guest', function()
{
    if (Auth::check()) return Redirect::to('/');
});
Was it helpful?

Solution

I would recommend using Zizaco's Entrust and Confide packages for this purpose, as they greatly simplify this task.

Follow the tutorials on these pages after installing both packages, and then you can limit access to certain routes just by defining Route Permission filters or regular Route filters. No need for any additional logic in controller actions.

These Route Permission filters can easily be defined like this:

// Any route under admin is only accessible by users with role Admin.
// Redirect happens if user doesn't have this role.

Entrust::routeNeedsRole('admin*', 'Admin', Redirect::to('/'));

A Route filter based on permissions would look like this:

Route::filter('myFilter', function()
{
    if (!Entrust::can('get_document_details') )
    {
        return Redirect::to('/');
    }
});

This filter could then be applied to any route. See the Entrust documentation for more examples and features. Entrust is really versatile.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top