<?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,$request->site['secret_key']);
        return $next($request);
    }


    /**
     * 检查数据是否正常
     * @param $secret_key
     */
    private function checkUser($token,$secret_key) {
        if(empty($secret_key)) {
            throw new AuthException('请重新登录', -99);
        }
        try{
            list($headb64, $bodyb64, $cryptob64) = explode('.', $token);
            $payload = JWT::jsonDecode(JWT::urlsafeB64Decode($bodyb64));

            //$token = $payload->token;
            //$uid = @crypto_decrypt(base64_decode($token),$secret_key);
            $uid = $payload->uid;
            $memData = (new Member)
                        ->where('uid',$uid)
                        ->where('sassid',\request()->site['sassid'])
                        ->find();

            if(empty($memData)) {
                throw new AuthException('请重新登录', -99);
            }
            //站点停用
            if(empty($memData['status'])) {
                throw new AuthException('用户已经停用。', -99);
            }
            return $memData->toArray();
        }catch (\Throwable $e) {
            //var_dump($e->getMessage());
            throw new AuthException('请重新登录', -99);
        }
    }


}
