<?php
namespace app\admin\middleware;

use Webman\Http\Request;
use Webman\Http\Response;
use Webman\MiddlewareInterface;

/**
 * 接口签名中间件
 * Class SignAuthMiddleware
 * @package app\admin\middleware
 */
class SignAuthMiddleware implements MiddlewareInterface
{
    public function process(Request $request, callable $handler) : Response
    {
        try {
            $sign = $request->header('sign');
            if(!$sign){
                throw new \Exception('签名不能为空！', 500);
            }
            $token  = $request->header('Authorization', '');
            $data   = $request->all();
            $string = KsortAscll($data);
            $mySign = strtoupper(md5($string . $token . config('app')['sign_key']));
            if($mySign != $sign)
            {
                throw new \Exception('签名错误！' . $string . $token . config('app')['sign_key'], 500);
            }
            return $handler($request);
        }catch (\Exception $exception){
            throw new \Exception($exception->getMessage(), $exception->getCode());
        }
    }
}
