<?php
// +----------------------------------------------------------------------
// | onezan-admin 快速开发的管理平台
// +----------------------------------------------------------------------
// | 官方网址：https://www.onezan.cn
// +----------------------------------------------------------------------
// | onezan团队 版权所有 开源版本可自由商用
// +----------------------------------------------------------------------
// | Author: 543885307@qq.com
// +----------------------------------------------------------------------
namespace app\middleware;

use app\model\AdminUser;
use app\service\domain\admin\CoreAdminPermissionService;


/**
 * 后台权限校验中间件
 * 校验管理员是否具备指定权限
 * @package app\middleware
 */
class AdminPermission
{
    /**
     * 处理权限校验
     * @param mixed $request
     * @param \Closure $next
     * @param string|null $permission 所需权限标识
     * @return mixed
     */
    public function handle($request, \Closure $next, $permission = null)
    {
        $uid = $request->uid ?? null;
        if (!$uid) {
            return json(['code' => 401, 'msg' => ''], 401);
        }

        $user = AdminUser::find($uid);
        if (!$user || (int)($user->status ?? 0) !== 1) {
            return json(['code' => 403, 'msg' => ''], 403);
        }

        if (!$permission) {
            return $next($request);
        }

        /** @var CoreAdminPermissionService $permissionService */
        $permissionService = app()->make(CoreAdminPermissionService::class);
        $canAccess = $permissionService->userCan($user, (string)$permission);
        if ($canAccess) {
            return $next($request);
        }

        return json(['code' => 403, 'msg' => ''], 403);
    }
}
