简体   繁体   English

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

[英]check user rights to do something

i am creating user permissions on laravel. 我在laravel上创建用户权限。 In my DB i have table with id/user_id/model/write/read/delete 在我的数据库中,我有ID / user_id / model / write / read / delete的表

last three permission is enum type: on and off. 最后三个权限是枚举类型:打开和关闭。

in my User model im wrote method to set: 在我的用户模型中,im编写了设置方法:

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();
        }
    }

in permission model im write: 在权限模型中我写道:

 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');
    }

}

ok, i have the method how to set permission from setting form. 好的,我有方法如何从设置表单设置权限。 Now i need to check the right if the user have permission write or read, delete and do somehting like this: 现在,我需要检查用户是否具有写或读,删除以及类似操作权限:

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

Please help me how to select from DB permissions and check user right with hasRight method. 请帮助我如何从数据库权限中选择并使用hasRight方法检查用户权限。

i think that need to check if user permissions from DB is in array. 我认为需要检查数据库中的用户权限是否在数组中。 How this should look? 这应该看起来如何?

and maybe can you tiny code of my setPermission method? 也许可以给我我的setPermission方法的小代码? thank u 感谢你

// 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();
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM