Login Backen/Frontend oddelene tabulky

Upozornění: Tohle vlákno je hodně staré a informace nemusí být platné pro současné Nette.
Turbo
Člen | 24
+
0
-

Zdravim,
potrebuji poradit jak vyresit dva loginy Backend/Frontend. Hledal jsem snad uz vsude, ale nikde nic aspon se domnivam, ze jsem nic nenasel.
resim to takto:

<?php
$this->user->getStorage()->setNamespace('xxxx');
?>

funguje to, ale potreboval bych, aby pro kazdy modul se uzivatele nacitaly z jine tabulky(user/klient). Vsem dekuji za informace a rady.

CZechBoY
Člen | 3608
+
+1
-

Udělej si 2 formuláře na přihlášení, 2 autentizátory (třída kterou se přihlašuješ). Neimplementuj IAuthenticator (nebo dej v konfiguráku autowired: false).
V každém formuláři si vyžádej ten svůj autentikátor a pomocí něj uživatele přihlaš.

class SignInFormFactory
{
	public function __construct(AuthenticatorFront $aF, AuthenticatorAdmin $aA, Security\User $user)
	{
		$this->authenticatorFront = $aF;
		$this->authenticatorAdmin = $aA;
		$this->user = $user;
	}

	public function createFrontForm()
	{
		$form = new UI\Form;
		$form->addText('name');
		$form->addPassword('pwd');

		$form->onSuccess[] = function($form, array $values) {
			$identity = $this->authenticatorFront->authenticate($values->name, $values->password);
			$this->user->getStorage()->setNamespace('front'); // nastavím namespace
			$this->user->login($identity); // jen uložím přihlášenou identitu uživatele
		};

		return $form;
	}

	public function createAdminForm()
	{
		// analogicky
	}
}

potom v presenterech

class FrontSignPresenter extends UI\Presenter
{
	public function __contstruct(SignInFormFactory $sff)
	{
		$this->signInFormFactory = $sff;
	}

	protected function createComponentSignInForm()
	{
		$form = $this->signInFormFactory->createFronForm();

		$form->onSuccess[] = function () {
			$this->flashMessage('Přihlášeno', 'success');
			$this->redirect('Front:Homepage:defalt');
		};

		return $form;
	}
}

Editoval CZechBoY (1. 3. 2017 11:13)

Turbo
Člen | 24
+
0
-

CZechBoY napsal(a):

Udělej si 2 formuláře na přihlášení, 2 autentizátory (třída kterou se přihlašuješ). Neimplementuj IAuthenticator (nebo dej v konfiguráku autowired: false).
V každém formuláři si vyžádej ten svůj autentikátor a pomocí něj uživatele přihlaš.

Ahoj predem dekuji za radu, vracim se k tomu az tedka.Implementoval jsem IAuthenticator radil jsi pokud pouziji IAuthenticator mam v configu pouzit autowired: false, ale i tak mi to stale hlasi chybu.

Chybova hlaska:
Service ‚security.user‘: Multiple services of type Nette\Security\IAuthenticator found: 62_App_Model_AdminAuthenticator, 63_App_Model_FrontAuthenticator

config.neon

<?php
services:
	- App\Model\AdminAuthenticator
	- App\Model\FrontAuthenticator
	autowired: false
	- App\Forms\FormFactory
	router: App\RouterFactory::createRouter
?>

porad prosim te kde delam chybu predem dekuji

newPOPE
Člen | 648
+
0
-

To je len o syntaxi v .neon a tu mas predpokladam zle.

Skus nieco ako

- [
    class: App\Model\FrontAuthenticator
    autowired: false
  ]
- [
    class: App\Model\AdminAuthenticator
    autowired: false
  ]
Turbo
Člen | 24
+
0
-

Dekuji, ale nerozjel jsem to podle toho. Tak jsem to udelal bez IAuthenticatoru, ale zase se objevila jina chyba. Loginy me plne funguji, ale pokud zadam neplatny user/heslo tak mi to vyhodi vyjimku do ladenky, ale nevykresli se do formu.Poradi jak to upravit?

<?php
public function authenticate($credentials)
    {
	$row = $this->database->table(self::TABLE_NAME)->where(self::COLUMN_EMAIL, $credentials['username'])->fetch();

        if (!$row)
        {
          **throw new \Exception('The username is incorrect.');**
	} elseif (!Passwords::verify($credentials['password'], $row[self::COLUMN_PASSWORD_HASH])) {
            throw new Nette\Security\AuthenticationException('The password is incorrect.', self::INVALID_CREDENTIAL);
	} elseif (Passwords::needsRehash($row[self::COLUMN_PASSWORD_HASH]))

        {
            $row->update(array(
                                self::COLUMN_PASSWORD_HASH => Passwords::hash($password),
                              ));
	}

                /*if(is_null($row->hash))
                {
                   throw new Nette\Security\AuthenticationException('Nepovoleny uživatel.', self::INVALID_CREDENTIAL);
                }*/
            $arr = $row->toArray();
            unset($arr[self::COLUMN_PASSWORD_HASH]);
            return new Nette\Security\Identity($row[self::COLUMN_ID], $row[self::COLUMN_ROLE], $arr);
	}
?>
David Matějka
Moderator | 6445
+
0
-

@Turbo ahoj, vyjimku musis chytat, jako je to treba tady

Turbo
Člen | 24
+
0
-

David Matějka napsal(a):

@Turbo ahoj, vyjimku musis chytat, jako je to treba tady

Ahoj proste nekde delam asi chybu… nejde mi odchytnout vyjimka nevim proc
prihlaseni je v pohode…

LoginFormFactory.php

<?php
class LoginFormFactory extends Object implements ILoginFormFactory
{

	/** @var User */
	private $user;

	/** @var string */
	private $username;

	/** @var IBaseFormFactory */
	private $baseFormFactory;

        /** @var AdminAuthenticator */
        private $aA;

        /** @var AdminAuthenticator */
        private $fA;

	function __construct(User $user, \App\Model\AdminAuthenticator $aA,$username = 'username',IBaseFormFactory $baseFormFactory)
	{
		$this->user = $user;
		$this->username = $username;
		$this->baseFormFactory = $baseFormFactory;
                $this->aA = $aA;
	}


	public function create(callable $onSuccess)
	{
		$form = $this->baseFormFactory->create();

		if ($this->username == 'email') {
			$form->addText('username', 'Email')
				->setAttribute('placeholder', 'Email')
				->setRequired('Please enter your email.')
				->addRule(Form::EMAIL, 'Please enter a valid email address.');
		} else {
			$form->addText('username', 'Username')
				->setAttribute('placeholder', 'Username')
				->setRequired('Please enter your username.');
		}

		$form->addPassword('password', 'Password')
			->setAttribute('placeholder', 'Password')
			->setRequired('Please enter your password.');

		$form->addCheckbox('remember', 'Pamatovat si');
		$form->addSubmit('submit', 'Sign In');
		$form->onSuccess[] = function (Form $form, $values) use ($onSuccess){
                        try
                        {
                            $this->user->setExpiration($values->remeber ? '14 days' : '20 minutes');
                            $identity = $this->aA->authenticate($values);
                            $this->user->getStorage()->setNamespace('admin');
                            $this->user->login($identity);

                        } catch (\Exception $ex) {
                            $form->addError('chyba form: '.$ex);
                            return;
                        }
                        $onSuccess();
                };
                return $form;
	}
}
?>

LoginControl.php

<?php
class LoginControl extends Control
{

	/** @var array */
	public $onLoggedIn;

        /** @var array */
	public $onSuccess;

	/** @var string */
	private $templateFile;

	/** @var ILoginFormFactory */
	private $loginFormFactory;

	/** @var ILoaderFactory */
	private $loaderFactory;

	/** @var string */
	private $pageTitle;

	/** @var string */
	private $pageName;

	/** @var string */
	private $pageMsg;

	/** @var string */
	private $usernameIcon;

	/** @var string */
	private $passwordIcon;


	function __construct(ILoginFormFactory $loginFormFactory, ILoaderFactory $loaderFactory)
	{
		$this->loginFormFactory = $loginFormFactory;
		$this->loaderFactory = $loaderFactory;
		$this->templateFile = __DIR__ . '/templates/LoginControl.latte';
	}


	public function render(array $options = [])
	{
		$this->template->setFile($this->getTemplateFile());
		$this->template->pageTitle = $this->pageTitle;
		$this->template->pageName = $this->pageName;
		$this->template->pageMsg = $this->pageMsg;
		$this->template->usernameIcon = $this->usernameIcon;
		$this->template->passwordIcon = $this->passwordIcon;
		foreach ($options as $key => $value) {
			$this->template->$key = $value;
		}
		$this->template->render();
	}


	protected function createTemplate($class = NULL)
	{
		$template = parent::createTemplate($class);
		if (!array_key_exists('translate', $template->getLatte()->getFilters())) {
			$template->addFilter('translate', function($str){return $str;});
		}
		return $template;
	}


	protected function createComponentForm()
	{
		$form = $this->loginFormFactory->create();
		try
                {
                    $form->onSuccess[] = function($form) {
                    $presenter = $form->getPresenter();
                    $this->onLoggedIn($form);

                        $this->redirect('Homepage:');
		};
                }  catch (Nette\Security\AuthenticationException $ex)
                {
                    $form->addError('chyba');
                }
		return $form;
	}


	protected function createComponentCss()
	{
		return $this->loaderFactory->createCssLoader();
	}


	protected function createComponentJs()
	{
		return $this->loaderFactory->createJavaScriptLoader();
	}

}

?>

provadim prihlaseni takto

<?php
public function authenticate($credentials)
    {
	$row = $this->database->table(self::TABLE_NAME)->where(self::COLUMN_EMAIL, $credentials['username'])->fetch();

        if (!$row)
        {
          throw new \Exception('The username is incorrect.');
	} elseif (!Passwords::verify($credentials['password'], $row[self::COLUMN_PASSWORD_HASH])) {
            throw new Exception('The password is incorrect.');
	} elseif (Passwords::needsRehash($row[self::COLUMN_PASSWORD_HASH]))

        {
            $row->update(array(
                                self::COLUMN_PASSWORD_HASH => Passwords::hash($password),
                              ));
	}


            $arr = $row->toArray();
            unset($arr[self::COLUMN_PASSWORD_HASH]);
            return new Nette\Security\Identity($row[self::COLUMN_ID], $row[self::COLUMN_ROLE], $arr);
	}

?>