AuthRepository.php 2.3 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879
  1. <?php
  2. namespace App\Repositories;
  3. use App\Models\User;
  4. use App\Models\PersonalAccessToken;
  5. use App\DataTransferObjects\AuthDto;
  6. use Carbon\Carbon;
  7. use Illuminate\Support\Facades\Auth;
  8. use Illuminate\Support\Facades\DB;
  9. class AuthRepository implements AuthRepositoryInterface
  10. {
  11. public function __construct(
  12. protected Auth $model,
  13. protected User $userModel,
  14. protected PersonalAccessToken $personalAccessTokenModel
  15. ) {}
  16. public function findUserByEmail(string $email): ?User
  17. {
  18. return $this->userModel->where('email', $email)->first();
  19. }
  20. public function findToken(string $token): ?PersonalAccessToken
  21. {
  22. return $this->personalAccessTokenModel->findToken($token);
  23. }
  24. public function createAccessToken(User $user, string $deviceId): string
  25. {
  26. return $user->createToken(
  27. "access_token_{$deviceId}",
  28. ['access'],
  29. Carbon::now()->addMinutes(15)
  30. )->plainTextToken;
  31. }
  32. public function createRefreshToken(User $user, string $deviceId): string
  33. {
  34. return $user->createToken(
  35. "refresh_token_{$deviceId}",
  36. ['refresh'],
  37. Carbon::now()->addDays(30)
  38. )->plainTextToken;
  39. }
  40. public function updateTokenExpiration(PersonalAccessToken $token, \DateTime $expirationTime): void
  41. {
  42. $token->update(['expires_at' => $expirationTime]);
  43. }
  44. public function deleteUserTokensByDevice(User $user, string $deviceId): void
  45. {
  46. $user->tokens()
  47. ->where('name', 'like', "%_{$deviceId}")
  48. ->delete();
  49. }
  50. public function attemptLogin(AuthDto $credentials): bool
  51. {
  52. return $this->model->attempt($credentials->toArray());
  53. }
  54. public function refreshToken(PersonalAccessToken $tokenModel, User $user, string $deviceId): array
  55. {
  56. return DB::transaction(function () use ($tokenModel, $user, $deviceId) {
  57. $this->updateTokenExpiration($tokenModel, Carbon::now()->addMinutes(2));
  58. $accessToken = $this->createAccessToken($user, $deviceId);
  59. $refreshToken = $this->createRefreshToken($user, $deviceId);
  60. return [
  61. 'access_token' => $accessToken,
  62. 'refresh_token' => $refreshToken,
  63. ];
  64. });
  65. }
  66. }