Auth.php 2.3 KB

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