<?php

namespace App\Http\Middleware;

use Closure;

class authJWT
{
    /**
     * Handle an incoming request.
     *
     * @param  \Illuminate\Http\Request  $request
     * @param  \Closure  $next
     * @return mixed
     */
    public function handle($request, Closure $next)
    {

        try {

            // 如果用户登陆后的所有请求没有jwt的token抛出异常
            $token = $request->input('token');
            if(empty($token)){
                return toJson(-30001);
            }

            $myToken = $this->createToken($request);
            if($token != $myToken){
                return toJson(-30001);
            }

        } catch (Exception $e) {
            return toJson(-30001);
        }
        return $next($request);
    }

    private function createToken($request){
        $key = $request->input('key');
        $secret = \App\Models\Party::where('key', $key)->first()['secret'];
        if(empty($secret)){
            return false;
        }

        $token = md5($key.$secret);
        return $token;
    }

}
