<?php
include_once('../rsa.php');
include_once('../hardware.php');
session_start();
$sid=session_id();
$fid=$_COOKIE['fid'];
$fid=Rsa::publicDecrypt($fid);
$guid=$_COOKIE['guid'];
$guid=Rsa::publicDecrypt($guid);

//授权文件不存在，跳转
if(!file_exists('/auth/certs/'.$fid.'.key')){
	echo  json_encode([
        'code'=>0,
        'msg'=>'授权失败'
    ]);
	die();			
}

//解密文件
$data=trim(file_get_contents('/auth/certs/'.$fid.'.key'));
$data=explode("\r\n",$data);
$mcode=HardwareInfo::getMCode();
//机器码不相等，该授权文件不是针对该机器的	
if($mcode!=Rsa::privDecrypt(trim($data[1]))){
	echo  json_encode([
        'code'=>0,
        'msg'=>'授权失败'
    ]);
    die();			
}

//GUID值
$authData=trim($data[0]);
$authData=Rsa::privDecrypt($authData);		
$authData=json_decode($authData,true);	
if($authData!=NULL && isset($authData['uuid'])){
    if($authData['uuid']==$guid){
        $authSuc=true;
        $ttime=time();
        if(file_exists('/auth/tmp/'.$guid)){
            $lock=file_get_contents('/auth/tmp/'.$guid);
            $lock=explode("\n",$lock);	
            foreach($lock as $k=>$v){
                if($v!=""){
                    $row=Rsa::privDecrypt(trim($v));
                    $row=explode('::',$row);
                    $id=$row[0];//guid
                    if($id==$authData['uuid']){
                        //判断sid是否相等，不相等说明已经授权给其他人
                        if($sid!=$row[1]){

                            echo  json_encode([
                                'code'=>0,
                                'msg'=>'授权失败'
                            ]);
                            die();	

                        }

                        $lock[$k]=Rsa::publicEncrypt($id.'::'.$sid.'::'.$ttime);
                        $lock=implode("\n",$lock);
                        file_put_contents('/auth/tmp/'.$guid,$lock);
                        echo  json_encode([
                            'code'=>1,
                            'msg'=>'授权成功'
                        ]); 

                        die();
                    }
                }
            }
        }       
        
    }
	
}


echo  json_encode([
        'code'=>0,
        'msg'=>'授权失败'
]);
	