Auth.php 2.5 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798
  1. <?php
  2. namespace app\common\logic;
  3. use think\Db;
  4. /**
  5. * mg权限认证类
  6. */
  7. class Auth
  8. {
  9. //默认配置
  10. protected $_config = [];
  11. public function __construct()
  12. {
  13. }
  14. /**
  15. * 检查权限
  16. * @param $name string|array 需要验证的规则列表,支持逗号分隔的权限规则或索引数组
  17. * @param $uid int 认证用户的id
  18. * @param $relation string 如果为 'or' 表示满足任一条规则即通过验证;如果为 'and'则表示需满足所有规则才能通过验证
  19. * @return boolean 通过验证返回true;失败返回false
  20. */
  21. public function check($uid, $name, $relation = 'or')
  22. {
  23. if (empty($uid)) {
  24. return false;
  25. }
  26. if ($uid == 1) {
  27. return true;
  28. }
  29. if (is_string($name)) {
  30. $name = strtolower($name);
  31. if (strpos($name, ',') !== false) {
  32. $name = explode(',', $name);
  33. } else {
  34. $findAuthRuleCount = Db::name('nw_admin_auth_rule')->where([
  35. 'auth_name' => $name
  36. ])->count();
  37. if ($findAuthRuleCount == 0) {//没有规则时,失败!
  38. //return false;
  39. return true;
  40. }
  41. }
  42. }
  43. $list = []; //保存验证通过的规则名
  44. $roleInfo = Db::name('nw_admin_role_user')
  45. ->alias("a")
  46. ->join('nw_admin_role b', 'a.role_id = b.id')
  47. ->where(["a.user_id" => $uid, "b.status" => 1])
  48. ->column("role_id, auth_ids");
  49. // if (in_array(1, $groups)) {
  50. // return true;
  51. // }
  52. // $groups = array_keys($roleInfo);
  53. $authIds = array_values($roleInfo);
  54. $uniqueAuthIdsTemp = [];
  55. foreach ($authIds as $ids) {
  56. $idsArr = explode(',', $ids);
  57. foreach ($idsArr as $id) {
  58. array_push($uniqueAuthIdsTemp, $id);
  59. }
  60. }
  61. $uniqueAuthIds = array_unique($uniqueAuthIdsTemp);
  62. // if (empty($groups)) {
  63. // return false;
  64. // }
  65. if (empty($uniqueAuthIds)) {
  66. return false;
  67. }
  68. $rules = Db::name('nw_admin_auth_rule')
  69. ->where(["id" => ["in", $uniqueAuthIds]])
  70. ->select();
  71. foreach ($rules as $rule) {
  72. if (strtolower($rule['auth_name']) === strtolower($name) ) {
  73. return true;
  74. }
  75. }
  76. return false;
  77. }
  78. }