AuthService.php 2.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475
  1. <?php
  2. namespace App\Services;
  3. use App\Repositories\AuthRepositoryInterface;
  4. use App\DTO\AuthDTO;
  5. use App\DTO\RefreshTokenDTO;
  6. use Illuminate\Support\Str;
  7. use Illuminate\Support\Facades\Auth;
  8. class AuthService
  9. {
  10. public function __construct(
  11. protected AuthRepositoryInterface $authRepository,
  12. ) {}
  13. public function login(AuthDTO $credentials): ?array
  14. {
  15. if (!$this->authRepository->attemptLogin(credentials: $credentials)) {
  16. return null;
  17. }
  18. $user = $this->authRepository->findUserByEmail(email: $credentials->email);
  19. $deviceId = Str::uuid()->toString();
  20. $accessToken = $this->authRepository->createAccessToken(user: $user, deviceId: $deviceId);
  21. $refreshToken = $this->authRepository->createRefreshToken(user: $user, deviceId: $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. if (!$refreshToken->refresh_token) {
  32. return null;
  33. }
  34. $tokenModel = $this->authRepository->findToken($refreshToken->refresh_token);
  35. if (!$tokenModel || !in_array(needle: 'refresh', haystack: $tokenModel->abilities) || $tokenModel->expires_at < now()) {
  36. return null;
  37. }
  38. $user = $tokenModel->tokenable;
  39. if (!$user) {
  40. return null;
  41. }
  42. $deviceId = Str::afterLast(subject: $tokenModel->name, search: '_');
  43. $tokens = $this->authRepository->refreshToken($tokenModel, $user, $deviceId);
  44. return array_merge($tokens, [
  45. 'user' => $user,
  46. 'device_id' => $deviceId,
  47. ]);
  48. }
  49. public function logout(): void
  50. {
  51. $user = Auth::user();
  52. $tokenName = $user->currentAccessToken()->name;
  53. $deviceId = Str::afterLast($tokenName, '_');
  54. if (!$user) {
  55. return;
  56. }
  57. $this->authRepository->deleteUserTokensByDevice(user: $user, deviceId: $deviceId);
  58. }
  59. }