<?php

namespace App\Http\Middleware;

use App\User;
use Closure;
use Firebase\JWT\JWT;
use Illuminate\Support\Facades\Auth;


class ProcurementApiAuth
{

    public function handle($request, Closure $next)
    {
        $alg =
            [
                "typ" => "JWT", //声明类型为jwt
                "alg" => "HS256" //声明签名算法为SHA256
            ];
        $jwt = $request->header('token');

//        $key = env('JWT_SECRET');
        $key =  config('weiXin.jwt.JWT_SECRET');
        try{
            $loginUser=JWT::decode($jwt,$key,$alg);
        }
        catch (\Exception $e)
        {
            return response()->json('token无效：'.$e);
        }
        if ($loginUser) $user=User::query()->find($loginUser->data->id);
        if ($user)   Auth::login($user);
        return $next($request);
    }
}
