Auth.php 2.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113
  1. <?php
  2. namespace common\helpers;
  3. use common\enums\StatusEnum;
  4. use common\models\rbac\AuthItem;
  5. use Yii;
  6. /**
  7. * Class Auth
  8. * @package common\helpers
  9. * @author qimall
  10. */
  11. class Auth
  12. {
  13. protected static $auth = [];
  14. /**
  15. * 校验权限
  16. *
  17. * @param string $route
  18. * @param array $defaultAuth
  19. * @return bool
  20. * @throws \yii\web\UnauthorizedHttpException
  21. */
  22. public static function verify(string $route, $defaultAuth = [])
  23. {
  24. if (Yii::$app->services->auth->isSuperAdmin()) {
  25. return true;
  26. }
  27. // if (Yii::$app->services->rbacAuthRole->isMallAdmin() && strpos($route, 'admin/') === false) return true;
  28. if(empty($route)) return false;
  29. $route = trim($route);
  30. //没有写入权限列表的,不验证
  31. $res = AuthItem::findOne(['name'=>$route,'status'=>StatusEnum::ENABLED]);
  32. if(empty($res)) return true;
  33. $auth = !empty($defaultAuth) ? $defaultAuth : self::getAuth();
  34. if (
  35. in_array('/*', $auth) ||
  36. in_array('*', $auth) ||
  37. in_array($route, $auth) ||
  38. in_array(Url::to([$route]), $auth)
  39. ) {
  40. return true;
  41. }
  42. return self::multistageCheck($route, $auth);
  43. }
  44. /**
  45. * 过滤自己拥有的权限
  46. *
  47. * @param array $route
  48. * @return array
  49. * @throws \yii\web\UnauthorizedHttpException
  50. */
  51. public static function verifyBatch(array $route)
  52. {
  53. if (Yii::$app->services->auth->isSuperAdmin()) {
  54. return $route;
  55. }
  56. return array_intersect(self::getAuth(), $route);
  57. }
  58. /**
  59. * 支持通配符 *
  60. *
  61. * 例如:
  62. * /goods/*
  63. * /goods/index/*
  64. *
  65. * @param string $route 权限名称
  66. * @param array $auth 所有权限组
  67. * @param string $separator 分隔符
  68. * @return bool
  69. */
  70. public static function multistageCheck($route, array $auth, $separator = '/')
  71. {
  72. $key = $separator;
  73. $routeArr = explode($separator, $route);
  74. foreach ($routeArr as $value) {
  75. if (!empty($value)) {
  76. $key .= $value . $separator;
  77. if (in_array($key . '*', $auth)) {
  78. return true;
  79. }
  80. }
  81. }
  82. return false;
  83. }
  84. /**
  85. * 获取权限信息
  86. *
  87. * @return array
  88. * @throws \yii\web\UnauthorizedHttpException
  89. */
  90. public static function getAuth()
  91. {
  92. if (self::$auth) {
  93. return self::$auth;
  94. }
  95. $role = Yii::$app->services->rbacAuthRole->getRole();
  96. self::$auth = Yii::$app->services->rbacAuthItemChild->getAuthByRole($role, Yii::$app->id);
  97. return self::$auth;
  98. }
  99. }