AuthService.php 1.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354
  1. <?php
  2. namespace App\Services;
  3. use Firebase\JWT\JWT;
  4. use Firebase\JWT\Key;
  5. use App\Models\User;
  6. use Illuminate\Support\Facades\Cache;
  7. class AuthService
  8. {
  9. private $user;
  10. public function __construct($user)
  11. {
  12. $this->user = $user;
  13. }
  14. public function generateAuthData($utm)
  15. {
  16. return [
  17. 'token' => $this->user->token,
  18. 'is_admin' => $this->user->is_admin,
  19. 'auth_data' => JWT::encode([
  20. 'expired_at' => time() + 3600,
  21. 'id' => $this->user->id,
  22. 'utm' => $utm,
  23. ], config('app.key'), 'HS256')
  24. ];
  25. }
  26. public static function decryptAuthData($jwt)
  27. {
  28. try {
  29. if (!Cache::has($jwt)) {
  30. $data = (array)JWT::decode($jwt, new Key(config('app.key'), 'HS256'));
  31. if ($data['expired_at'] < time()) return false;
  32. $user = User::select([
  33. 'id',
  34. 'email',
  35. 'is_admin',
  36. 'is_staff'
  37. ])
  38. ->find($data['id']);
  39. if (!$user) return false;
  40. Cache::put($jwt, $user->toArray(), 3600);
  41. }
  42. return Cache::get($jwt);
  43. } catch (\Exception $e) {
  44. return false;
  45. }
  46. }
  47. }