Switch user to recipient before rendering view

Created on 5 February 2020, over 4 years ago
Updated 17 March 2023, about 1 year ago

I am running into issues when anything in the message requires access control to work. For instance, I have a token that is rendering node content into a message before emailing it.

The problem is that MessageNotifierBase::send() is rendering the view as whichever user happens to be active when it runs. If I send a message interactively using the UI, I get content that is visible to me. If I queue the message to be send on cron, I get only content that is visible to the anonymous user that cron runs as.

When sending mail to a known user in our system, it makes more sense to assume that user's identity when rendering the message to be sure only content that user should see is displayed.

I think this might also fix language problems or other things that depend on knowing who the user is.

The basic idea would be this:

<?php
    // Store the current session, it will be anonymous user if run on cron.
    // Emulate the permissions of the email recipient.
    $accountSwitcher = Drupal::service('account_switcher');
    $mail_account = user_load_by_mail($message>getOwnerId());
    $needs_switch = FALSE;

    // If the message is going to a known, valid, Drupal user, switch accounts.
    if (!empty($mail_account) && !$mail_account->isAnonymous()) {
      $accountSwitcher->switchTo($mail_account);
      $needs_switch = TRUE;
   }

   // Render the content here.

    // Revert back to original user.
    if ($needs_switch) {
      $accountSwitcher->switchBack();
    }
?>
πŸ› Bug report
Status

Needs review

Version

1.0

Component

Code

Created by

πŸ‡ΊπŸ‡ΈUnited States KarenS

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.69.0 2024