Search code examples
phpyii2user-management

Yii2-usuario: extending login process


Working with Yii2-usuario, I want to extend the login process by setting some session variables AFTER the user has logged in successfully.

I tried extending the User model by:

replacing the User class in ./config/web.php:

'modules' => [
    'user' => [
        'class' => Da\User\Module::class,
        'classMap' => [
            'User' => app\models\user\User::class,
        ],
    ],
],

and overloading the Userclass in ./models/users/User.php:

namespace app\models\user;
use Da\User\Model\User as BaseUser;

class User extends BaseUser
{
    public function login(IdentityInterface $identity, $duration = 0)
    {
        $ok = parent::login();
        myNewFeature();
        return $ok;
    }
}

as stated in the docs.

BUT: this login() function never gets executed when a user logs in.

How can I make this work?


Solution

  • The best way to do it is to utilize the events provided by the extension. If you look into the FormEvents you see the following under the SecurityController heading

    • FormEvent::EVENT_BEFORE_LOGIN: Occurs before a user logs into the system
    • FormEvent::EVENT_AFTER_LOGIN: Occurs after a user logs into the system

    So what you need to do is to define an event and add your code there, the docs say to create a file named events.php inside your config folder and then load it into your entry script.

    Here is an example of setting an event for the SecurityController:

    <?php 
    // events.php file
    
    use Da\User\Controller\SecurityController;
    use Da\User\Event\FormEvent;
    use yii\base\Event;
    
    Event::on(SecurityController::class, FormEvent::EVENT_AFTER_LOGIN, function (FormEvent $event) {
        $form = $event->getForm();
    
        // ... your logic here
    });
    

    and then the last part is to load this file in your entry script

    <?php
    defined('YII_DEBUG') or define('YII_DEBUG', true);
    defined('YII_ENV') or define('YII_ENV', 'dev');
    
    require(__DIR__ . '/../../vendor/autoload.php');
    require(__DIR__ . '/../../vendor/yiisoft/yii2/Yii.php');
    require(__DIR__ . '/../../common/config/bootstrap.php');
    require(__DIR__ . '/../config/bootstrap.php');
    
    require(__DIR__ . '/../config/events.php'); // <--- adding events here! :)
    
    $config = yii\helpers\ArrayHelper::merge(
        require(__DIR__ . '/../../common/config/main.php'),
        require(__DIR__ . '/../../common/config/main-local.php'),
        require(__DIR__ . '/../config/main.php'),
        require(__DIR__ . '/../config/main-local.php')
    );
    
    $application = new yii\web\Application($config);
    $application->run();