审查视图

application/admin/library/Auth.php 15.0 KB
Karson authored
1 2 3 4 5 6
<?php

namespace app\admin\library;

use app\admin\model\Admin;
use fast\Random;
Karson authored
7
use fast\Tree;
8
use think\Config;
Karson authored
9 10 11 12 13 14
use think\Cookie;
use think\Request;
use think\Session;

class Auth extends \fast\Auth
{
15
    protected $_error = '';
Karson authored
16
    protected $requestUri = '';
Karson authored
17
    protected $breadcrumb = [];
18
    protected $logined = false; //登录状态
Karson authored
19 20 21 22 23 24 25 26 27 28 29

    public function __construct()
    {
        parent::__construct();
    }

    public function __get($name)
    {
        return Session::get('admin.' . $name);
    }
30 31
    /**
     * 管理员登录
32
     *
33 34
     * @param   string $username 用户名
     * @param   string $password 密码
35
     * @param   int    $keeptime 有效时长
36 37
     * @return  boolean
     */
Karson authored
38 39 40
    public function login($username, $password, $keeptime = 0)
    {
        $admin = Admin::get(['username' => $username]);
41
        if (!$admin) {
42
            $this->setError('Username is incorrect');
Karson authored
43 44
            return false;
        }
45 46 47 48
        if ($admin['status'] == 'hidden') {
            $this->setError('Admin is forbidden');
            return false;
        }
49
        if (Config::get('fastadmin.login_failure_retry') && $admin->loginfailure >= 10 && time() - $admin->updatetime < 86400) {
50
            $this->setError('Please try again after 1 day');
51 52
            return false;
        }
53
        if ($admin->password != md5(md5($password) . $admin->salt)) {
Karson authored
54 55
            $admin->loginfailure++;
            $admin->save();
56
            $this->setError('Password is incorrect');
Karson authored
57 58 59 60 61 62
            return false;
        }
        $admin->loginfailure = 0;
        $admin->logintime = time();
        $admin->token = Random::uuid();
        $admin->save();
63
        Session::set("admin", $admin->toArray());
Karson authored
64 65 66 67 68 69 70 71 72 73
        $this->keeplogin($keeptime);
        return true;
    }

    /**
     * 注销登录
     */
    public function logout()
    {
        $admin = Admin::get(intval($this->id));
74
        if (!$admin) {
Karson authored
75 76 77 78
            return true;
        }
        $admin->token = '';
        $admin->save();
79
        $this->logined = false; //重置登录状态
Karson authored
80 81 82 83 84 85 86 87 88 89 90 91
        Session::delete("admin");
        Cookie::delete("keeplogin");
        return true;
    }

    /**
     * 自动登录
     * @return boolean
     */
    public function autologin()
    {
        $keeplogin = Cookie::get('keeplogin');
92
        if (!$keeplogin) {
Karson authored
93 94 95
            return false;
        }
        list($id, $keeptime, $expiretime, $key) = explode('|', $keeplogin);
96
        if ($id && $keeptime && $expiretime && $key && $expiretime > time()) {
Karson authored
97
            $admin = Admin::get($id);
98
            if (!$admin || !$admin->token) {
Karson authored
99 100 101
                return false;
            }
            //token有变更
102
            if ($key != md5(md5($id) . md5($keeptime) . md5($expiretime) . $admin->token)) {
Karson authored
103 104
                return false;
            }
105
            Session::set("admin", $admin->toArray());
Karson authored
106 107 108
            //刷新自动登录的时效
            $this->keeplogin($keeptime);
            return true;
109
        } else {
Karson authored
110 111 112 113 114 115
            return false;
        }
    }

    /**
     * 刷新保持登录的Cookie
116
     *
117
     * @param   int $keeptime
118
     * @return  boolean
Karson authored
119 120 121
     */
    protected function keeplogin($keeptime = 0)
    {
122
        if ($keeptime) {
Karson authored
123 124 125
            $expiretime = time() + $keeptime;
            $key = md5(md5($this->id) . md5($keeptime) . md5($expiretime) . $this->token);
            $data = [$this->id, $keeptime, $expiretime, $key];
126
            Cookie::set('keeplogin', implode('|', $data), 86400 * 30);
Karson authored
127 128 129 130 131 132 133 134 135 136 137 138 139 140
            return true;
        }
        return false;
    }

    public function check($name, $uid = '', $relation = 'or', $mode = 'url')
    {
        return parent::check($name, $this->id, $relation, $mode);
    }

    /**
     * 检测当前控制器和方法是否匹配传递的数组
     *
     * @param array $arr 需要验证权限的数组
141
     * @return bool
Karson authored
142 143 144 145 146
     */
    public function match($arr = [])
    {
        $request = Request::instance();
        $arr = is_array($arr) ? $arr : explode(',', $arr);
147
        if (!$arr) {
148
            return false;
Karson authored
149 150
        }
151
        $arr = array_map('strtolower', $arr);
Karson authored
152
        // 是否存在
153
        if (in_array(strtolower($request->action()), $arr) || in_array('*', $arr)) {
154
            return true;
Karson authored
155 156 157
        }

        // 没找到匹配
158
        return false;
Karson authored
159 160 161 162 163 164 165 166 167
    }

    /**
     * 检测是否登录
     *
     * @return boolean
     */
    public function isLogin()
    {
168
        if ($this->logined) {
169 170
            return true;
        }
171
        $admin = Session::get('admin');
172
        if (!$admin) {
173 174 175
            return false;
        }
        //判断是否同一时间同一账号只能在一个地方登录
176
        if (Config::get('fastadmin.login_unique')) {
177
            $my = Admin::get($admin['id']);
178
            if (!$my || $my['token'] != $admin['token']) {
179 180 181
                return false;
            }
        }
182
        $this->logined = true;
183
        return true;
Karson authored
184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230
    }

    /**
     * 获取当前请求的URI
     * @return string
     */
    public function getRequestUri()
    {
        return $this->requestUri;
    }

    /**
     * 设置当前请求的URI
     * @param string $uri
     */
    public function setRequestUri($uri)
    {
        $this->requestUri = $uri;
    }

    public function getGroups($uid = null)
    {
        $uid = is_null($uid) ? $this->id : $uid;
        return parent::getGroups($uid);
    }

    public function getRuleList($uid = null)
    {
        $uid = is_null($uid) ? $this->id : $uid;
        return parent::getRuleList($uid);
    }

    public function getUserInfo($uid = null)
    {
        $uid = is_null($uid) ? $this->id : $uid;

        return $uid != $this->id ? Admin::get(intval($uid)) : Session::get('admin');
    }

    public function getRuleIds($uid = null)
    {
        $uid = is_null($uid) ? $this->id : $uid;
        return parent::getRuleIds($uid);
    }

    public function isSuperAdmin()
    {
231
        return in_array('*', $this->getRuleIds()) ? true : false;
Karson authored
232 233
    }
Karson authored
234
    /**
235 236 237 238 239 240 241 242
     * 获取管理员所属于的分组ID
     * @param int $uid
     * @return array
     */
    public function getGroupIds($uid = null)
    {
        $groups = $this->getGroups($uid);
        $groupIds = [];
243 244
        foreach ($groups as $K => $v) {
            $groupIds[] = (int)$v['group_id'];
245 246 247 248 249 250 251 252 253 254 255 256 257 258
        }
        return $groupIds;
    }

    /**
     * 取出当前管理员所拥有权限的分组
     * @param boolean $withself 是否包含当前所在的分组
     * @return array
     */
    public function getChildrenGroupIds($withself = false)
    {
        //取出当前管理员所有的分组
        $groups = $this->getGroups();
        $groupIds = [];
259
        foreach ($groups as $k => $v) {
260 261 262
            $groupIds[] = $v['id'];
        }
        // 取出所有分组
263
        $groupList = \app\admin\model\AuthGroup::where(['status' => 'normal'])->select();
264
        $objList = [];
265 266
        foreach ($groups as $K => $v) {
            if ($v['rules'] === '*') {
267 268 269 270 271 272 273 274 275
                $objList = $groupList;
                break;
            }
            // 取出包含自己的所有子节点
            $childrenList = Tree::instance()->init($groupList)->getChildren($v['id'], true);
            $obj = Tree::instance()->init($childrenList)->getTreeArray($v['pid']);
            $objList = array_merge($objList, Tree::instance()->getTreeList($obj));
        }
        $childrenGroupIds = [];
276
        foreach ($objList as $k => $v) {
277 278
            $childrenGroupIds[] = $v['id'];
        }
279
        if (!$withself) {
280 281 282 283 284 285 286 287 288 289 290 291 292
            $childrenGroupIds = array_diff($childrenGroupIds, $groupIds);
        }
        return $childrenGroupIds;
    }

    /**
     * 取出当前管理员所拥有权限的管理员
     * @param boolean $withself 是否包含自身
     * @return array
     */
    public function getChildrenAdminIds($withself = false)
    {
        $childrenAdminIds = [];
293
        if (!$this->isSuperAdmin()) {
294
            $groupIds = $this->getChildrenGroupIds(false);
295
            $authGroupList = \app\admin\model\AuthGroupAccess::
296 297 298
            field('uid,group_id')
                ->where('group_id', 'in', $groupIds)
                ->select();
299
300
            foreach ($authGroupList as $k => $v) {
301 302
                $childrenAdminIds[] = $v['uid'];
            }
303
        } else {
304 305
            //超级管理员拥有所有人的权限
            $childrenAdminIds = Admin::column('id');
306
        }
307 308
        if ($withself) {
            if (!in_array($this->id, $childrenAdminIds)) {
309 310
                $childrenAdminIds[] = $this->id;
            }
311
        } else {
312 313 314 315 316 317
            $childrenAdminIds = array_diff($childrenAdminIds, [$this->id]);
        }
        return $childrenAdminIds;
    }

    /**
Karson authored
318 319 320 321 322 323
     * 获得面包屑导航
     * @param string $path
     * @return array
     */
    public function getBreadCrumb($path = '')
    {
324
        if ($this->breadcrumb || !$path) {
Karson authored
325
            return $this->breadcrumb;
326
        }
Karson authored
327
        $path_rule_id = 0;
328
        foreach ($this->rules as $rule) {
Karson authored
329 330
            $path_rule_id = $rule['name'] == $path ? $rule['id'] : $path_rule_id;
        }
331
        if ($path_rule_id) {
Karson authored
332
            $this->breadcrumb = Tree::instance()->init($this->rules)->getParents($path_rule_id, true);
333
            foreach ($this->breadcrumb as $k => &$v) {
334
                $v['url'] = url($v['name']);
335
                $v['title'] = __($v['title']);
336
            }
Karson authored
337 338 339 340 341
        }
        return $this->breadcrumb;
    }

    /**
342
     * 获取左侧和顶部菜单栏
Karson authored
343
     *
344
     * @param array  $params    URL对应的badge数据
345 346
     * @param string $fixedPage 默认页
     * @return array
Karson authored
347
     */
348
    public function getSidebar($params = [], $fixedPage = 'dashboard')
Karson authored
349 350 351 352
    {
        $colorArr = ['red', 'green', 'yellow', 'blue', 'teal', 'orange', 'purple'];
        $colorNums = count($colorArr);
        $badgeList = [];
353
        $module = request()->module();
Karson authored
354
        // 生成菜单的badge
355
        foreach ($params as $k => $v) {
Karson authored
356
            $url = $k;
357
            if (is_array($v)) {
Karson authored
358 359 360
                $nums = isset($v[0]) ? $v[0] : 0;
                $color = isset($v[1]) ? $v[1] : $colorArr[(is_numeric($nums) ? $nums : strlen($nums)) % $colorNums];
                $class = isset($v[2]) ? $v[2] : 'label';
361
            } else {
Karson authored
362 363 364 365 366
                $nums = $v;
                $color = $colorArr[(is_numeric($nums) ? $nums : strlen($nums)) % $colorNums];
                $class = 'label';
            }
            //必须nums大于0才显示
367
            if ($nums) {
Karson authored
368 369 370 371 372 373
                $badgeList[$url] = '<small class="' . $class . ' pull-right bg-' . $color . '">' . $nums . '</small>';
            }
        }

        // 读取管理员当前拥有的权限节点
        $userRule = $this->getRuleList();
374 375
        $selected = $referer = [];
        $refererUrl = Session::get('referer');
Karson authored
376
        $pinyin = new \Overtrue\Pinyin\Pinyin('Overtrue\Pinyin\MemoryFileDictLoader');
Karson authored
377
        // 必须将结果集转换为数组
378
        $ruleList = collection(\app\admin\model\AuthRule::where('status', 'normal')->where('ismenu', 1)->order('weigh', 'desc')->cache("__menu__")->select())->toArray();
379 380
        foreach ($ruleList as $k => &$v) {
            if (!in_array($v['name'], $userRule)) {
381
                unset($ruleList[$k]);
Karson authored
382
                continue;
383
            }
384
            $v['icon'] = $v['icon'] . ' fa-fw';
Karson authored
385
            $v['url'] = '/' . $module . '/' . $v['name'];
Karson authored
386
            $v['badge'] = isset($badgeList[$v['name']]) ? $badgeList[$v['name']] : '';
Karson authored
387 388
            $v['py'] = $pinyin->abbr($v['title'], '');
            $v['pinyin'] = $pinyin->permalink($v['title'], '');
389
            $v['title'] = __($v['title']);
390
            $selected = $v['name'] == $fixedPage ? $v : $selected;
391
            $referer = url($v['url']) == $refererUrl ? $v : $referer;
392 393 394
        }
        if ($selected == $referer) {
            $referer = [];
Karson authored
395
        }
396 397
        $selected && $selected['url'] = url($selected['url']);
        $referer && $referer['url'] = url($referer['url']);
398
399
        $select_id = $selected ? $selected['id'] : 0;
400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416
        $menu = $nav = '';
        if (Config::get('fastadmin.multiplenav')) {
            $topList = [];
            foreach ($ruleList as $index => $item) {
                if (!$item['pid']) {
                    $topList[] = $item;
                }
            }
            $selectParentIds = [];
            $tree = Tree::instance();
            $tree->init($ruleList);
            if ($select_id) {
                $selectParentIds = $tree->getParentsIds($select_id, true);
            }
            foreach ($topList as $index => $item) {
                $childList = Tree::instance()->getTreeMenu($item['id'], '<li class="@class" pid="@pid"><a href="@url@addtabs" addtabs="@id" url="@url" py="@py" pinyin="@pinyin"><i class="@icon"></i> <span>@title</span> <span class="pull-right-container">@caret @badge</span></a> @childlist</li>', $select_id, '', 'ul', 'class="treeview-menu"');
                $current = in_array($item['id'], $selectParentIds);
417 418
                $url = $childList ? 'javascript:;' : url($item['url']);
                $addtabs = $childList || !$url ? "" : (stripos($url, "?") !== false ? "&" : "?") . "ref=addtabs";
419
                $childList = str_replace('" pid="' . $item['id'] . '"', ' treeview ' . ($current ? '' : 'hidden') . '" pid="' . $item['id'] . '"', $childList);
420
                $nav .= '<li class="' . ($current ? 'active' : '') . '"><a href="' . $url . $addtabs . '" addtabs="' . $item['id'] . '" url="' . $url . '"><i class="' . $item['icon'] . '"></i> <span>' . $item['title'] . '</span> <span class="pull-right-container"> </span></a> </li>';
421 422 423 424 425 426
                $menu .= $childList;
            }
        } else {
            // 构造菜单数据
            Tree::instance()->init($ruleList);
            $menu = Tree::instance()->getTreeMenu(0, '<li class="@class"><a href="@url@addtabs" addtabs="@id" url="@url" py="@py" pinyin="@pinyin"><i class="@icon"></i> <span>@title</span> <span class="pull-right-container">@caret @badge</span></a> @childlist</li>', $select_id, '', 'ul', 'class="treeview-menu"');
427 428 429 430 431 432
            if ($selected) {
                $nav .= '<li role="presentation" id="tab_' . $selected['id'] . '" class="' . ($referer ? '' : 'active') . '"><a href="#con_' . $selected['id'] . '" node-id="' . $selected['id'] . '" aria-controls="' . $selected['id'] . '" role="tab" data-toggle="tab"><i class="' . $selected['icon'] . ' fa-fw"></i> <span>' . $selected['title'] . '</span> </a></li>';
            }
            if ($referer) {
                $nav .= '<li role="presentation" id="tab_' . $referer['id'] . '" class="active"><a href="#con_' . $referer['id'] . '" node-id="' . $referer['id'] . '" aria-controls="' . $referer['id'] . '" role="tab" data-toggle="tab"><i class="' . $referer['icon'] . ' fa-fw"></i> <span>' . $referer['title'] . '</span> </a> <i class="close-tab fa fa-remove"></i></li>';
            }
433 434
        }
435
        return [$menu, $nav, $selected, $referer];
Karson authored
436 437
    }
438 439 440
    /**
     * 设置错误信息
     *
441
     * @param string $error 错误信息
442
     * @return Auth
443 444 445 446 447 448 449 450 451 452 453 454 455 456 457
     */
    public function setError($error)
    {
        $this->_error = $error;
        return $this;
    }

    /**
     * 获取错误信息
     * @return string
     */
    public function getError()
    {
        return $this->_error ? __($this->_error) : '';
    }
Karson authored
458
}