0

When a user attempts to login, I check a 3rd-party to make sure they should have access. If they shouldn't, I need to stop them logging in. I have this working, but I could only get it working by setting my own session var and it's hacky and there must be a better way!

I'm using the EVENT_BEFORE_AUTHENTICATE event like so:

use craft\elements\User;
use craft\events\AuthenticateUserEvent;

// ...

Event::on(
    User::class,
    User::EVENT_BEFORE_AUTHENTICATE,
    function (AuthenticateUserEvent $event) {

        //Empty a session var to use.
        Craft::$app->getSession()->remove('myCheckInvalidUser');

        //Do my checks.
        $checksuccess = $this->doMyChecks($event->sender->username, $event->password);
        if (!$checksuccess) {

            // This is where I feel I should be calling some Craft:: invalid login 
            // call or something. But instead I'm doing this:

            Craft::$app->getSession()->set('myCheckInvalidUser', true);

        } else {

            $success = Craft::$app->user->loginByUserId($user->id);
            Craft::$app->response->redirect($referrer);
            return Craft::$app->end();

        }
    }
);

Then in a second hook for EVENT_BEFORE_LOGIN I have:

use yii\web\UserEvent;
use craft\web\User as WebUser;

// ...

Event::on(
    WebUser::class,
    WebUser::EVENT_BEFORE_LOGIN,
    function (UserEvent $event) {

        $myCheckInvalidUser = Craft::$app->getSession()->get('myCheckInvalidUser');

        if (!$myCheckInvalidUser === false) {
            $event->isValid = false; //Shuts this down, woop.
        }

    }
);

Any and all suggestions, however brief, appreciated. Even if it's to do with some bad coding that doesn't answer my question, because this event malarkey and knowing which bits to use is doing my head in and I want to learn!

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Browse other questions tagged or ask your own question.