Laravel 4中的角色特定登录

Nav*_*vya 3 authentication role laravel laravel-4

我正在成功登录系统,但我希望角色为"管理员"的用户只能访问所有路由,而具有"管理员"角色的用户可以转到"主页"和"GetDocumentDetails",否则其他登录用户将被限制在主页和访客登录页面.我的路由和过滤文件如下:


路线:

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
});
Run Code Online (Sandbox Code Playgroud)

过滤器:

/* 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('/');
});
Run Code Online (Sandbox Code Playgroud)

cir*_*van 5

我建议使用Zizaco的EntrustConfide软件包,因为它们大大简化了这项任务.

安装两个软件包后,请按照这些页面上的教程进行操作,然后只需定义路径权限过滤器或常规路径过滤器即可限制对某些路径的访问.控制器操作中不需要任何其他逻辑.

这些Route Permission过滤器可以很容易地定义如下:

// 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('/'));
Run Code Online (Sandbox Code Playgroud)

基于权限的路由过滤器如下所示:

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

然后可以将此过滤器应用于任何路线.有关更多示例和功能,请参阅Entrust文档.委托真的是多才多艺.