Skip to content

Instantly share code, notes, and snippets.

@Kcko
Created November 9, 2018 11:45
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save Kcko/492ef7a19f43e64b0e8da9afa228721c to your computer and use it in GitHub Desktop.
Save Kcko/492ef7a19f43e64b0e8da9afa228721c to your computer and use it in GitHub Desktop.
<?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