In this episode, we tackle a pretty important part of team switching—in other words, making sure users can only switch to teams they actually belong to. Right now, our app lets you switch to any team just by passing an ID. That's obviously not great for security, so we want to lock this down!
First, we start by writing a test to check that users cannot switch to a team they don't belong to. We set up the test: create a user, create a different team they're not part of, and try switching to it. We expect this to be forbidden (HTTP 403) and verify that the user's current team does not change.
Initially, we show a couple of approaches to enforce this—for example, just aborting in the controller if the user isn’t attached to the team. But since we'll need this kind of authorization in other places (like roles and permissions), we refactor! We create a dedicated policy (TeamPolicy) for handling authorization logic related to teams.
With the policy in place, we use Laravel's gate mechanism to authorize the action in a cleaner, re-usable way. Our tests now pass, but we take it a step further: we refactor to use a form request for SetCurrentTeamRequest
. This moves the authorization logic out of the controller and into the request, tidying things up and keeping our controllers neat.
After running the tests and making sure everything works, we're left with a clean, secure way to handle team switching. By the end, you’ll have a robust foundation for managing which teams users have access to, getting ready for more advanced roles and permissions later in the course.