<?php
/**
*------Create thems Model------
*------SCWPHP  Version 1.0.0------
*------Dev Model Jions------
*------Create Time 2017-06-13 18:45:24------
*/
namespace App\Commons\Model;
use \System\Model;
class Wagent extends Model {

protected $table = 'wagent';

    function getByName($name){
       $data = $this->where('agent_name', $name)->first();
       
        if (!$data) {
            return false;
        }
        return $data;
    }


    //验证是否正确
    function   CheckKey($model , $parentString,$keyString){
        //token超时
        if ( time()  > $model->auth_expire){
                return -1 ;
         }

        if (empty($model->auth_token)){
            return -3;
        }

        if ($model->status != 1){
            return -4 ;
        }

        //验证不通过
        $md5String = md5($parentString.$model->auth_token);

        if ( $md5String != $keyString){
            return -2;
        }

        return  1  ;

    }


    public  function   TokenGetAndUpdate($agentName,$agentKey,$agentSecret){
        $model = $this->getByName($agentName);

        if (!$model){
            return false;
        }

        if ($agentKey != $model->agent_key ||  $agentSecret!= $model->agent_secret){
            return  false;
        }

        if ($model->status != 1){
            return false;
        }

        if ( intval($model->auth_expire) < time() ){
            $model->auth_expire = time () +   3600*24 ;
            $model->auth_token = md5($model->agent_name.$model->agent_key.uniqid(mt_rand())) ;
            $model->save();
        }

        return $model;

    }


}