<?php
declare (strict_types = 1);

namespace app\middleware;

use Firebase\JWT\JWT;
use think\facade\Cache;
use think\facade\Request;

/**
 * Class Logincheck
 * @package app\middleware
 *admin后台登入的中间件,验证后台是否登入
 */
class AdminLoginCheck
{
    /**
     * 处理请求
     *
     * @param \think\Request $request
     * @param \Closure       $next
     * @return Response
     */
    public function handle($request, \Closure $next)
    {
        if(Request::header('token')) {
            $token =  Request::header('token');
            //判断是否在redis中
            $redis= Cache::store('redis')->handler();
            $decodeData = (array)JWT::decode($token,config('app.jwt_key'),array("HS256"));
            if(!isset($decodeData['code'])){
                $r_token= $redis->get("admin_tokens_".$decodeData['uid']);
                if(!$r_token && $r_token!=$token) {
                    return response()->data(json_encode(['code'=>401,'msg'=>'非法的token!!!!']))->code(400);
                }
            } else {
                return response()->data(json_encode(['code'=>401,'msg'=>'非法的token!!!!']))->code(400);
            }
        } else {
            return response()->data(json_encode(['code'=>401,'msg'=>'token不存在']))->code(401);
        }
        return $next($request);
    }

}
