AccessToken.php 1.2KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647
  1. <?php
  2. /**
  3. * Created by PhpStorm.
  4. * User: guanxl
  5. * Date: 2018/3/20
  6. * Time: 14:30
  7. */
  8. namespace App\Services;
  9. use App\Traits\Singleton;
  10. use Illuminate\Support\Facades\Log;
  11. use Illuminate\Support\Facades\Redis;
  12. class AccessToken
  13. {
  14. use Singleton;
  15. const REDIS_ACCESS_TOKENS = "bs_accesstoken";
  16. public function create($user)
  17. {
  18. $accessToken = $this->generate(64);
  19. Log::info($accessToken);
  20. Redis::hset(self::REDIS_ACCESS_TOKENS, $user["user_id"], $accessToken);
  21. return $accessToken;
  22. }
  23. public function generate($length = 32)
  24. {
  25. $characters = 'abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ!"§$%&/()=[]{}';
  26. $useChars = array();
  27. // select some random chars:
  28. for ($i = 0; $i < $length; $i++) {
  29. $useChars[] = $characters[mt_rand(0, strlen($characters) - 1)];
  30. }
  31. // Add numbers
  32. array_push($useChars, rand(0, 9), rand(0, 9), rand(0, 9));
  33. shuffle($useChars);
  34. $randomString = trim(implode('', $useChars));
  35. $randomString = substr($randomString, 0, $length);
  36. return base64_encode($randomString);
  37. }
  38. public function getAccessToken($userId){
  39. return Redis::hGet(self::REDIS_ACCESS_TOKENS,$userId);
  40. }
  41. }