<?php

namespace Modules\Permissions\Middlewares;

use Illuminate\Http\Request;
use Modules\Common\Errors\Errors;
use Modules\Common\Exceptions\CommonBusinessException;
use Modules\User\Models\User;

/**
 * 检测用户角色权限
 * 使用方法:
 * Route::get('list', [FinanceCheckController::class, 'list'])->middleware(['roleCheck:aa,bb,cc'])
 * aa,bb,cc 代表可以操作的多个角色的 identify
 */
class RoleCheck
{
    public function handle(Request $request, \Closure $next, ...$enableRoles)
    {
        /* @var User $user */
        $user = $request->user(getGuardName());
        $role = $user->roles();
        if($role->pluck('identify')->intersect($enableRoles)->isEmpty()) {
            CommonBusinessException::throwError(Errors::NO_OPERATE_PERMISSION);
        }
        return $next($request);
    }
}
