domovoy/app/Services/AuthService.php

54 lines
1.3 KiB
PHP

<?php
declare(strict_types=1);
namespace Domovoy\Services;
use Domovoy\Models\User;
use Domovoy\Repositories\UserRepository;
class AuthService
{
private UserRepository $userRepository;
public function __construct(UserRepository $userRepository)
{
$this->userRepository = $userRepository;
}
public function authenticate(string $username, string $password): ?User
{
$user = $this->userRepository->findByUsername($username);
if ($user === null) {
return null;
}
if (!password_verify($password, $user->passwordHash)) {
return null;
}
return $user;
}
public function createUser(string $username, string $password): User
{
if ($this->userRepository->findByUsername($username) !== null) {
throw new \RuntimeException("User '{$username}' already exists");
}
$user = new User();
$user->username = $username;
$user->passwordHash = password_hash($password, PASSWORD_ARGON2ID);
$user->createdAt = new \DateTimeImmutable();
$user->updatedAt = new \DateTimeImmutable();
$this->userRepository->save($user);
return $user;
}
public function getUserCount(): int
{
return $this->userRepository->count();
}
}