| 123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172 |
- <?php
- namespace App\Services;
- use App\Repositories\AuthRepositoryInterface;
- use App\DTO\AuthDTO;
- use App\DTO\RefreshTokenDTO;
- use Illuminate\Support\Str;
- use Illuminate\Support\Facades\Auth;
- class AuthService
- {
- public function __construct(
- protected AuthRepositoryInterface $authRepository,
- ) {
- }
- public function login(AuthDTO $credentials): ?array
- {
- if (!$this->authRepository->attemptLogin(credentials: $credentials)) {
- return null;
- }
- $user = $this->authRepository->findUserByEmail(email: $credentials->email);
- $deviceId = Str::uuid()->toString();
- $accessToken = $this->authRepository->createAccessToken(user: $user, deviceId: $deviceId);
- $refreshToken = $this->authRepository->createRefreshToken(user: $user, deviceId: $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(needle: 'refresh', haystack: $tokenModel->abilities) || $tokenModel->expires_at < now()) {
- return null;
- }
- $user = $tokenModel->tokenable;
- if (!$user) {
- return null;
- }
- $deviceId = Str::afterLast(subject: $tokenModel->name, search: '_');
- $tokens = $this->authRepository->refreshToken($tokenModel, $user, $deviceId);
- return array_merge($tokens, [
- 'user' => $user,
- 'device_id' => $deviceId,
- ]);
- }
- public function logout(): void
- {
- $user = Auth::user();
- $tokenName = $user->currentAccessToken()->name;
- $deviceId = Str::afterLast($tokenName, '_');
- if (!$user) {
- return;
- }
- $this->authRepository->deleteUserTokensByDevice(user: $user, deviceId: $deviceId);
- }
- }
|