Created
November 9, 2018 11:45
-
-
Save Kcko/492ef7a19f43e64b0e8da9afa228721c to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?php | |
declare(strict_types=1); | |
namespace App\Forms; | |
use Nette; | |
use Nette\Application\UI\Form; | |
use Nette\Security\User; | |
final class SignInFormFactory | |
{ | |
use Nette\SmartObject; | |
/** @var FormFactory */ | |
private $factory; | |
/** @var User */ | |
private $user; | |
public function __construct(FormFactory $factory, User $user) | |
{ | |
$this->factory = $factory; | |
$this->user = $user; | |
} | |
public function create(callable $onSuccess): Form | |
{ | |
$form = $this->factory->create(); | |
$form->addText('username', 'Username:') | |
->setRequired('Please enter your username.'); | |
$form->addPassword('password', 'Password:') | |
->setRequired('Please enter your password.'); | |
$form->addCheckbox('remember', 'Keep me signed in'); | |
$form->addSubmit('send', 'Sign in'); | |
$form->onSuccess[] = function (Form $form, \stdClass $values) use ($onSuccess): void { | |
try { | |
$this->user->setExpiration($values->remember ? '14 days' : '20 minutes'); | |
$this->user->login($values->username, $values->password); | |
} catch (Nette\Security\AuthenticationException $e) { | |
$form->addError('The username or password you entered is incorrect.'); | |
return; | |
} | |
$onSuccess(); | |
}; | |
return $form; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment