When using "user_email", user load causing exception

Created on 1 March 2023, over 1 year ago
Updated 16 March 2023, over 1 year ago

Problem/Motivation

I discovered this problem while working on an automated test.

When using "user_email" method, the following line is used to load the user.

$control_entity = User::load(\Drupal::currentUser());

This causes the following exception:

"Object of class Drupal\Core\Session\AccountProxy could not be converted to string"

This is because User::load expects the User ID as its argument, but the currentUser object is being passed.

Steps to reproduce

1. Install fresh D9 site.
2. composer require drupal/access_by_ref & drush en access_by_ref
3. Create new content type "Shared by Email" leave everything else default.
4. Under manage fields, Add Field, type Email, label "Owner Emails", Allowed number of values "Unlimited". Everything else use defaults.
5. Under people->roles, add a role, "Additional owners".
6. Under people->permissions, grant "Access by reference" to "Additional owners".
7. Under people, add a user. Username "test", email "test@example.com", password anything you like. Place in group "Additional owners".
8. Content->Add content->Shared by Email. Title: Test. Owner Emails: "test@example.com".
9. Log in as "test".
10. Go to "/node/1/edit" and verify "Access denied".
11. Log in as admin.
12. Go to Configuration->Content Authoring->Set access by reference.
13. Click Add abr configuration.
14. Label: "Abr email access", Bundle: "Shared by Email", Field: "Owner Emails", Reference type: "Users mail". Check "Assign update rights". Leave other fields blank.
15. Click "Save".
16. Select "Flush all caches" (or use "drush cr").
17. Log in as "test".
18. Go to "/node/1".
19. "The website encountered an unexpected error."

Proposed resolution

User:load expects a user ID, so the line could be changed to:

$control_entity = User::load(\Drupal::currentUser()->id());

However, I don't think the full entity needs to be loaded for the _node_access hook, so it might be sufficient to just use the currentUser object:

$control_entity = \Drupal::currentUser();

Remaining tasks

Make change.
Test.

User interface changes

None

API changes

None

Data model changes

None

🐛 Bug report
Status

Fixed

Version

2.0

Component

Code

Created by

🇮🇪Ireland lostcarpark

Live updates comments and jobs are added and updated live.
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.

Production build 0.71.5 2024