<?php

namespace App\Lib;

use \Firebase\JWT\JWT;
use Illuminate\Support\Facades\Log;
use Illuminate\Support\Facades\Redis;
use Firebase\JWT\Key;
use Exception;

class JwtService
{
    //token有效期 -> 30天
    const TOKEN_EXPIRE = 31536000;

    protected static $cacheKey = '';

    /**
     * @param  $info array   用户基本信息，
     * @param  $key  string  产品线秘钥，
     * @param  $appid  string  产品线id  用于后面同一端校验唯一登录使用
     */
    public static function createToken(array $info, $key)
    {
        $timeNow = time();
        $info += [
            'iat' => $timeNow,
            'nbf' => $timeNow,
            'exp' => $timeNow + self::TOKEN_EXPIRE
        ];

        self::$cacheKey = implode(':', ['token', $info['platform'], $info['id']]);

        return JWT::encode($info, $key, "HS256");
    }

    public static function verifyToken($token, $key)
    {
        try {
            JWT::$leeway = 180;//上下3分钟的冗余
            return JWT::decode($token,  new Key($key, 'HS256'));
        } catch (Exception $e) {
            Log::error("token解析失败: " . $e->getMessage());
            return false;
        }
    }

    public static function deleteToken(array $userInfos) {
        $platformList = config('config.platform_list');
        $deleteKey = [];

        foreach ($platformList as $platform) {
            foreach ($userInfos as $info) {
                $deleteKey[] = implode(':', ['token', $platform, $info['id']]);
            }
        }

        Redis::del($deleteKey);
    }

}
















