Laravel 5中的多个auth用户类型

时间:2015-02-25 19:58:52

标签: php authentication laravel-5

如何将auth用户组分成3组,我需要管理员,客户端和工作组。

以下是auth用户的路线:

Route::group(['middleware' => 'auth'], function(){

    Route::get('home', array(
        'as' => 'home',
        'uses'  => 'HomeController@index'
        ));


    Route::get('logout', array(
       'as' => 'logout',
       'uses' => 'UserController@logout'
    ));


});

1 个答案:

答案 0 :(得分:4)

我已经编写了一个可以进行基本角色身份验证的中间件,正如您所描述的那样。

Route::get('home', [
     'middleware' => ['auth', 'roles'], //use the roles middleware
     'uses' => 'HomeController@index',
     'roles' => ['admin', 'client'] // only admin and client roles are allowed
]);

说明

在App \ Http \ Middleware中,创建一个名为“CheckRole.php”的文件

<?php namespace App\Http\Middleware;
// First copy this file into your middleware directoy
use Closure;
class CheckRole{
/**
* Handle an incoming request.
*
* @param \Illuminate\Http\Request $request
* @param \Closure $next
* @return mixed
*/
public function handle($request, Closure $next)
{
    // Get the required roles from the route
    $roles = $this->getRequiredRoleForRoute($request->route());
    // Check if a role is required for the route, and
    // if so, ensure that the user has that role.
    if($request->user()->hasRole($roles) || !$roles)
    {
        return $next($request);
    }
    return response([
        'error' => [
        'code' => 'INSUFFICIENT_ROLE',
        'description' => 'You are not authorized to access this  resource.'
    ]
    ], 401);
    }
    private function getRequiredRoleForRoute($route)
    {
        $actions = $route->getAction();
        return isset($actions['roles']) ? $actions['roles'] : null;
    }
} 

在内核中,启用“角色”中间件:

protected $routeMiddleware = [
    'auth' => 'App\Http\Middleware\Authenticate',
    'auth.basic' => 'Illuminate\Auth\Middleware\AuthenticateWithBasicAuth',
    'guest' => 'App\Http\Middleware\RedirectIfAuthenticated',
    'roles' => 'App\Http\Middleware\CheckRole',
]; 

您还需要设置一个角色表,其中包含一些角色数据,然后将关系分配给用户模型上的角色。

完整代码可在此处找到:https://gist.github.com/amochohan/8cb599ee5dc0af5f4246

希望这有帮助。