LoginService.php 2.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293
  1. <?php
  2. namespace App\Services;
  3. use App\Traits\CommonTrait;
  4. use Illuminate\Support\Facades\Cache;
  5. class LoginService
  6. {
  7. /**
  8. * 存放通用的 缓存key和tags
  9. */
  10. use CommonTrait;
  11. protected ?string $uniqueIdentifier;
  12. public int $expiredTime = 24 * 3600 * 7;
  13. public ?string $authorizationEncrypt;
  14. public function __construct($siteAliasName)
  15. {
  16. $this->siteAliasName = $siteAliasName;
  17. $this->uniqueIdentifier = $this->getUniqueIdentifier();
  18. // 用户登录的token信息
  19. $this->authorizationEncrypt = $this->getToken();
  20. }
  21. /**
  22. * 设置登录,返回登录token
  23. *
  24. * @param $userInfo
  25. * @param int $time
  26. * @return array
  27. */
  28. public function setLoginCookie($userInfo, int $time = 24 * 3600 * 7): array
  29. {
  30. $this->expiredTime = $time = $time ?: config('session.lifetime') * 60;
  31. //设置随机值
  32. $encrypt = md5(sha1(md5(microtime() . mt_rand())));
  33. //设置登录的用户id
  34. $keyArr = $this->getUserIdCacheKey($encrypt);
  35. Cache::tags($keyArr['tags'])->put($keyArr['key'], $userInfo['id'], $time);
  36. // 存储用户信息
  37. $keyArr = $this->getUserInfoCacheKey($encrypt);
  38. Cache::tags($keyArr['tags'])->put($keyArr['key'], $userInfo, $time);
  39. return ['token' => $encrypt, 'expire' => $time];
  40. }
  41. /**
  42. * 用户退出登录,清除已经保存的登录信息
  43. *
  44. * @param string $encrypt
  45. * @return bool
  46. */
  47. public function clearLoginInfo(string $encrypt = ''): bool
  48. {
  49. $this->authorizationEncrypt = $encrypt ?: $this->authorizationEncrypt;
  50. $keyArr = $this->getUserIdCacheKey($this->authorizationEncrypt);
  51. Cache::tags($keyArr['tags'])->forget($keyArr['key']);
  52. return true;
  53. }
  54. /**
  55. * @param $yzm
  56. * @param int $time
  57. */
  58. public function saveImgYzm($yzm, int $time = 300)
  59. {
  60. $keyArr = $this->getYzmCacheKey();
  61. Cache::tags($keyArr['tags'])->put($keyArr['key'], $yzm, $time);
  62. }
  63. /**
  64. * @param $yzm
  65. * @return bool
  66. */
  67. public function checkImgYzm($yzm): bool
  68. {
  69. $keyArr = $this->getYzmCacheKey();
  70. return $yzm == Cache::tags($keyArr['tags'])->get($keyArr['key']);
  71. }
  72. public function clearImgYzm()
  73. {
  74. $keyArr = $this->getYzmCacheKey();
  75. Cache::tags($keyArr['tags'])->forget($keyArr['key']);
  76. }
  77. }