AuthService.php 2.6 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798
  1. <?php
  2. namespace App\Services;
  3. use App\Utils\CacheKey;
  4. use App\Utils\Helper;
  5. use Firebase\JWT\JWT;
  6. use Firebase\JWT\Key;
  7. use App\Models\User;
  8. use Illuminate\Support\Facades\Cache;
  9. use Illuminate\Http\Request;
  10. class AuthService
  11. {
  12. private $user;
  13. public function __construct(User $user)
  14. {
  15. $this->user = $user;
  16. }
  17. public function generateAuthData(Request $request)
  18. {
  19. $guid = Helper::guid();
  20. $authData = JWT::encode([
  21. 'id' => $this->user->id,
  22. 'session' => $guid,
  23. ], config('app.key'), 'HS256');
  24. self::addSession($this->user->id, $guid, [
  25. 'ip' => $request->ip(),
  26. 'login_at' => time(),
  27. 'ua' => $request->userAgent()
  28. ]);
  29. return [
  30. 'token' => $this->user->token,
  31. 'is_admin' => $this->user->is_admin,
  32. 'auth_data' => $authData
  33. ];
  34. }
  35. public static function decryptAuthData($jwt)
  36. {
  37. try {
  38. if (!Cache::has($jwt)) {
  39. $data = (array)JWT::decode($jwt, new Key(config('app.key'), 'HS256'));
  40. if (!self::checkSession($data['id'], $data['session'])) return false;
  41. $user = User::select([
  42. 'id',
  43. 'email',
  44. 'is_admin',
  45. 'is_staff'
  46. ])
  47. ->find($data['id']);
  48. if (!$user) return false;
  49. Cache::put($jwt, $user->toArray(), 3600);
  50. }
  51. return Cache::get($jwt);
  52. } catch (\Exception $e) {
  53. return false;
  54. }
  55. }
  56. private static function checkSession($userId, $session)
  57. {
  58. $sessions = (array)Cache::get(CacheKey::get("USER_SESSIONS", $userId)) ?? [];
  59. if (!in_array($session, array_keys($sessions))) return false;
  60. return true;
  61. }
  62. private static function addSession($userId, $guid, $meta)
  63. {
  64. $cacheKey = CacheKey::get("USER_SESSIONS", $userId);
  65. $sessions = (array)Cache::get($cacheKey, []);
  66. $sessions[$guid] = $meta;
  67. if (!Cache::put(
  68. $cacheKey,
  69. $sessions
  70. )) return false;
  71. return true;
  72. }
  73. public function getSessions()
  74. {
  75. return (array)Cache::get(CacheKey::get("USER_SESSIONS", $this->user->id), []);
  76. }
  77. public function delSession($sessionId)
  78. {
  79. $cacheKey = CacheKey::get("USER_SESSIONS", $this->user->id);
  80. $sessions = (array)Cache::get($cacheKey, []);
  81. unset($sessions[$sessionId]);
  82. if (!Cache::put(
  83. $cacheKey,
  84. $sessions
  85. )) return false;
  86. return true;
  87. }
  88. }