<?php

namespace App\Http\Middleware;

use Auth;
use Closure;
use Illuminate\Http\Request;

class ScopeCheck
{
    /**
     * Handle an incoming request.
     *
     * @param  \Illuminate\Http\Request  $request
     * @param  \Closure  $next
     * @return mixed
     */
    public function handle(Request $request, Closure $next, $scope)
    {
        if (! $request->user() || ! $request->user()->token()) {
            throw new AuthenticationException;
        }

        $user = $request->user();

        if ($request->user()->tokenCan($scope)) {
            return $next($request);
        }

        return response()->json([
            'status' => false, 
            'error' => 'UNAUTHORIZE'
        ], 403);
    }
}
