如何在Laravel中分配hasMany角色

时间:2016-06-20 11:43:20

标签: php laravel-5.1

在我的网站

我有一个看起来像是

的InitiatorController
class InitiatorController extends Controller
{

 use ExchangerateTrait;
 public function __construct(){

    $this->middleware('auth');
    $this->middleware('role:sales'); // replace 'collector' with whatever role you need.
}

 public function getIndex(){


            return redirect('initiator/home');
 }

}

现在验证后我正在检查角色中间件中的用户角色是否为sales

我的角色中间件看起来像这样。

class Role
{
    /**
     * Handle an incoming request.
     *
     * @param  \Illuminate\Http\Request  $request
     * @param  \Closure  $next
     * @return mixed
     */
        public function handle($request, Closure $next, $role){

            if ($request->user()->role != $role){

                    if($role=="collector" || $role=="admin" )
                    return Redirect::to('/');  
                    if($role=="director" || $role=="admin" )
                    return Redirect::to('/');  
                    if($role=="admin1" || $role=="admin" )
                    return Redirect::to('/');
                    if($role=="admin2" || $role=="admin" )
                    return Redirect::to('/');
                    if($role=="sales" || $role=="admin" )
                     return Redirect::to('/');
                    if($role=="developer" || $role=="admin" )
                     return Redirect::to('/');


            }

            return $next($request);
        }

}

现在我的角色是director,但他也是销售人员,我该如何解决这个问题。

第一个想法 在控制器

如果我有一些如何将一组角色发送到像这样的中间件

$roles = array('director,sales,teamlead');
$this->middleware('role:$roles');

然后在中间件中我可以检查

if(in_array ($request->user()->role,$roles)){
      //do some thing
}
else
{
   //redirect to login 
}

3 个答案:

答案 0 :(得分:1)

这就是我实施角色中间件的方式:

RoleMiddleware.php

class RoleMiddleware
{
    /**
     * Handle an incoming request.
     *
     * @param  \Illuminate\Http\Request $request
     * @param  \Closure $next
     * @return mixed
     */
    public function handle($request, Closure $next)
    {
        $routeRoles = $this->getRolesForRoute($request->route());
        $user = $request->user();
        if (!$routeRoles || (isset($user) && $user->isPermitted($routeRoles))) {
            return $next($request);
        }
        abort(401);
    }

    /**
     * Function to get the roles of the requested route.
     * 
     * @param \Illuminate\Routing\Route $route
     * @return array|null
     */
    public function getRolesForRoute($route)
    {
        $routeAction = $route->getAction();
        return isset($routeAction['roles']) ? $routeAction['roles'] : null;
    }
}

routes.php文件

Route::get(
            '/post/delete/{pageId}',
            [
                'as' => 'deleteNavigation',
                'uses' => 'NavigationController@postDeleteNavigation',
                'roles' => 'Administrator'
            ]
        );

请注意'角色'可以是数组或字符串

然后在User.php中用户的雄辩模型:

/**
 * Function to check whether this user is permitted
 * a route or not.
 *
 * @param array|string|null $routeRoles Route roles.
 *
 * @return bool
 */
public function isPermitted($routeRoles)
{
    $routeRoles = strtolower($routeRoles);
    if (empty($routeRoles)) {
        return true;
    }

    $userRole = strtolower($this->role()->getResults()->name);
    if (is_array($routeRoles)) {
        foreach ($routeRoles as $routeRole) {
            if ($routeRole == $userRole) {
                return true;
            }
        }
    } else {
        if ($routeRoles == $userRole) {
            return true;
        }
    }

    return false;
}

/**
 * Define an inverse one-to-many relationship.
 *
 * @return \Illuminate\Database\Eloquent\Relations\BelongsTo
 */
public function role()
{
    return $this->belongsTo(Role::class);
}

我知道它与你的逻辑略有不同,但它对我来说很好。希望它有所帮助。

答案 1 :(得分:1)

我和L5.2,但我认为它们之间没有区别。如果我正确理解您的问题,您可以插入多个中间件参数,就像

一样
$this->middleware('role:sales,leader'); //so on separated by commas

如果您使用的是PHP> = 5.6,它会提供我经常使用的新酷炫功能:Variable-length argument list...$roles

对于5.6以下,我猜func_get_args也可能有帮助

然后中间件中的某些东西(也适应我自己破坏的逻辑路由中间件)

/**
 * Handle an incoming request.
 *
 * @param  \Illuminate\Http\Request  $request
 * @param  \Closure  $next
 * @param  array  $roles
 * @return mixed
 */
public function handle($request, Closure $next, ...$roles)
{
    $user = $request->user();

    if ($user && $this->isAllowed($user, $roles)) {
        return $next($request);
    }

    return view('errors.403');
}

继续看到我破碎的逻辑

/**
 * Check if current user role is allowed 
 * 
 * @param  string      $user    current requested user
 * @param  null|array  $roles
 * @return bool
 */
protected function isAllowed($user, $roles)
{
    $roles = $this->extractRoles($roles);

    //Check for role exsistance
    if (! $this->roleExists($roles)) {
        return false;
    }

    //Override this check if user has super privillege
    if ($user->role === $this->superRole()) {
        return true;
    }

    foreach ($roles as $role) {
        if (str_contains($role, $user->role)) {
            return true;
        }  
    }

    return false;
}

/**
 * Convert given roles to an array
 * 
 * @param  null|array  $roles
 * @return array
 */
protected function extractRoles($roles)
{
    $super = $this->superRole();
    foreach($roles as &$role)
        $roles = strtolower($role);

    //if no argument set on middleware return
    //the super role
    return count($roles) == 0 ? [$super] : $roles;
}

/**
 * Check if role is defined in config file
 * 
 * @param  null|array  $roles
 * @return bool
 */
protected function roleExists($roles)
{
    $roleList = config('roles.roles');
    foreach($roleList as &$role)
        $roleList = strtolower($role);

    foreach ($roles as $role) {
        if (in_array($roles, $roleList)) {
            return true;
        }
    }

    return false;
}

/**
 * Set the super privillege role
 * 
 * @return string 
 */
public function superRole()
{
    $super = config('roles.super');

    if (is_array($super)) {
        $super = head($super);
    }

    return (string) strtolower($super);
}

答案 2 :(得分:0)

您可以将模型中的关系定义为函数,并使用该函数检查hasMany角色。

如laravel 5 docs所示

https://laravel.com/docs/5.2/eloquent-relationships#one-to-many