<?php
// +----------------------------------------------------------------------
// | [ WE CAN DO IT MORE SIMPLE  ]
// +----------------------------------------------------------------------
// | Copyright (c) 2018-2020 rights reserved.
// +----------------------------------------------------------------------
// | Author: TABLE ME
// +----------------------------------------------------------------------
// | Date: 2020-08-30 14:59
// +----------------------------------------------------------------------
namespace app\api\middleware;

use app\Request;
use library\exceptions\AuthException;
use library\interfaces\MiddlewareInterface;
use library\services\UtilService;

class SeretKeyMiddleware implements MiddlewareInterface
{
    public function handle(Request $request, \Closure $next)
    {
//        $this->checkSign($request);//暂时不用
        return $next($request);
    }


    /**
     * 检查数据是否正常
     * @param $secret_key
     */
    private function checkSign(Request $request) {
        $checkHeader = ['deviceId','deviceType','fromApp','fromPlat','mobileType','version','timestamp'];
        $sign = $request->header('sign','');
        $config = [
            'token' => $request->header('token',''),
            'deviceId' => $request->header('deviceId',''),
            'deviceType' => $request->header('deviceType',0),
            'fromApp' => $request->header('fromApp',''),
            'fromPlat' => $request->header('fromPlat',''),
            'mobileType' => $request->header('mobileType',''),
            'version' => $request->header('version',''),
            'timestamp' => $request->header('timestamp',''),
        ];
        foreach ($checkHeader as $v) {
            if(empty($config[$v])) {
               // throw new AuthException('签名参数出错!', 1001);
            }
        }
//        $calSign = $this->makeSign($config);
        if(strtoupper($sign) != $calSign){
           // throw new AuthException('签名错误!加密规则:' . $this->makeSignStr($config), 1002);
        }
    }


    private function makeSignStr(array $config)
    {
        $string = 'token=' . $config['token'] . ',deviceId=' . $config['deviceId'] . ',deviceType=' . $config['deviceType'] . ',fromApp=' . $config['fromApp'] . ',fromPlat=' . $config['fromPlat'] . ',mobileType=' . $config['mobileType'] . ',version=' . $config['version'] . ',timestamp=' . $config['timestamp'];
        $salt = config('app.appSalt');
        return $salt . $string;
    }

    private function makeSign(array $config)
    {
        $string = 'token=' . $config['token'] . ',deviceId=' . $config['deviceId'] . ',deviceType=' . $config['deviceType'] . ',fromApp=' . $config['fromApp'] . ',fromPlat=' . $config['fromPlat'] . ',mobileType=' . $config['mobileType'] . ',version=' . $config['version'] . ',timestamp=' . $config['timestamp'];
        $salt = config('app.appSalt');
        $sign = strtoupper(md5($salt . $string));
        return $sign;
    }


}
