AppUserLogic.php 2.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107
  1. <?php
  2. namespace App\Admin\Http\Logics;
  3. use Illuminate\Support\Arr;
  4. use Illuminate\Support\Facades\Cache;
  5. use function App\Http\_header;
  6. use function App\Http\_microtime;
  7. use function App\Http\success;
  8. use Illuminate\Support\Facades\Log;
  9. class AppUserLogic
  10. {
  11. const CACHE_PREFIX = "TM_USER_CACHE_";
  12. const TOKEN_CACHE_PREFIX = "TM_USER_TOKEN_";
  13. public static function token($id, $user)
  14. {
  15. $token = uniqid(_microtime(13), true);
  16. $user = $user->toArray();
  17. $user = Arr::except($user, 'created_at');
  18. $user = Arr::except($user, 'updated_at');
  19. $user = Arr::except($user, 'deleted_at');
  20. $user = Arr::except($user, 'status');
  21. $prefix = "USER_CACHE_" . $id;
  22. Cache::put($token, $user, 8640000 * 1); //1天
  23. if (Cache::has($prefix)) {
  24. $oldToken = Cache::get($prefix);
  25. Cache::forget($oldToken);
  26. }
  27. Cache::put($prefix, $token, 86400 * 8);
  28. return success(['token' => $token, 'user' => $user], "登录成功");
  29. }
  30. public static function updateToekn($user)
  31. {
  32. $user = $user->toArray();
  33. $user = Arr::except($user, 'created_at');
  34. $user = Arr::except($user, 'updated_at');
  35. $user = Arr::except($user, 'deleted_at');
  36. $user = Arr::except($user, 'status');
  37. $token = _header('authorization');
  38. Cache::put($token, $user, 8640000 * 1); //1天
  39. }
  40. /**
  41. * 校验token
  42. *
  43. * @param $token
  44. *
  45. * @return mixed
  46. */
  47. public static function validToken($token = null,$platform = null): mixed
  48. {
  49. $token = $token ?: _header('authorization');
  50. if (empty($token)) {
  51. return false;
  52. }
  53. $user = Cache::get($token);
  54. if (empty($user)) {
  55. return false;
  56. }
  57. $userId = $user['id'];
  58. $platform = $platform ?: _header('platform');
  59. if (empty($platform)) {
  60. return false;
  61. }
  62. if($platform == 1){
  63. $cacheKeyPrefix = "ADMIN_CACHE_";
  64. }
  65. if($platform == 2 || $platform == 3){
  66. $cacheKeyPrefix = "FONT_CACHE_";
  67. }
  68. $cacheKey = $cacheKeyPrefix . $userId;
  69. if (Cache::get($cacheKey) != $token) {
  70. return false;
  71. }
  72. return $user;
  73. }
  74. public static function delToken($id)
  75. {
  76. $prefix = "USER_CACHE_" . $id;
  77. if (Cache::has($prefix)) {
  78. $oldToken = Cache::get($prefix);
  79. Cache::forget($oldToken);
  80. }
  81. return success([], "退出成功");
  82. }
  83. }