Skip to content
Sid Roberts edited this page Jan 26, 2023 · 5 revisions

Version Requirements

Installing

Install using Composer:

composer require sidroberts/phalcon-authmiddleware

For more information on the available releases, check out the Changelog.

You'll need to add the event to the dispatcher DI service:

use Phalcon\Mvc\Dispatcher;

$di->set(
    "dispatcher",
    function () use ($di) {
        $dispatcher = new Dispatcher();

        // ...

        $eventsManager = $di->getShared("eventsManager");

        $eventsManager->attach(
            "dispatch:beforeExecuteRoute",
            new \Sid\Phalcon\AuthMiddleware\Event()
        );

        $dispatcher->setEventsManager($eventsManager);

        // ...

        return $dispatcher;
    },
    true
);

Now, you can create middleware classes:

namespace Example\AuthMiddleware;

use Phalcon\Mvc\User\Plugin;
use Sid\Phalcon\AuthMiddleware\MiddlewareInterface;

class MustBeLoggedIn extends Plugin implements MiddlewareInterface
{
    public function authenticate() : bool
    {
        $loggedIn = $this->auth->isLoggedIn();

        if (!$loggedIn) {
            $this->flash->error(
                "You must be logged in."
            );

            $this->response->redirect(
                "login"
            );

            return false;
        }

        return true;
    }
}
Clone this wiki locally