<?php
namespace app\common\middleware;

use Exception;
use thans\jwt\exception\TokenInvalidException;
use thans\jwt\facade\JWTAuth;
use think\facade\Cache;
//验证权限
class CheckAuth
{
    public function handle($request, \Closure $next)
    {
        try {

            //判断，如果当前控制的noNeedLogin 属性包含当前接口的名称，则不需要验证权限
            $noNeedLogin = [
                'admin/login',
            ];
            $noNeedRight = [
                'admin/login',
            ];
            $route = $request->pathinfo();
            if(in_array($route, $noNeedLogin)){
                return $next($request);
            }
            if(in_array($route, $noNeedRight)){
                return $next($request);
            }
            
            $jwtData = JWTAuth::auth();
        } catch (Exception $exception) {

            //token有误
            if (get_class($exception) == TokenInvalidException::class) {
                return shutdown(lang('user.loginError'), 10001);
            }

            $errorMsgArr = [
                'Must have token' => lang('user.mustToken'),
                'The token is in blacklist.' => lang('user.blacklist'),
                'The token is expired.' => lang('user.expired'),
                'The token is in blacklist grace period list.' => lang('user.expired')
            ];
            return shutdown($errorMsgArr[$exception->getMessage()] ?? $exception->getMessage(), 10001);
        }
        $adminInfo = [];
        if (!empty($jwtData['admin'])) {
            $adminInfo = $jwtData['admin']->getValue();
        }
        $userInfo = $jwtData['info']->getValue();

        //解密token中的用户信息
        $userInfo = str_encipher($userInfo,false, config('app.aes_token_key'));

        if (!$userInfo) {
            return shutdown(lang('user.loginError'), 10001);
        }
        //解析json
        $userInfo = (array)json_decode($userInfo, true);
        
        if(cache('forbidUser_'.$userInfo['id'])){
            JWTAuth::invalidate(JWTAuth::token()->get());
            Cache::delete('forbidUser_'.$userInfo['id']);
            return shutdown(lang('user.forbid'), -1);
        }
        //已经登陆，将用户信息存入请求头
        $request->adminInfo  = $adminInfo;
        $request->userInfo  = $userInfo;
        $request->uid       = $userInfo['id'];
        $request->userToken = JWTAuth::token()->get();
        return $next($request);
    }
}