AuthService.php 2.0 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071
  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. $tokenModel = $this->authRepository->findToken($refreshToken->refresh_token);
  32. if (!$tokenModel || !in_array(needle: 'refresh', haystack: $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(subject: $tokenModel->name, search: '_');
  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(): void
  47. {
  48. $user = Auth::user();
  49. $tokenName = $user->currentAccessToken()->name;
  50. $deviceId = Str::afterLast($tokenName, '_');
  51. if (!$user) {
  52. return;
  53. }
  54. $this->authRepository->deleteUserTokensByDevice(user: $user, deviceId: $deviceId);
  55. }
  56. }