| 12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788 |
- <?php
- namespace App\Http\Middleware\Manager;
- use Closure;
- use Illuminate\Http\Request;
- use App\Models\Manager\AuthRule;
- // 访问权限验证
- class AccessAuth
- {
- // 无需验证的路径
- protected $except = [
- 'manager/login/index',
- ];
- //默认配置
- protected $_config = [
- 'auth_on' => true, // 认证开关
- 'auth_type' => 1, // 认证方式,1为实时认证;2为登录认证。
- 'auth_group' => 'auth_group', // 用户组数据表名
- 'auth_group_access' => 'auth_group_access', // 用户-用户组关系表
- 'auth_rule' => 'auth_rule' // 权限规则表
- ];
- /**
- * $prefix表前缀
- */
- public function __construct()
- {
- // 判断配置
- if (config('AUTH_CONFIG')) {
- //可设置配置项 AUTH_CONFIG, 此配置项为数组。
- $this->_config = array_merge($this->_config, config('AUTH_CONFIG'));
- }
- }
- /**
- * Handle an incoming request.
- *
- * @param \Illuminate\Http\Request $request
- * @param \Closure $next
- * @return mixed
- */
- public function handle(Request $request, Closure $next)
- {
- // 当前路径
- $path = ltrim($request->getPathInfo(), '/');
- // 判断是否需要验证登录
- if (!in_array($path, $this->except)) {
- // 用户ID
- $uid = request('access_token.uid', 0);
- // 如果未登录
- if (!$uid) return json_send(['code' => 'no_login', 'msg' => '请登录账号', 'data' => ['请您登录']]);
- // 如果不是超级管理员
- if (!request('access_token.is_super', 0)) {
- // 进行验证
- if (!$this->check($path, $uid)) return json_send(['code' => 'error', 'msg' => '您没有操作权限', 'data' => ['没有操作权限']]);
- }
- }
- // 返回下一个闭包
- return $next($request);
- }
- /**
- * 检查权限
- * @param name string|array 需要验证的规则列表
- * @param uid int 认证用户的id
- * @return boolean 通过验证返回true;失败返回false
- */
- private function check($path, $uid)
- {
- // 未开启验证,直接通过
- if (!$this->_config['auth_on']) return true;
- // 获取用户需要验证的所有有效规则列表
- $authList = (new AuthRule())->getAuthList($uid, 'manager');
- // 切割path
- $path = explode('/', $path);
- // 没有控制器
- if (count($path) < 2) $path[] = 'index';
- // 没有方法
- if (count($path) < 3) $path[] = 'index';
- // 切割path
- $path = implode('/', $path);
- // 判断是否通过验证
- return in_array($path, $authList);
- }
- }
|