Policy

Policy(即策略)是在特定模型或者资源中组织授权逻辑的类,用来处理用户授权动作。

组件要求

  • php: ^7.1
  • ext-json: >=1.0
  • easyswoole/spl: ^1.1

安装

composer require easyswoole/policy

仓库地址

easyswlle/policy

使用方法

  1. use EasySwoole\Policy\PolicyNode;
  2. use EasySwoole\Policy\Policy;
  3. //授权动作
  4. //PolicyNode::EFFECT_ALLOW 允许
  5. //PolicyNode::EFFECT_DENY 拒绝
  6. //PolicyNode::EFFECT_UNKNOWN 未知
  7. $policy = new Policy();
  8. //添加节点授权
  9. $policy->addPath('/user/add',PolicyNode::EFFECT_ALLOW);
  10. $policy->addPath('/user/update',PolicyNode::EFFECT_ALLOW);
  11. $policy->addPath('/user/delete',PolicyNode::EFFECT_DENY);
  12. $policy->addPath('/user/*',PolicyNode::EFFECT_DENY);
  13. //验证节点权限
  14. var_dump($policy->check('user/asdasd'));//deny
  15. var_dump($policy->check('user/add')); //allow
  16. var_dump($policy->check('user/update'));//allow
  17. /*
  18. * 允许/api/*,但是唯独拒绝/api/order/charge,/api/order/info,/api/sys/*
  19. */
  20. $policy->addPath('/api/*',PolicyNode::EFFECT_ALLOW);
  21. $policy->addPath('/api/order/charge',PolicyNode::EFFECT_DENY);
  22. $policy->addPath('/api/order/info',PolicyNode::EFFECT_DENY);
  23. $policy->addPath('/api/sys/*',PolicyNode::EFFECT_DENY);
  24. var_dump($policy->check('/api/whatever'));
  25. var_dump($policy->check('/api/order/charge'));
  26. var_dump($policy->check('/api/order/info'));
  27. var_dump($policy->check('/api/sys/whatever'));
  28. //对象添加
  29. $root = new PolicyNode('*');
  30. $userChild = $root->addChild('user');
  31. $userAddChild = $userChild->addChild('add');
  32. $userAddChild->addChild('aaaaaa')->setAllow(PolicyNode::EFFECT_ALLOW);
  33. $userChild->addChild('update')->setAllow(PolicyNode::EFFECT_DENY);
  34. $userChild->addChild('*')->setAllow(PolicyNode::EFFECT_ALLOW);
  35. $apiChild = $root->addChild('charge');
  36. $apiChild->addChild('*');
  37. $node = $root->search('/user/add/aaaa');
  38. if ($node) {
  39. var_dump($node->isAllow());
  40. }

相关仓库

基于Policy组件的后台权限管理demo easyswoole_admin