<?php

namespace app\middleware;

use Firebase\JWT\ExpiredException;
use Firebase\JWT\JWT;
use Firebase\JWT\Key;
use Webman\MiddlewareInterface;
use Webman\Http\Response;
use Webman\Http\Request;
use support\Redis;

class adminAuth implements MiddlewareInterface
{
    public function process(Request $request, callable $next): Response
    {

        $path = $request->path();
        if($path) {
            //白名单
            $url = [
                '/admin/login'
            ];
            if(in_array($path, $url)) {
                return $next($request);
            }
        }

        $token = $request->header('X-Token');
        if(empty($token)) {
            $token = $request->cookie('vue_admin_template_token');
        }
        if(empty($token)) {
            $token = $request->cookie('AdminToken');
        }
        if(empty($token)) {
            return response(json_encode(['code' => 403, 'msg'=> 'token expire']));
        }
        //判断是否退出登录
        $md5 = md5($token);
        $logout = Redis::get('Admin:logout:'.$md5);
        if(!empty($logout)) {
            return response(json_encode(['code' => 400, 'msg'=> 'token expire']));
        }

        try {
            $key = new Key(config('app.jwt_key_admin'), 'HS256');   // 密钥
            $decoded = JWT::decode(str_replace('Bearer ','',$token), $key);
            if(!empty($decoded) && $decoded->data && $decoded->data->id) {
                $id = $decoded->data->id;
                $disabled = Redis::get('Admin:disabled:'.$id);
                //用户是否被禁用了
                if($disabled) {
                    return response(json_encode(['code' => 405, 'msg'=> 'token disabled']));
                }
                $request->admin = $decoded->data;
                $request->token = $token;
            }else {
                return response(json_encode(['code' => 401, 'msg'=> 'token expired']));
            }
        }catch (ExpiredException $e){
            return response(json_encode(['code' => 401, 'msg'=> 'token expired']));
        }catch (\Exception $e){
            return response(json_encode(['code' => 402, 'msg'=> 'token expire']));
        }

        $response = $next($request);
        return $response;
    }
}