<?php
// +----------------------------------------------------------------------
// | A3Mall
// +----------------------------------------------------------------------
// | Copyright (c) 2020 http://www.a3-mall.com All rights reserved.
// +----------------------------------------------------------------------
// | Author: xzncit <158373108@qq.com>
// +----------------------------------------------------------------------

namespace app\common\middleware;

use app\common\exception\BaseException;
use Closure;
use app\common\service\Users as UsersService;
use app\common\model\AdminManage as AdminManageModel;
use app\common\model\AdminMenu as AdminMenuModel;
use think\Request;

/**
 * @package app\common\middleware
 * @class Purview
 * @author xzncit 2024-02-01
 */
class Auth extends Base {

    /**
     * @param Request $request
     * @param Closure $next
     * @return mixed|\think\response\Json
     */
    public function handle(Request $request,Closure $next){
        try{
            $controller = $request->controller(true);
            $action     = $request->action(true);
            $commonRole = $this->controller->auth;
            if(!empty($commonRole["except"]) && in_array($action,$commonRole["except"])){
                return $next($request);
            }

            $purview = UsersService::get("purview","-");
            if(empty($purview)){
                throw new BaseException("该操作您无执行权限",402);
            }

            if($purview == "*"){
                return $next($request);
            }

            $condition   = [];
            $condition[] = ["id","in",$purview];
            $condition[] = ["code","=",$controller.'/'.$action];
            if(AdminMenuModel::where($condition)->count()){
                return $next($request);
            }

            throw new BaseException("该操作您无执行权限",402);
        }catch (\Exception $ex){
            throw new BaseException($ex->getMessage(),402);
        }
    }

}