User::getRoles() assumed unauthenticated users are anonymous

Created on 10 March 2017, over 7 years ago
Updated 7 February 2023, almost 2 years ago

Problem/Motivation

With it's locked roles, User::getRoles() assumes that users are either authenticated or anonymous. Although this is true in core, it causes problems for contrib that has unauthenticated users who have a user ID (i.e. are not anonymous).

This is mitigated by the fact any contrib implementing that kind of feature would likely be overriding the User class anyway, but would be nice not to have to override User::getRoles() for one tiny change.

Proposed resolution

Explicitly check User::isAnonymous() rather than assuming.

API changes

No change in behaviour for core.

🐛 Bug report
Status

Needs work

Version

10.1

Component
User module 

Last updated about 4 hours ago

Created by

🇬🇧United Kingdom andrewbelcher

Live updates comments and jobs are added and updated live.
  • Needs tests

    The change is currently missing an automated test that fails when run with the original code, and succeeds when the bug has been fixed.

Sign in to follow issues

Comments & Activities

Not all content is available!

It's likely this issue predates Contrib.social: some issue and comment data are missing.

  • 🇺🇸United States smustgrave

    This issue is being reviewed by the kind folks in Slack, #needs-review-queue-initiative. We are working to keep the size of Needs Review queue [2700+ issues] to around 400 (1 month or less), following Review a patch or merge request as a guide.

    Previously tagged for tests in #13 which still need to happen.

  • 🇮🇳India anup.sinha Bengaluru

    Hi All,

    As per my analysis, we have to modify the below test method.

    File - \core\modules\user\tests\src\Unit\Plugin\Core\Entity\UserTest.php
    Test Function Name - testUserGetRoles()

    But the problem here is that the authenticated/anonymous role is being set through the createUserSession() method not testUserGetRoles() method. So we have to modify the parameters of the createUserSession() function like below and set the anonymous role only when it is set. But then I have to modify the arguments in the parent class UserSessionTest as well.

    protected function createUserSession(array $rids = [], $authenticated = FALSE, $anonymous = FALSE) {
    $id = '';
    if ($authenticated) {
    $id = 2;
    }
    elseif ($anonymous) {
    $id = 0;
    }

    So just wanted to check if anyone has a better solution to add the test coverage for this change.

    Thanks & Regards,
    Anup

Production build 0.71.5 2024