<?php

namespace App\Http\Middleware;

use App\Helpers\Constants;
use Closure;
use Illuminate\Auth\AuthenticationException;
use Illuminate\Validation\UnauthorizedException;
use Symfony\Component\HttpKernel\Exception\UnauthorizedHttpException;
use Tymon\JWTAuth\Exceptions\JWTException;
use Tymon\JWTAuth\Exceptions\TokenBlacklistedException;
use Tymon\JWTAuth\Exceptions\TokenExpiredException;
use Tymon\JWTAuth\Http\Middleware\BaseMiddleware;

class JWTRoleAuth extends BaseMiddleware
{
    /**
     * Handle an incoming request.
     *
     * @param         $request
     * @param Closure $next
     * @param null    $guard
     * @return mixed
     * @throws TokenExpiredException
     */
    public function handle($request, Closure $next, $guard = null)
    {
        try {
            $this->checkForToken($request);

            $tokenRole = $this->auth->parseToken()->getClaim('role');

        }catch (TokenExpiredException $e) {
            // 处理刷新 token 的异常
            try {
                // token 过期
                $sToken = auth($guard)->refresh();
                \Auth::guard($guard)->onceUsingId($this->auth->manager()->getPayloadFactory()->buildClaimsCollection()->toPlainArray()['sub']);
                return $this->setAuthenticationHeader($next($request), $sToken);

            }catch (JWTException $exception) {
                // token 令牌 刷新时间超时，或使用失效的 token 刷新
                throw new TokenExpiredException('登录超时请重新登录');
            }
        }catch (JWTException $e) {
            throw new UnauthorizedHttpException('jwt-auth', '请登录后再进行访问');
        }

        // 判断token角色。
        if ($tokenRole != $guard) {
            throw new UnauthorizedException('您当前不能访问该接口');
        }

        return $next($request);
    }
}
