<?php
// +----------------------------------------------------------------------
// | A3Mall
// +----------------------------------------------------------------------
// | Copyright (c) 2020 http://www.a3-mall.com All rights reserved.
// +----------------------------------------------------------------------
// | Author: xzncit <158373108@qq.com>
// +----------------------------------------------------------------------

namespace app\common\library\jwt;

use app\common\exception\BaseException;
use think\facade\Request;

/**
 * @package app\common\library\jwt
 * @class Auth
 * @author xzncit 2023-08-23
 */
class Auth {

    /**
     * @param $token
     * @return string
     * @throws BaseException
     */
    public static function value($token=""){
        if(empty($token)){
            $token = Request::header("Authorization");
        }

        if(empty($token)){
            throw new BaseException("您还未登录，请重新登录",401);
        }

        return str_replace("Bearer ", "",$token);
    }

    /**
     * @param $value
     * @return array
     * @throws BaseException
     */
    public static function parse($value){
        $string = base64_decode($value);
        $arr = explode('|', $string);
        if (count($arr) != 3) {
            throw new BaseException("解析JWT失败，请重新登录",401);
        }

        list($value,$time,$md5) = $arr;
        if(md5(Config::getSign().$value.$time) != $md5){
            throw new BaseException("解析加密失败，请重新登录",401);
        }

        return [
            "value"     => $value,
            "time"      => $time
        ];
    }

}