AuthService.php 1.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869
  1. <?php
  2. namespace App\Services;
  3. use App\Repositories\AuthRepositoryInterface;
  4. use App\DataTransferObjects\AuthDto;
  5. use App\DataTransferObjects\RefreshTokenDto;
  6. use Illuminate\Support\Str;
  7. class AuthService
  8. {
  9. public function __construct(
  10. protected AuthRepositoryInterface $authRepository,
  11. ) {
  12. }
  13. public function login(AuthDto $credentials): ?array
  14. {
  15. if (!$this->authRepository->attemptLogin($credentials)) {
  16. return null;
  17. }
  18. $user = $this->authRepository->findUserByEmail($credentials->email);
  19. $deviceId = Str::uuid()->toString();
  20. $accessToken = $this->authRepository->createAccessToken($user, $deviceId);
  21. $refreshToken = $this->authRepository->createRefreshToken($user, $deviceId);
  22. return [
  23. 'access_token' => $accessToken,
  24. 'refresh_token' => $refreshToken,
  25. 'user' => $user,
  26. 'device_id' => $deviceId,
  27. ];
  28. }
  29. public function refresh(RefreshTokenDto $refreshToken): ?array
  30. {
  31. $tokenModel = $this->authRepository->findToken($refreshToken->token);
  32. if (!$tokenModel || !in_array('refresh', $tokenModel->abilities) || $tokenModel->expires_at < now()) {
  33. return null;
  34. }
  35. $user = $tokenModel->tokenable;
  36. if (!$user) {
  37. return null;
  38. }
  39. $deviceId = Str::afterLast($tokenModel->name, '_');
  40. $tokens = $this->authRepository->refreshToken($tokenModel, $user, $deviceId);
  41. return array_merge($tokens, [
  42. 'user' => $user,
  43. 'device_id' => $deviceId,
  44. ]);
  45. }
  46. public function logout(string $deviceId): void
  47. {
  48. $user = auth()->user();
  49. if (!$user) {
  50. return;
  51. }
  52. $this->authRepository->deleteUserTokensByDevice($user, $deviceId);
  53. }
  54. }