<?php

namespace App\Http\Middleware;

use App\Http\Appadapter\PartySign;
use Closure;
use \App\Http\Models;

class authJWT
{
    /**
     * Handle an incoming request.
     *
     * @param  \Illuminate\Http\Request  $request
     * @param  \Closure  $next
     * @return mixed
     */
    public function handle($request, Closure $next)
    {
        try {
            $data = $request->input();

            $secret = $this->getToken($data['key']);
            $partySign = new PartySign($secret);
            if(!$partySign->checkSignature($data)) {
                return toJson(-30001);
            }
        } catch (Exception $e) {
            return toJson(-30001);
        }
        return $next($request);
    }

    private function getToken($key){
        $partyModel = new Models\Party;
        $partyInfo = $partyModel->where('key', $key)->first();
        return $partyInfo['secret'];
    }

}
