codebranch's avatar

Extending Auth facade

I have a setup where a user can belong to multiple teams. After login, a user selects a team which allows the user to act on behalf of that teams. The user current team id selection is stored in session and can be changed during the same user login session, so a user can act on another teams data.

I want to extend Auth facade so that methods like Auth::currentTeamId() or Auth::userHasRoleInCurrentTeam('Owner') is possible. How can this be done. Is there documentation or a blog with some pointers.

Since the current team id is stored in session, how can team id be injected into the Auth class (if its possible to extend)

Would appreciate any pointers

0 likes
3 replies
rodrigo.pedra's avatar

The SessionGuard is macroable which means you can methods to it at runtime.

Add this to your AuthServiceProvider's boot method:

// ./app/Providers/AuthServiceProvider.php

    public function boot()
    {
        $this->registerPolicies();

        SessionGuard::macro('currentTeamId', function () {
            return session('current_team_id'); // use you actual session variable
        });

        SessionGuard::macro('userHasRoleInCurrentTeam', function ($team) {
            return true;  // add custom logic
        });
    }

Some references to understand how macros work:

https://tighten.co/blog/the-magic-of-laravel-macros/

https://www.manifest.uk.com/blog/understanding-laravels-macroable-trait

The docs only mentions it for Collections, but it work for every "Macroable" class:

https://laravel.com/docs/8.x/collections#extending-collections

2 likes

Please or to participate in this conversation.