<?php
/**
 * Created by PhpStorm.
 * User: guanxl
 * Date: 2018/3/20
 * Time: 14:30
 */

namespace App\Services;

use App\Traits\Singleton;
use Illuminate\Support\Facades\Log;
use Illuminate\Support\Facades\Redis;

class AccessToken
{
    use Singleton;
    const REDIS_ACCESS_TOKENS = "bs_accesstoken";

    public function create($user)
    {
        $accessToken = $this->generate(64);
        Log::info($accessToken);
        Redis::hset(self::REDIS_ACCESS_TOKENS, $user["user_id"], $accessToken);
        return $accessToken;
    }

    public function generate($length = 32)
    {
        $characters = 'abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ!"§$%&/()=[]{}';
        $useChars = array();
        // select some random chars:
        for ($i = 0; $i < $length; $i++) {
            $useChars[] = $characters[mt_rand(0, strlen($characters) - 1)];
        }
        // Add numbers
        array_push($useChars, rand(0, 9), rand(0, 9), rand(0, 9));
        shuffle($useChars);
        $randomString = trim(implode('', $useChars));
        $randomString = substr($randomString, 0, $length);
        return base64_encode($randomString);
    }

    public function getAccessToken($userId){
        return Redis::hGet(self::REDIS_ACCESS_TOKENS,$userId);
    }
}