| 12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879 |
- <?php
- namespace App\Repositories;
- use App\Models\User;
- use App\Models\PersonalAccessToken;
- use App\DataTransferObjects\AuthDto;
- use Carbon\Carbon;
- use Illuminate\Support\Facades\Auth;
- use Illuminate\Support\Facades\DB;
- class AuthRepository implements AuthRepositoryInterface
- {
- public function __construct(
- protected Auth $model,
- protected User $userModel,
- protected PersonalAccessToken $personalAccessTokenModel
- ) {}
- public function findUserByEmail(string $email): ?User
- {
- return $this->userModel->where('email', $email)->first();
- }
- public function findToken(string $token): ?PersonalAccessToken
- {
- return $this->personalAccessTokenModel->findToken($token);
- }
- public function createAccessToken(User $user, string $deviceId): string
- {
- return $user->createToken(
- "access_token_{$deviceId}",
- ['access'],
- Carbon::now()->addMinutes(15)
- )->plainTextToken;
- }
- public function createRefreshToken(User $user, string $deviceId): string
- {
- return $user->createToken(
- "refresh_token_{$deviceId}",
- ['refresh'],
- Carbon::now()->addDays(30)
- )->plainTextToken;
- }
- public function updateTokenExpiration(PersonalAccessToken $token, \DateTime $expirationTime): void
- {
- $token->update(['expires_at' => $expirationTime]);
- }
- public function deleteUserTokensByDevice(User $user, string $deviceId): void
- {
- $user->tokens()
- ->where('name', 'like', "%_{$deviceId}")
- ->delete();
- }
- public function attemptLogin(AuthDto $credentials): bool
- {
- return $this->model->attempt($credentials->toArray());
- }
- public function refreshToken(PersonalAccessToken $tokenModel, User $user, string $deviceId): array
- {
- return DB::transaction(function () use ($tokenModel, $user, $deviceId) {
- $this->updateTokenExpiration($tokenModel, Carbon::now()->addMinutes(2));
- $accessToken = $this->createAccessToken($user, $deviceId);
- $refreshToken = $this->createRefreshToken($user, $deviceId);
- return [
- 'access_token' => $accessToken,
- 'refresh_token' => $refreshToken,
- ];
- });
- }
- }
|