<?php
// +----------------------------------------------------------------------
// | [ WE CAN DO IT MORE SIMPLE  ]
// +----------------------------------------------------------------------
// | Copyright (c) 2018-2020 rights reserved.
// +----------------------------------------------------------------------
// | Author: TABLE ME
// +----------------------------------------------------------------------
// | Date: 2020-08-30 14:59
// +----------------------------------------------------------------------
namespace app\api\middleware;

use app\model\api\Member;
use app\model\api\Site;
use app\Request;
use Firebase\JWT\JWT;
use library\exceptions\AuthException;
use library\interfaces\MiddlewareInterface;
use think\facade\Env;

class UserMiddleware implements MiddlewareInterface
{
    public function handle(Request $request, \Closure $next)
    {
        $token =$request->header('TOKEN');
        $request->user = $this->checkUser($token);
        return $next($request);
    }


    /**
     * 检查数据是否正常
     * @param $token
     */
    private function checkUser($token) {
        try{
            list($headb64, $bodyb64, $cryptob64) = explode('.', $token);
            $payload = JWT::jsonDecode(JWT::urlsafeB64Decode($bodyb64));
            $uid = $payload->uid;
            $member = (new Member)->where('uid',$uid)->find();
            if(empty($member)) {
                throw new AuthException('请重新登录', -99);
            }
            return $member->toArray();
        }catch (\Throwable $e) {
            throw new AuthException('请重新登录', -99);
        }
    }


}
