<?php
namespace App\Http\Middleware;

use Route;
use Closure;

class CheckPermission
{
    /**
     * Handle an incoming request.
     *
     * @param  \Illuminate\Http\Request  $request
     * @param  \Closure  $next
     * @return mixed
     */
    public function handle($request, Closure $next)
    {
        $routeName = Route::currentRouteName();
        $params = ['store', 'update'];
        $operatingName = explode('.', $routeName);

        if (!in_array(array_pop($operatingName), $params) && !in_array($routeName, config('system.whitelistRoute'))) {
            $this->check($request, $routeName);
        }

        return $next($request);
    }

    private function check($request,$permission)
    {
        if (!$request->user()->user()->can($permission)) {
            abort(500);
        }
    }
}
