7

I have the Spatie Permissions package installed, and I have created policies to restrict access for my models using this package.

However, I'm struggling a bit on the creating a gate to enable certain roles such as 'Admin' and 'Content Editor' to access the Nova dashboard?

I assume it would involve the gate() function in the NovaServiceProvider. Here is what i tried.

   protected function gate()
    {
        Gate::define('viewNova', function ($user) {
             if ($user->hasRole('Admin') || $user->hasRole('Content Editor'))
    {
        return true;
    }
       });
    }
apokryfos
  • 38,771
  • 9
  • 70
  • 114
Adnan
  • 3,129
  • 6
  • 31
  • 36
  • Are you testing this on your local environment or not? – Chin Leung Sep 12 '18 at 16:02
  • No, I would like to implement this for production so that other users can have access to Nova. – Adnan Sep 12 '18 at 17:41
  • What I mean is, are you testing the code you've provided on a local environment? – Chin Leung Sep 12 '18 at 18:10
  • So what the other comments are trying to get at is that the gate() function is ignored if your environment is 'local'. I'm not sure what the reasoning was for that choice, but it does make it difficult to test authentication with Nova. – orrd Sep 23 '18 at 22:22
  • @orrd - Workaround is to override the APP_ENV as part of your testing. For PHPUnit, this is in `phpunit.xml`, and for Dusk this is in `.env.dusk.local`. – LeigerGaming Dec 25 '18 at 16:37

1 Answers1

7

You can achieve what you want like this:

/**
 * Register the Nova gate.
 *
 * This gate determines who can access Nova in non-local environments.
 *
 * @return void
 */
protected function gate()
{
    Gate::define('viewNova', function ($user) {
        return $user->hasAnyRole(['Admin', 'Content Editor']);
    });
}

More information from the documentation on authorization for access to Nova: https://nova.laravel.com/docs/1.0/installation.html#authorizing-nova

Chin Leung
  • 14,621
  • 3
  • 34
  • 58
  • 7
    It's worth repeating that Nova currently ignores your 'viewNova' gate if the environment is "local". So you have to change your environment to test it. I suspect they may change that behavior in the future because it causes confusion. But also there is an issue where if the user is rejected by your 'viewNova' gate, the user can't even logout (in order to login as a different user). – orrd Sep 23 '18 at 22:25
  • @orrd - Workaround is to override the APP_ENV as part of your testing. For PHPUnit, this is in `phpunit.xml`, and for Dusk this is in `.env.dusk.local`. – LeigerGaming Dec 25 '18 at 16:36
  • @orrd Thank you so much for mentioning this. It was driving me crazy that my breakpoint didn't hit the callback function in development but it seemed to work fine in production – Robin van Baalen Jun 17 '19 at 15:31