AuthService.php 2.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172
  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. }
  14. public function login(AuthDTO $credentials): ?array
  15. {
  16. if (!$this->authRepository->attemptLogin(credentials: $credentials)) {
  17. return null;
  18. }
  19. $user = $this->authRepository->findUserByEmail(email: $credentials->email);
  20. $deviceId = Str::uuid()->toString();
  21. $accessToken = $this->authRepository->createAccessToken(user: $user, deviceId: $deviceId);
  22. $refreshToken = $this->authRepository->createRefreshToken(user: $user, deviceId: $deviceId);
  23. return [
  24. 'access_token' => $accessToken,
  25. 'refresh_token' => $refreshToken,
  26. 'user' => $user,
  27. 'device_id' => $deviceId,
  28. ];
  29. }
  30. public function refresh(RefreshTokenDTO $refreshToken): ?array
  31. {
  32. $tokenModel = $this->authRepository->findToken( $refreshToken->token);
  33. if (!$tokenModel || !in_array(needle: 'refresh', haystack: $tokenModel->abilities) || $tokenModel->expires_at < now()) {
  34. return null;
  35. }
  36. $user = $tokenModel->tokenable;
  37. if (!$user) {
  38. return null;
  39. }
  40. $deviceId = Str::afterLast(subject: $tokenModel->name, search: '_');
  41. $tokens = $this->authRepository->refreshToken($tokenModel, $user, $deviceId);
  42. return array_merge($tokens, [
  43. 'user' => $user,
  44. 'device_id' => $deviceId,
  45. ]);
  46. }
  47. public function logout(): void
  48. {
  49. $user = Auth::user();
  50. $tokenName = $user->currentAccessToken()->name;
  51. $deviceId = Str::afterLast($tokenName, '_');
  52. if (!$user) {
  53. return;
  54. }
  55. $this->authRepository->deleteUserTokensByDevice(user: $user, deviceId: $deviceId);
  56. }
  57. }