Skip to content

Sample Login Page Setup

Alexandre Lemaire edited this page Dec 14, 2016 · 1 revision

Here's what a login page might look like. Your mileage may vary of course!

Controller

use CirclicalUser\Exception\BadPasswordException;
use CirclicalUser\Exception\NoSuchUserException;
use CirclicalUserUI\Form\LoginForm;
use Zend\Mvc\Controller\AbstractActionController;
use Zend\View\Model\ViewModel;

class LoginController extends AbstractActionController
{
    private $loginForm;

    public function __construct(LoginForm $loginForm)
    {
        $this->loginForm = $loginForm;
    }

    /**
     * Main action, hit when the site is loaded on the client side
     *
     * @return ViewModel
     */
    public function indexAction()
    {
        $user = $this->auth()->getIdentity();

        if ($user) {
            return $this->redirect()->toUrl("/dashboard");
        }

        $viewModel = new ViewModel([
            'form' => $this->loginForm,
        ]);

        return $viewModel;
    }


    /**
     * Submit action!
     */
    public function submitAction()
    {
        return $this->json()->wrap(function () {

            if (!$this->getRequest()->isPost()) {
                throw new \Exception("Sorry, please try again! (Error: PR015).");
            }

            $form = $this->loginForm;
            $form->setData($this->params()->fromPost());
            if ($form->isValid()) {

                try {
                    $this->auth()->authenticate(
                        $form->get('email')->getValue(),
                        $form->get('password')->getValue()
                    );

                    return ['message' => "Success! Welcome back, one second while we gather your fishing rods..."];
                } catch (NoSuchUserException $exception) {

                } catch (BadPasswordException $exception) {

                }
                throw new \Exception("Sorry! That email and password combination was incorrect.");
            }

            return [
                'form_errors' => $form->getMessages(),
                'message' => "Sorry! That email and password combination didn't work.",
                'success' => false,
            ];

        });
    }
}

Form

use Zend\Captcha;
use Zend\Form\Element\Password;
use Zend\Form\Form;
use Zend\Form\Element\Hidden;
use CirclicalRecaptcha\Form\Element\Recaptcha;


class LoginForm extends Form
{

    const EMAIL = 'email';

    public function __construct($name, $options = [])
    {
        parent::__construct($name, $options);
    }

    public function init()
    {
        
        $this->add([
            'name' => self::EMAIL,
            'type' => self::EMAIL,
            'attributes' => [
                'maxlength' => 254,
                'id' => 'email-input',
                'placeholder' => _('Email'),
            ],
        ]);

        $this->add([
            'name' => 'password',
            'type' => Password::class,
            'attributes' => [
                'maxlength' => 24,
                'autocomplete' => 'off',
                'id' => 'password-input',
                'placeholder' => _('Password'),
            ],
        ]);

        $this->add([
            'name' => 'g-recaptcha-response',
            'type' => Recaptcha::class,
            'options' => [
                'label' => _("Please complete the challenge below"),
                'label_attributes' => [
                    'class' => 'captcha-label',
                ],
            ],
            'attributes' => [
                'id' => 'captcha-area',
            ],
        ]);

        $this->add([
            'name' => 'axis',
            'type' => Hidden::class,
        ]);
    }

}

Form Factory

use CirclicalUserUI\Form\LoginForm;
use CirclicalUserUI\InputFilter\LoginInputFilter;
use Zend\ServiceManager\FactoryInterface;
use Zend\ServiceManager\ServiceLocatorInterface;

class LoginFormFactory implements FactoryInterface
{
    /**
     * {@inheritdoc}
     */
    public function createService(ServiceLocatorInterface $serviceLocator)
    {
        $serviceManager = $serviceLocator->getServiceLocator();
        try {
            $form = new LoginForm('login');
            $form->setInputFilter(
                $serviceManager->get('InputFilterManager')->get(LoginInputFilter::class)
            );
        } catch (\Exception $x) {
            die($x->getMessage());
        }

        return $form;
    }
}

Clone this wiki locally