2023-08-20 22:35:58 +00:00
|
|
|
<?php
|
|
|
|
|
|
|
|
namespace App\Services;
|
|
|
|
|
|
|
|
use App\Exceptions\InvalidCredentialsException;
|
|
|
|
use App\Models\User;
|
|
|
|
use App\Repositories\UserRepository;
|
2024-01-09 23:26:16 +00:00
|
|
|
use App\Values\CompositeToken;
|
2023-08-20 22:35:58 +00:00
|
|
|
use Illuminate\Hashing\HashManager;
|
|
|
|
|
|
|
|
class AuthenticationService
|
|
|
|
{
|
|
|
|
public function __construct(
|
|
|
|
private UserRepository $userRepository,
|
|
|
|
private TokenManager $tokenManager,
|
|
|
|
private HashManager $hash
|
|
|
|
) {
|
|
|
|
}
|
|
|
|
|
2024-01-09 23:26:16 +00:00
|
|
|
public function login(string $email, string $password): CompositeToken
|
2023-08-20 22:35:58 +00:00
|
|
|
{
|
|
|
|
/** @var User|null $user */
|
|
|
|
$user = $this->userRepository->getFirstWhere('email', $email);
|
|
|
|
|
|
|
|
if (!$user || !$this->hash->check($password, $user->password)) {
|
|
|
|
throw new InvalidCredentialsException();
|
|
|
|
}
|
|
|
|
|
2023-10-10 15:19:00 +00:00
|
|
|
if ($this->hash->needsRehash($user->password)) {
|
|
|
|
$user->password = $this->hash->make($password);
|
|
|
|
$user->save();
|
|
|
|
}
|
|
|
|
|
2024-01-09 23:26:16 +00:00
|
|
|
return $this->tokenManager->createCompositeToken($user);
|
2023-08-20 22:35:58 +00:00
|
|
|
}
|
|
|
|
|
|
|
|
public function logoutViaBearerToken(string $token): void
|
|
|
|
{
|
|
|
|
$this->tokenManager->deleteCompositionToken($token);
|
|
|
|
}
|
|
|
|
}
|