1

I have a Laravel application using the built-in basic Laravel auth, but in addition to being able to authenticate users, I also need to be able to do things like check permissions and authorize them for given controller actions as well as do things like check the subdomain of the site the user is on and allow them access or not accordingly.

For authorization, I came across Spatie and was able to set that up and get it working. It seems to be fine. However, I'm not sure of the best way to integrate it into my controllers.

If possible, I'd like to check Spatie permissions in controller constructors and block access accordingly, as opposed to checking the authorization in every controller action. Is there a good way to do this in Laravel? How can I either point the user to an unauthorized-access view or redirect them to the login screen, etc. from a controller constructor?

Similarly, if a user tries to perform an action that isn't valid for a given subdomain, how can I block them / redirect them from the constructor? Thank you.

apokryfos
  • 38,771
  • 9
  • 70
  • 114
HartleySan
  • 7,404
  • 14
  • 66
  • 119
  • 1
    Look into using middleware; you can wrap multiple routes (tied to Controllers) and handle this check long before it gets to the constructor of a Controller. – Tim Lewis Mar 04 '19 at 16:47
  • Thanks, Tim. That really helps guide me in the right direction. So thinking about this more, would I basically want to create a new middleware that does all the Spatie and subdomain checks and redirects the user accordingly? Am I able to access `auth()->user()` from middleware? Thanks. – HartleySan Mar 04 '19 at 17:04
  • 1
    For sure :) I use something similar, called Sentinel, which has `Sentinel::getUser()`, which is 100% accessible from any middleware. The same should apply for Spatie (haven't worked with it personally, but should be similar). – Tim Lewis Mar 04 '19 at 17:08
  • That'll work. Thanks a lot. – HartleySan Mar 04 '19 at 17:10

1 Answers1

1

Middleware is the way to go... You can use it in the constructor of your controller or in the route.

https://laravel.com/docs/5.7/middleware

xyLuz
  • 178
  • 1
  • 11