审查视图

application/admin/library/Auth.php 17.4 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
use think\Cookie;
10
use think\Hook;
Karson authored
11 12 13 14 15
use think\Request;
use think\Session;

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

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

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

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

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

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

    public function check($name, $uid = '', $relation = 'or', $mode = 'url')
    {
140 141
        $uid = $uid ? $uid : $this->id;
        return parent::check($name, $uid, $relation, $mode);
Karson authored
142 143 144 145 146 147
    }

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

        // 没找到匹配
165
        return false;
Karson authored
166 167 168 169 170 171 172 173 174
    }

    /**
     * 检测是否登录
     *
     * @return boolean
     */
    public function isLogin()
    {
175
        if ($this->logined) {
176 177
            return true;
        }
178
        $admin = Session::get('admin');
179
        if (!$admin) {
180 181 182
            return false;
        }
        //判断是否同一时间同一账号只能在一个地方登录
183
        if (Config::get('fastadmin.login_unique')) {
184
            $my = Admin::get($admin['id']);
185
            if (!$my || $my['token'] != $admin['token']) {
186 187 188
                $this->logined = false; //重置登录状态
                Session::delete("admin");
                Cookie::delete("keeplogin");
189 190 191
                return false;
            }
        }
192 193 194 195 196 197
        //判断管理员IP是否变动
        if (Config::get('fastadmin.loginip_check')) {
            if (!isset($admin['loginip']) || $admin['loginip'] != request()->ip()) {
                $this->logout();
                return false;
            }
198
        }
199
        $this->logined = true;
200
        return true;
Karson authored
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 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247
    }

    /**
     * 获取当前请求的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()
    {
248
        return in_array('*', $this->getRuleIds()) ? true : false;
Karson authored
249 250
    }
Karson authored
251
    /**
252 253 254 255 256 257 258 259
     * 获取管理员所属于的分组ID
     * @param int $uid
     * @return array
     */
    public function getGroupIds($uid = null)
    {
        $groups = $this->getGroups($uid);
        $groupIds = [];
260 261
        foreach ($groups as $K => $v) {
            $groupIds[] = (int)$v['group_id'];
262 263 264 265 266 267 268 269 270 271 272 273 274 275
        }
        return $groupIds;
    }

    /**
     * 取出当前管理员所拥有权限的分组
     * @param boolean $withself 是否包含当前所在的分组
     * @return array
     */
    public function getChildrenGroupIds($withself = false)
    {
        //取出当前管理员所有的分组
        $groups = $this->getGroups();
        $groupIds = [];
276
        foreach ($groups as $k => $v) {
277 278
            $groupIds[] = $v['id'];
        }
279 280 281 282 283 284 285
        $originGroupIds = $groupIds;
        foreach ($groups as $k => $v) {
            if (in_array($v['pid'], $originGroupIds)) {
                $groupIds = array_diff($groupIds, [$v['id']]);
                unset($groups[$k]);
            }
        }
286
        // 取出所有分组
287
        $groupList = \app\admin\model\AuthGroup::where(['status' => 'normal'])->select();
288
        $objList = [];
289
        foreach ($groups as $k => $v) {
290
            if ($v['rules'] === '*') {
291 292 293 294 295 296 297 298 299
                $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 = [];
300
        foreach ($objList as $k => $v) {
301 302
            $childrenGroupIds[] = $v['id'];
        }
303
        if (!$withself) {
304 305 306 307 308 309 310 311 312 313 314 315 316
            $childrenGroupIds = array_diff($childrenGroupIds, $groupIds);
        }
        return $childrenGroupIds;
    }

    /**
     * 取出当前管理员所拥有权限的管理员
     * @param boolean $withself 是否包含自身
     * @return array
     */
    public function getChildrenAdminIds($withself = false)
    {
        $childrenAdminIds = [];
317
        if (!$this->isSuperAdmin()) {
318
            $groupIds = $this->getChildrenGroupIds(false);
319
            $authGroupList = \app\admin\model\AuthGroupAccess::
320 321 322 323
            field('uid,group_id')
                ->where('group_id', 'in', $groupIds)
                ->select();
            foreach ($authGroupList as $k => $v) {
324 325
                $childrenAdminIds[] = $v['uid'];
            }
326
        } else {
327 328
            //超级管理员拥有所有人的权限
            $childrenAdminIds = Admin::column('id');
329
        }
330 331
        if ($withself) {
            if (!in_array($this->id, $childrenAdminIds)) {
332 333
                $childrenAdminIds[] = $this->id;
            }
334
        } else {
335 336 337 338 339 340
            $childrenAdminIds = array_diff($childrenAdminIds, [$this->id]);
        }
        return $childrenAdminIds;
    }

    /**
Karson authored
341 342 343 344 345 346
     * 获得面包屑导航
     * @param string $path
     * @return array
     */
    public function getBreadCrumb($path = '')
    {
347
        if ($this->breadcrumb || !$path) {
Karson authored
348
            return $this->breadcrumb;
349
        }
350 351 352 353 354 355 356 357
        $titleArr = [];
        $menuArr = [];
        $urlArr = explode('/', $path);
        foreach ($urlArr as $index => $item) {
            $pathArr[implode('/', array_slice($urlArr, 0, $index + 1))] = $index;
        }
        if (!$this->rules && $this->id) {
            $this->getRuleList();
Karson authored
358
        }
359 360 361 362 363 364
        foreach ($this->rules as $rule) {
            if (isset($pathArr[$rule['name']])) {
                $rule['title'] = __($rule['title']);
                $rule['url'] = url($rule['name']);
                $titleArr[$pathArr[$rule['name']]] = $rule['title'];
                $menuArr[$pathArr[$rule['name']]] = $rule;
365
            }
366
Karson authored
367
        }
368 369
        ksort($menuArr);
        $this->breadcrumb = $menuArr;
Karson authored
370 371 372 373
        return $this->breadcrumb;
    }

    /**
374
     * 获取左侧和顶部菜单栏
Karson authored
375
     *
376
     * @param array  $params    URL对应的badge数据
377 378
     * @param string $fixedPage 默认页
     * @return array
Karson authored
379
     */
380
    public function getSidebar($params = [], $fixedPage = 'dashboard')
Karson authored
381
    {
382 383
        // 边栏开始
        Hook::listen("admin_sidebar_begin", $params);
Karson authored
384 385 386
        $colorArr = ['red', 'green', 'yellow', 'blue', 'teal', 'orange', 'purple'];
        $colorNums = count($colorArr);
        $badgeList = [];
387
        $module = request()->module();
Karson authored
388
        // 生成菜单的badge
389
        foreach ($params as $k => $v) {
Karson authored
390
            $url = $k;
391
            if (is_array($v)) {
Karson authored
392 393 394
                $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';
395
            } else {
Karson authored
396 397 398 399 400
                $nums = $v;
                $color = $colorArr[(is_numeric($nums) ? $nums : strlen($nums)) % $colorNums];
                $class = 'label';
            }
            //必须nums大于0才显示
401
            if ($nums) {
Karson authored
402 403 404 405 406 407
                $badgeList[$url] = '<small class="' . $class . ' pull-right bg-' . $color . '">' . $nums . '</small>';
            }
        }

        // 读取管理员当前拥有的权限节点
        $userRule = $this->getRuleList();
408 409
        $selected = $referer = [];
        $refererUrl = Session::get('referer');
Karson authored
410
        $pinyin = new \Overtrue\Pinyin\Pinyin('Overtrue\Pinyin\MemoryFileDictLoader');
Karson authored
411
        // 必须将结果集转换为数组
412 413 414 415 416 417 418 419 420 421 422 423
        $ruleList = collection(\app\admin\model\AuthRule::where('status', 'normal')
            ->where('ismenu', 1)
            ->order('weigh', 'desc')
            ->cache("__menu__")
            ->select())->toArray();
        $indexRuleList = \app\admin\model\AuthRule::where('status', 'normal')
            ->where('ismenu', 0)
            ->where('name', 'like', '%/index')
            ->column('name,pid');
        $pidArr = array_filter(array_unique(array_map(function ($item) {
            return $item['pid'];
        }, $ruleList)));
424 425
        foreach ($ruleList as $k => &$v) {
            if (!in_array($v['name'], $userRule)) {
426
                unset($ruleList[$k]);
Karson authored
427
                continue;
428
            }
429 430 431 432 433
            $indexRuleName = $v['name'] . '/index';
            if (isset($indexRuleList[$indexRuleName]) && !in_array($indexRuleName, $userRule)) {
                unset($ruleList[$k]);
                continue;
            }
434
            $v['icon'] = $v['icon'] . ' fa-fw';
Karson authored
435
            $v['url'] = '/' . $module . '/' . $v['name'];
Karson authored
436
            $v['badge'] = isset($badgeList[$v['name']]) ? $badgeList[$v['name']] : '';
Karson authored
437 438
            $v['py'] = $pinyin->abbr($v['title'], '');
            $v['pinyin'] = $pinyin->permalink($v['title'], '');
439
            $v['title'] = __($v['title']);
440
            $selected = $v['name'] == $fixedPage ? $v : $selected;
441
            $referer = url($v['url']) == $refererUrl ? $v : $referer;
442
        }
443 444 445 446 447 448 449 450
        $lastArr = array_diff($pidArr, array_filter(array_unique(array_map(function ($item) {
            return $item['pid'];
        }, $ruleList))));
        foreach ($ruleList as $index => $item) {
            if (in_array($item['id'], $lastArr)) {
                unset($ruleList[$index]);
            }
        }
451 452
        if ($selected == $referer) {
            $referer = [];
Karson authored
453
        }
454 455
        $selected && $selected['url'] = url($selected['url']);
        $referer && $referer['url'] = url($referer['url']);
456
457
        $select_id = $selected ? $selected['id'] : 0;
458 459 460 461 462 463 464 465 466 467 468 469 470 471 472
        $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) {
473 474 475 476 477 478 479 480
                $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"'
                );
481
                $current = in_array($item['id'], $selectParentIds);
482 483
                $url = $childList ? 'javascript:;' : url($item['url']);
                $addtabs = $childList || !$url ? "" : (stripos($url, "?") !== false ? "&" : "?") . "ref=addtabs";
484 485
                $childList = str_replace(
                    '" pid="' . $item['id'] . '"',
Karson authored
486
                    ' ' . ($current ? '' : 'hidden') . '" pid="' . $item['id'] . '"',
487 488
                    $childList
                );
489
                $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>';
490 491 492 493 494
                $menu .= $childList;
            }
        } else {
            // 构造菜单数据
            Tree::instance()->init($ruleList);
495 496 497 498 499 500 501 502
            $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"'
            );
503 504 505 506 507 508
            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>';
            }
509 510
        }
511
        return [$menu, $nav, $selected, $referer];
Karson authored
512 513
    }
514 515 516
    /**
     * 设置错误信息
     *
517
     * @param string $error 错误信息
518
     * @return Auth
519 520 521 522 523 524 525 526 527 528 529 530 531 532 533
     */
    public function setError($error)
    {
        $this->_error = $error;
        return $this;
    }

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