<?php

namespace App\Http\Middleware;

use Closure;
use Tymon\JWTAuth\Exceptions\JWTException;
use Tymon\JWTAuth\Exceptions\TokenExpiredException;
use Tymon\JWTAuth\Middleware\BaseMiddleware;

class XchengxuGetUserFromToken extends BaseMiddleware
{
    /**
     * Handle an incoming request.
     *
     * @param  \Illuminate\Http\Request  $request
     * @param  \Closure  $next
     * @return mixed
     */
    public function handle($request, \Closure $next)
    {
        if (! $token = $this->auth->setRequest($request)->getToken()) {
            return response()->error('XCX_TOKEN_ERROR');
        }

        try {
            $user = $this->auth->authenticate($token);
        } catch (TokenExpiredException $e) {
            return response()->error('XCX_TOKEN_ERROR');
        } catch (JWTException $e) {
            return response()->error('XCX_TOKEN_ERROR');
        }

        if (! $user) {
             return response()->error('XCX_TOKEN_ERROR');
        }

        $this->events->fire('tymon.jwt.valid', $user);

        return $next($request);
    }
}
