<?php


namespace App\Http\Middleware;

use App\Cache\UserCache;
use App\Consts\ErrorConst;
use App\Libs\Utils;
use App\Models\Channel\Channel;
use Closure;
use App\Exceptions\ApiException;
use Illuminate\Support\Facades\Log;

class CheckSign
{
    /**
     * @param         $request
     * @param Closure $next
     * @return mixed
     * @throws ApiException
     */
    public function handle($request, Closure $next)
    {
        $params = $request->all();
        $token = $request->header('d-token', '');
        $token_data = UserCache::getTokenData($token);
        // 未登录跳过验签
        if (!getProp($token_data, 'uid')) return $next($request);
        $uid = getProp($token_data, 'uid');
        // 老用户跳过验签
        if ($uid <= 479) return $next($request);

        $referer_url = '';
        if (isset($params['_url'])) {
            $referer_url = $params['_url'];
            unset($params['_url']);
        }
        // 先验签(非本地模式需要验签)
        if (env('CHECK_SIGN') && $params) {
            $param_sign = getProp($params, 'sign');
            $timestamp = getProp($params, 'timestamp');
            if (!getProp($params, 'nonce_str') || !$timestamp) {
                Log::info('验签失败, 请求参数不正确;传参: '.json_encode($params, 256));
                Utils::throwError('1002:数据异常,请求参数不正确');
            }
            if (time() - $timestamp > 300) {
                Log::info('验签失败, 签名5分钟内有效;传参: '.json_encode($params, 256));
                Utils::throwError('1002:数据异常,请求参数不正确');
            }

            foreach ($params as $k=>$v) {
                if (!$v) unset($params[$k]);
            }

            unset($params['sign']);
            ksort($params);
            $str = strtoupper(http_build_query($params));
            $sign = md5($str.'&key='.env('SIGN_SALT'));
            if ($param_sign != $sign) {
                $params['_url'] = $referer_url;
                $params['sign'] = $param_sign;
                $params['check_sign'] = $sign;
                $params['check_str'] = $str.'&key='.env('SIGN_SALT');
                Log::info('验签失败, 签名不正确;传参: '.json_encode($params, 256));
                Utils::throwError('1002:数据异常,请求参数不正确');
            }
        }

        return $next($request);
    }
}
