Kufrik/app/Model/Security/Authentificator.php

71 lines
2.3 KiB
PHP

<?php
namespace App\Model\Security;
use Nette\Security\IAuthenticator;
use Nette\Security\SimpleIdentity;
use Nette\Security\AuthenticationException;
use Nette\Security\Passwords;
use Nette\Database\Connection;
class Authenticator implements IAuthenticator
{
private Connection $masterDb;
private Passwords $passwords;
public function __construct(Connection $masterDb, Passwords $passwords)
{
$this->masterDb = $masterDb;
$this->passwords = $passwords;
}
/**
* Nette předává přihlašovací údaje jako pole [$email, $password]
*/
public function authenticate(array $credentials): SimpleIdentity
{
[$email, $password] = $credentials;
// 1. Načtení uživatele podle tvého přesného schématu UZIVATEL
$row = $this->masterDb->fetch(
'SELECT ID, EMAIL, HESLO_HASH, [DATABASE], [SERVER], FIRMA_ID
FROM dbo.LOGIN
WHERE EMAIL = ? AND AKTIVNI = 1',
$email
);
// $passwords = new Passwords(PASSWORD_BCRYPT, ['cost' => 12]);
// bdump($passwords->hash('admin1234'));
if (!$row || !$this->passwords->verify($password, $row->HESLO_HASH)) {
throw new AuthenticationException('Nespravný e-mail nebo heslo.');
}
// 2. Aktualizace času posledního přihlášení
$this->masterDb->query(
'UPDATE dbo.LOGIN SET POSLEDNI_PRIHLASENI = SYSDATETIME() WHERE ID = ?',
$row->ID
);
// 3. Načtení výchozí FIRMA_ID z vazební tabulky UZIVATEL_FIRMA (pokud existuje)
// $firmaRow = $this->masterDb->fetch(
// 'SELECT TOP 1 FIRMA_ID FROM dbo.UZIVATEL_FIRMA WHERE UZIVATEL_ID = ?',
// $row->ID
// );
// Fallback: Pokud vazební tabulka ještě není/nepoužívá se, použije se ID uživatele
//$firmaId = $firmaRow ? $firmaRow->FIRMA_ID : $row->ID;
// 4. Předání dat do Nette Identity
return new SimpleIdentity(
$row->ID,
null, // role
[
'email' => $row->EMAIL,
'database' => $row->DATABASE, // Nulllable -> KufrikConnectionFactory použije default_db
'server' => $row->SERVER,
'firma_id' => (int) $row->FIRMA_ID, // Zpřístupní $user->identity->firma_id
]
);
}
}