Presmerovanie formuláru do Autentifikátoru

Br0visT
Člen | 17
+
0
-

Zdravím, mám SignPresenter.php:

protected function createComponentSignInForm(): Form
	{
		$form = new Form;
		$form->setRenderer(new BootstrapRenderer);
		$form->addEmail('email', 'Email:')
			->setRequired('Vypíšte prihlasovací email.');

		$form->addPassword('password', 'Heslo:')
			->setRequired('Vypíšte heslo.');

		$form->addSubmit('submit', 'Prihlásiť');

		$form->onSuccess[] = [$this, 'signInFormSucceeded'];
		return $form;
	}

	public function signInFormSucceeded(Form $form, \stdClass $values): void
	{
		try {
			$this->getUser()->login($values->email, $values->password);
			$this->redirect('Homepage:');

		} catch (Nette\Security\AuthenticationException $e) {
			$form->addError('Nesprávne prihlasovacie meno alebo heslo.');
		}
	}

v ktorom som doteraz takto riešil prihlásovanie.
No keďže nechcem pracovať s configom ale s reálnou databázou, vytvoril som si MyAuthentificator.php:

<?php
namespace App;
use Nette;

class MyAuthenticator implements Nette\Security\IAuthenticator
{
	private $database;
	private $passwords;

	public function __construct(Nette\Database\Context $database, Nette\Security\Passwords $passwords)
	{
		$this->database = $database;
		$this->passwords = $passwords;
	}

	public function authenticate(array $credentials): Nette\Security\IIdentity
	{
		[$email, $password] = $credentials;

		$row = $this->database->table('users')
			->where('email', $email)
			->fetch();

		if (!$row) {
			throw new Nette\Security\AuthenticationException('Používateľ sa nenašiel.');
		}

		if (!$this->passwords->verify($password, $row->password)) {
			throw new Nette\Security\AuthenticationException('Nesprávne heslo.');
		}

		return new Nette\Security\Identity(
			$row->id,
			$row->role, // nebo pole více rolí
			['email' => $row->$email]
		);
	}
}
?>

Otázka je ako prepojiť ten formulár s tým autentifikátorom?

Kamil Valenta
Člen | 752
+
+1
-

Zaregistruj si ho v configu:

services:
	authenticator: App\MyAuthenticator
Br0visT
Člen | 17
+
0
-

kamil_v napsal(a):

Zaregistruj si ho v configu:

services:
	authenticator: App\MyAuthenticator

Mám ho tam a stále, keď sa snažím napísať id a heslo, ktoré jasne vidím, že je v databáze, neprihlási ma.

CZechBoY
Člen | 3608
+
+1
-

V databazi musis mit hash, jelikoz verifikujes hash hesla.

Editoval CZechBoY (13. 8. 2020 20:42)

Br0visT
Člen | 17
+
0
-

CZechBoY napsal(a):

V databazi musis mit hash, jelikoz verifikujes hash hesla.

No ani tak to nejde. Niečo si nevšímam/nevedome robím zle.
Skúsim tu napísať kódy, keby niekto niečo našiel, budem rád.

SignPresenter.php:

<?php
namespace App\Presenters;

use Nette;
use Tomaj\Form\Renderer\BootstrapRenderer;
use Nette\Application\UI\Form;
use Nette\Security\Passwords;


class SignPresenter extends Nette\Application\UI\Presenter
{

	private $database;

    public function __construct(Nette\Database\Context $database)
    {
        $this->database = $database;
    }


	protected function createComponentSignInForm(): Form
	{
		$form = new Form;
		$form->setRenderer(new BootstrapRenderer);
		$form->addEmail('email', 'Email:')
			->setRequired('Vypíšte prihlasovací email.');

		$form->addPassword('password', 'Heslo:')
			->setRequired('Vypíšte heslo.');

		$form->addSubmit('submit', 'Prihlásiť');

		$form->onSuccess[] = [$this, 'signInFormSucceeded'];
		return $form;
	}

	public function signInFormSucceeded(Form $form, \stdClass $values): void
	{
		try {
			$this->getUser()->login($values->email, $values->password);
			$this->redirect('Homepage:');

		} catch (Nette\Security\AuthenticationException $e) {
			$form->addError('Nesprávne prihlasovacie meno alebo heslo.');
		}
	}

	public function actionOut(): void
	{
		$this->getUser()->logout();
		$this->flashMessage('Odhlásenie bolo úspešné.');
		$this->redirect('Homepage:');
	}

	protected function createComponentSignUpForm(): Form
	{
		if ($this->getUser()->isLoggedIn()) {
			$this->error('Pre registráciu sa musíte odhlásiť.');
			$this->redirect('Homepage:');
        }
		$form = new Form;
		$form->setRenderer(new BootstrapRenderer);
		$form->addEmail('email', 'Email:')
			->setRequired('Vypíšte prihlasovací email.');

		$form->addPassword('password', 'Heslo:')
			->setRequired('Vypíšte heslo.');

		$form->addSubmit('submit', 'Registrovať');

		$form->onSuccess[] = [$this, 'signUpFormSucceeded'];
		return $form;
	}

	public function signUpFormSucceeded(Form $form, array $values): void{
		if ($this->getUser()->isLoggedIn()) {
            $this->error('Pre registráciu sa odhláste!');
        }
        else{
			$result = $this->database->table('users')->where('email', $values['email'])->fetch();

			if($result){
				$form->addError('Tento email je už zaregistrovaný.');
			}
			else{
				$passwords = new Passwords(PASSWORD_BCRYPT, ['cost' => 12]);
				$res = $passwords->hash($values['password']);
				$this->database->table('users')->insert([
					'user_id' => 0,
					'email' => $values['email'],
					'password' => $res,
				]);
				$this->flashMessage('Ďakujeme za registráciu, môžete sa prihlásiť.');
				$this->redirect('this');
			}
        }
	}
}
?>

MyAuthenticator.php:

<?php
namespace App;
use Nette;


class MyAuthenticator implements Nette\Security\IAuthenticator
{
	private $database;
	private $passwords;

	public function __construct(Nette\Database\Context $database, Nette\Security\Passwords $passwords)
	{
		$this->database = $database;
		$this->passwords = $passwords;
	}

	public function authenticate(array $credentials): Nette\Security\IIdentity
	{
		[$email, $password] = $credentials;

		$row = $this->database->table('users')
			->where('email', $email)
			->fetch();

		if (!$row) {
			throw new Nette\Security\AuthenticationException('Používateľ sa nenašiel.');
		}

		if (!$this->passwords->verify($password, $row->password)) {
			throw new Nette\Security\AuthenticationException('Nesprávne heslo.');
		}

		return new Nette\Security\Identity(
			$row->id,
			$row->role, // nebo pole více rolí
			['email' => $row->$email]
		);
	}
}
?>

local.neon:

parameters:


database:
	dsn: 'mysql:host=127.0.0.1;dbname=zizzy'
	user: root
	password: root123


services:
	authenticator: App\MyAuthenticator
	security.passwords: Nette\Security\Passwords(::PASSWORD_BCRYPT, [cost: 12])

Keby ste niečo potrebovali doplniť, dajte vedieť. Ďakujem

EDIT: Mal som limitovanú dĺžku hesla na 20 znakov – nevošiel sa mi do tabuľky hash :)

Editoval Br0visT (13. 8. 2020 22:34)

CZechBoY
Člen | 3608
+
0
-

jn, zrovna jsem to chtěl napsat s tou délkou sloupce.
btw používej tu službu Passwords i v signup.