Permissions.php 3.0 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798
  1. <?php
  2. /**
  3. * Created by PhpStorm.
  4. * User: 中闽 < 1464674022@qq.com >
  5. * Date: 2019/12/5
  6. * Time: 17:44
  7. */
  8. namespace app\admin\controller\base;
  9. use app\admin\model\Urlconfig;
  10. use app\common\behavior\AdminLogBehavior;
  11. use app\common\service\WebService;
  12. use think\Controller;
  13. use think\Db;
  14. use think\Hook;
  15. use think\Session;
  16. class Permissions extends Controller
  17. {
  18. const ADMIN_ID = 'admin';
  19. const ADMIN_NAME = 'admin_name';
  20. const ADMIN_CATE_ID = 'admin_cate_id';
  21. protected function _initialize()
  22. {
  23. (new WebService())->checkInstalled();
  24. Hook::listen('admin_log');
  25. if ($this->request->isCli()) {
  26. return;
  27. }
  28. //检查ip黑名单
  29. $black_ip = \app\common\model\Webconfig::getValue('black_ip', 3600);
  30. if (!empty($black_ip)) {
  31. $black_ip = explode(',', $black_ip);
  32. $ip = $this->request->ip();
  33. if (in_array($ip, $black_ip)) {
  34. //退出登录
  35. if (Session::has(self::ADMIN_ID)) {
  36. Session::delete(self::ADMIN_ID);
  37. }
  38. $this->error('你已被封禁!', 'admin/common/login');
  39. }
  40. }
  41. //检查是否登录
  42. if (!Session::has(self::ADMIN_ID)) {
  43. if ((new Urlconfig())->isWeekBackend()) {
  44. $this->redirect('admin/common/login');
  45. } else {
  46. abort(404, '404 not found');
  47. }
  48. }
  49. //检查访问的url是否再用户的权限范围内,mysql查询自动忽略了大小写
  50. $where['module'] = $this->request->module();
  51. $where['controller'] = $this->request->controller();
  52. $where['function'] = $this->request->action();
  53. $where['type'] = 1;//权限节点
  54. //用户的权限菜单id
  55. $menus = Db::name('admin_cate')->where('id', Session::get(self::ADMIN_CATE_ID))->value('permissions');
  56. $menus = explode(',', $menus);
  57. $string = $this->request->query();
  58. $param_menu = Db::name('admin_menu')->where($where)->where('parameter', $string)->find();
  59. if ($param_menu) {
  60. if (false == in_array($param_menu['id'], $menus)) {
  61. (new AdminLogBehavior())->updateLastLog("缺少权限");
  62. $this->error('缺少权限');
  63. }
  64. } else if ($string) {
  65. $menu = Db::name('admin_menu')->where($where)->where('parameter', '')->find();
  66. if ($menu && !in_array($menu['id'], $menus)) {
  67. (new AdminLogBehavior())->updateLastLog("缺少权限");
  68. $this->error('缺少权限');
  69. }
  70. }
  71. if ($this->request->has('check_permission')) {
  72. $this->success('has permission');
  73. }
  74. }
  75. /**
  76. * 查询当前用户权限
  77. * @return array|mixed 菜单id数组
  78. */
  79. public function getPermission()
  80. {
  81. //用户的权限菜单id
  82. $menus = Db::name('admin_cate')->where('id', Session::get(self::ADMIN_CATE_ID))->value('permissions');
  83. $menus = explode(',', $menus);
  84. return $menus;
  85. }
  86. }