检查用户权限以执行某些操作

时间:2015-03-05 20:54:52

标签: php laravel-4

我在laravel上创建用户权限。在我的数据库中,我有id / user_id / model / write / read / delete

的表

最后三个权限是枚举类型:打开和关闭。

在我的用户模型中我写了设置方法:

protected $models   = ['dashboard', 'preferences'];  

public function setPermissions($input=false)             
    {
        foreach($this->models as $model) {
            $read   = (isset($input[$model]['read']) ? 'on' : 'off');
            $write  = (isset($input[$model]['write']) ? 'on' : 'off');
            $delete = (isset($input[$model]['delete']) ? 'on' : 'off');

            $perms          = Permissions::firstOrNew([
                'user_id'   => $this->id,
                'model'     => $model,
            ]);

            $perms->read    = $read;
            $perms->write   = $write;
            $perms->delete  = $delete;
            $perms->save();
        }
    }

在权限模型中我写道:

 use Illuminate\Database\Eloquent\SoftDeletingTrait;

class Permissions extends Eloquent {

    use SoftDeletingTrait;

    protected $table    = 'user_permissions';
    protected $fillable = ['user_id', 'model', 'read', 'write', 'delete'];

    public function user() 
    {
        return $this->belongsTo('User','user_id','id');
    }

}

好的,我有如何从设置表单设置权限的方法。现在我需要检查权限,如果用户有权限写或读,删除并做这样的事情:

if (Auth::user->hasRights('write', 'delete'))
          //do something

请帮我看看如何从数据库权限中选择并使用hasRight方法检查用户权限。

我认为需要检查来自DB的用户权限是否在数组中。这应该怎么样?

也许你的setPermission方法的代码很小吗?谢谢你

1 个答案:

答案 0 :(得分:0)

// in User model
public function hasRights(...$accessLevels)
{
    return ! $this->permissions()->filter(function (Permissions $p) use ($accessLevels) {
        foreach ($accessLevels as $access) {
            if ( ! $p->{$access}) return false;
        }
        return true;
    })->isEmpty();
}