<?php

namespace App\Http\Middleware;

use Closure;
use Illuminate\Support\Facades\Route;

class CheckPermissions
{
    /**
     * Handle an incoming request.
     *
     * @param \Illuminate\Http\Request $request
     * @param \Closure $next
     * @return mixed
     */
    public function handle($request, Closure $next)
    {
        // 获取当前路由名称
        $currentRouteName = Route::currentRouteName();
        // 引入当前守卫的权限文件
        $routes = include(resource_path('lang/zh-CN/permission.php'));
        if (is_array($routes) && array_key_exists($currentRouteName, $routes)) {
            $permissions = $request->user()->getPermissionsViaRoles()->toArray();
            $permissions = array_column($permissions, 'name');
            if (in_array($currentRouteName, $permissions, true)) {
                return $next($request);
            }
        }

        $res = [
            'httpCode' => 403,
            'errorCode' => 403403,
            'errorMessage' => '您没有使用此功能的权限' . $currentRouteName,
        ];
        return response($res, 403);
    }
}
