<?php
namespace App\Services;

use Illuminate\Support\Facades\DB;
use JWT;
class TokenService
{
    public function RefreshToken($arr){
        $result=array();
        $cc= JWT::CheckJwt($arr['token']);  //校验token是否有效


        if($cc['status'] != "OK"){
            $result['status']=false;
            $result['msg']='校验失败,请重新登录';
            return  $result;
        }
        if($cc['tokentype']=='refresh'){  //校验类型通过，刷新创建新token
            $OldRefreshToken= substr($arr['token'],strpos($arr['token'],' ')+1);
            $accessTimeout = JWT::GetGetSecretTimeOut();
            $refreshTimeout = JWT::GetRefreshTokenTimeOut();
            $access_token = JWT::BuildJWT('yz','access',$cc['userid'],'',$accessTimeout);
            $refresh_token = JWT::BuildJWT('yz','refresh',$cc['userid'],'',$refreshTimeout);
            //判断先前的token是否未使用（存在），是则更新为新token
            $u=DB::table('admin_accounts')->where(['id'=>$cc['userid'],'type'=>1,'del'=>2,'token'=>md5($OldRefreshToken)])->update(['token'=>md5($refresh_token)]);
            $result['token']=$access_token;
            $result['refresh_token']=$refresh_token;

            if($u==1){
                $result['status']=true;
            }else{
                $result['status']=false;
                $result['msg']='刷新授权失败';
            }
            //  var_dump($result);

        }else{
            $result['status']=false;
            $result['msg']='无效令牌';
        }
        return  $result;
    }
}
