Skip to content

[5.x]: yii\base\ErrorException: Attempt to read property "username" on null #18569

@daanj1998

Description

@daanj1998

What happened?

Description

In UsersController::actionImpersonateWithToken(), when impersonation fails, the error logging on line 531 calls $userSession->getIdentity()->username without a null check. Since the impersonate-with-token action allows anonymous access and the visitor has no active session, getIdentity() returns null, causing an ErrorException.
The relevant code in src/controllers/UsersController.php:

if (!$success) {
    $this->setFailFlash(Craft::t('app', 'There was a problem impersonating this user.'));
    Craft::error(sprintf('%s tried to impersonate userId: %s but something went wrong.',
        $userSession->getIdentity()->username, $userId), __METHOD__);
    return null;
}

$userSession->getIdentity() is null because the visitor opening the impersonation URL is not logged in which is the expected use case, since impersonation URLs are meant to be opened in a separate browser or incognito window.

Steps to reproduce

  1. Log in to the Craft CP as an admin
  2. Generate an impersonation URL for another user (e.g. via the user's edit screen)
  3. Open the impersonation URL in a different browser or incognito window (where you are not logged in)
  4. If the login step within actionImpersonateWithToken fails for any reason (e.g. the target user has been deactivated, deleted, or the session login fails), the error is triggered

Expected behavior

When impersonation via token fails, a friendly error flash message should be shown and the failure should be logged gracefully. The Craft::error() call should handle the case where there is no authenticated identity, for example by using $prevUserId or a fallback string like "unknown".

Actual behavior

An unhandled ErrorException is thrown instead of showing the failure flash message:

yii\base\ErrorException: Attempt to read property "username" on null
in vendor/craftcms/cms/src/controllers/UsersController.php:531

The error logging line accesses ->username on the return value of $userSession->getIdentity(), which is null because the visitor opening the impersonation URL has no active session. This is the normal use case in my opinion. Impersonation URLs are typically opened in a separate browser or incognito window where no user is logged in.

Craft CMS version

4.9.14

PHP version

8.4

Operating system and version

No response

Database type and version

No response

Image driver and version

No response

Installed plugins and versions

Metadata

Metadata

Assignees

No one assigned

    Labels

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions