We have moved our forum to GitHub Discussions. For questions about Phalcon v3/v4/v5 you can visit here and for Phalcon v6 here.

MIddleware for some routes in micro

Hello! I am trying to make an authentication system using phalcon's micro, with Controller handler. The system will generate a token at login and I need a middleware to check if the token is valid, but not on all routes. The register route should not be checked. I made an event listener and attached it.

$eventsManager = new Manager();
$eventsManager->attach('micro', new CheckTokenMiddleware());

$app->setEventsManager($eventsManager);

For routes I'm using micro collection.

$usersCollection = new \Phalcon\Mvc\Micro\Collection();
$usersCollection->setHandler('\App\Controllers\UserController', true);
$usersCollection->setPrefix('/user');
$usersCollection->post('/register', 'register');
$usersCollection->get('/([0-9]+)', 'get');

$app->mount($usersCollection);

How could I skip the register route when checking if token is valid?

I don't have much experience with Micro, so I'm not sure exactly how it differs from a full application. However, in a full application, I would use an ACL. that ACL could say that the register routes can be accessible by anyone - which would cause the ACL check to always succeed.

If all you're requiring for authorization is a simple valid/invalid token check, then maybe just configure your middleware to ignore certain urls. Matching the url against :^/register.*: should work.

你可以参考这里的代码 https://docs.phalcon.io/3.4/zh-cn/application-micro

<?php

use Phalcon\Mvc\Micro;
use Phalcon\Events\Event;
use Phalcon\Events\Manager as EventsManager;

// Create a events manager
$eventsManager = new EventsManager();

$eventsManager->attach(
    'micro:beforeExecuteRoute',
    function (Event $event, $app) {
        if ($app->session->get('auth') === false) {
            $app->flashSession->error("The user isn't authenticated");

            $app->response->redirect('/');
            $app->response->sendHeaders();

            // Return (false) stop the operation
            return false;
        }
    }
);

$app = new Micro();

// Bind the events manager to the app
$app->setEventsManager($eventsManager);