Score:2

How do I switch user account in drush to test permissions?

ph flag

I'm playing around with the D9 Groups module and I want to test the access control in drush, either using drush php or writing a script and using drush scr.

In drush 8 I would always use drush -u to run as a specific user but that option seems to have disappeared in drush 10.

What's the easiest way to either run drush as a specific user or switch the user in drush php or a script?

Edit: I'm working around this by making calls to json:api endpoints instead but it would still be nice to validate this in drush.

cn flag
I know you're asking for Drush but it's worth noting that the Devel module provides a block for switching users, which can be useful in a local dev environment.
Lambic avatar
ph flag
Yeah testing in browser is fine, but I specifically need to test at the cli or api level.
Score:0
cn flag

Hi In your test you could use account switcher service @ core/lib/Drupal/Core/Session/AccountSwitcherInterface.php

For example,

// You can switch to any type of account here.
$this->accountSwitcher->switchTo(new UserSession(['uid' => 1]));

// Using try-catch-finally we make sure we be never leave it by accident.
try {
  // Whatever you want to test
}
catch (\Exception $e) {
  $this->logger->get(self::MODULE_NAME)->error($e->getMessage());
} finally {
  // Making sure we always switch back. Very important if you using u1.
  $this->accountSwitcher->switchBack();
}
mangohost

Post an answer

Most people don’t grasp that asking a lot of questions unlocks learning and improves interpersonal bonding. In Alison’s studies, for example, though people could accurately recall how many questions had been asked in their conversations, they didn’t intuit the link between questions and liking. Across four studies, in which participants were engaged in conversations themselves or read transcripts of others’ conversations, people tended not to realize that question asking would influence—or had influenced—the level of amity between the conversationalists.