Kufrik/app/Model/Security/Authentificator.php

72 lines
2.4 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, JMENO, PRIJMENI, DATABASE_NAME, CONNECTION_STRING_KEY
FROM dbo.UZIVATEL
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.UZIVATEL 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,
'jmeno' => trim(($row->JMENO ?? '') . ' ' . ($row->PRIJMENI ?? '')),
'db_name' => $row->DATABASE_NAME, // Nulllable -> KufrikConnectionFactory použije default_db
'connection_key' => $row->CONNECTION_STRING_KEY,
'firma_id' => $firmaId,
]
);
}
}