| 123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869 |
- <?php
- namespace App\Services;
- use App\Repositories\AuthRepositoryInterface;
- use App\DataTransferObjects\AuthDto;
- use App\DataTransferObjects\RefreshTokenDto;
- use Illuminate\Support\Str;
- class AuthService
- {
- public function __construct(
- protected AuthRepositoryInterface $authRepository,
- ) {
- }
- public function login(AuthDto $credentials): ?array
- {
- if (!$this->authRepository->attemptLogin($credentials)) {
- return null;
- }
- $user = $this->authRepository->findUserByEmail($credentials->email);
- $deviceId = Str::uuid()->toString();
- $accessToken = $this->authRepository->createAccessToken($user, $deviceId);
- $refreshToken = $this->authRepository->createRefreshToken($user, $deviceId);
- return [
- 'access_token' => $accessToken,
- 'refresh_token' => $refreshToken,
- 'user' => $user,
- 'device_id' => $deviceId,
- ];
- }
- public function refresh(RefreshTokenDto $refreshToken): ?array
- {
- $tokenModel = $this->authRepository->findToken($refreshToken->token);
- if (!$tokenModel || !in_array('refresh', $tokenModel->abilities) || $tokenModel->expires_at < now()) {
- return null;
- }
- $user = $tokenModel->tokenable;
- if (!$user) {
- return null;
- }
- $deviceId = Str::afterLast($tokenModel->name, '_');
- $tokens = $this->authRepository->refreshToken($tokenModel, $user, $deviceId);
- return array_merge($tokens, [
- 'user' => $user,
- 'device_id' => $deviceId,
- ]);
- }
- public function logout(string $deviceId): void
- {
- $user = auth()->user();
- if (!$user) {
- return;
- }
- $this->authRepository->deleteUserTokensByDevice($user, $deviceId);
- }
- }
|