<?php

namespace App\Http\Middleware;

use Closure;
use Illuminate\Http\Request;

use App\Libraries\Response;
use App\Libraries\Users\AuthAPI;

/**
 * Class AuthToken
 *
 * @package App\Http\Middleware
 */
class AuthToken
{
    /**
     * Handle an incoming request
     *
     * @param \Illuminate\Http\Request $request
     * @param \Closure $next
     * @return mixed
     */
    public function handle(Request $request, Closure $next)
    {
        if ($request->header('Token') === null) {
            return $this->jsonAbort();
        } else {
            $auth = AuthAPI::getInstance()->getSession($request->header('Token'));

            if (!$auth) {
                return $this->jsonAbort();
            }
        }

        return $next($request);
    }

    /**
     * Abort method, no token is found
     *
     * @return \Illuminate\Http\JsonResponse
     */
    protected function jsonAbort()
    {
        $response = new Response();
        $response->setErrors([
            'token' => 'Invalid access token'
        ]);

        return $response->toJson();
    }
}