<?php

namespace App\Http\Middleware;

use Auth;
use Closure;
use Tymon\JWTAuth\Exceptions\JWTException;
use Tymon\JWTAuth\Http\Middleware\BaseMiddleware;
use Tymon\JWTAuth\Exceptions\TokenExpiredException;
use Symfony\Component\HttpKernel\Exception\UnauthorizedHttpException;

class CheckTokenMiddleware extends BaseMiddleware
{

    public function handle($request, Closure $next)
    {
        // 检查此次请求中是否带有 token，如果没有则抛出异常。
        try{
            $this->checkForToken($request);
        }catch (\Exception $exception){
            return response()->json([
                'code'=>40021,
                'msg'=>'没有携带token',
            ]);
        }

        // 使用 try 包裹，以捕捉 token 过期所抛出的 TokenExpiredException  异常
        try {
            // 检测用户的登录状态，如果正常则通过
            if ($this->auth->parseToken()->authenticate()) {
                return $next($request);
            }
            return response()->json([
                'code'=>50000,
                'msg'=>'未登录',
            ]);
        } catch (TokenExpiredException $exception) {
            try {
                return response()->json([
                    'code'=>50000,
                    'msg'=>'token已过期',
                ]);
            } catch (JWTException $exception) {
                return response()->json([
                    'code'=>50000,
                    'msg'=>'token已失效，请重新登陆',
                ]);
            }
        }
    }
}
