Laravel access authenticated user in global scope

laravel global scope
laravel tenant scope
laravel get auth::user
laravel global observer
laravel request->user
laravel auth
laravel custom authentication
laravel findorcreate

I have a multi-user application with the following entity/model relationship.

User belongs to a Company and has many SupportTicket

Users of one company should not have access to the support tickets of other companies - if a user of one company navigates to a url pointing to a support ticket of another company, they should receive a 404 or something equivalent.

I was hoping to define a global scope in the SupportTicket class as follows:

class SupportTicket extends Model {

    protected $fillable = ['company_id'];

    public static function boot() {
        static::addGlobalScope('ofCompany', function(Builder $builder) {
            $authUser = auth()->user();

            $builder->where('company_id', $authUser->company_id);
        });
    }

}

The benefit of a global scope is that it will apply to all queries. Other developers working on the project need not work when retrieving tickets as the right results will always be returned.

For example SupportTicket::all() or SupportTicket::find(5) will always restrict access by user's company.

The challenge I have now is that auth()->user() always returns null as the authenticate middleware has not yet been run.

  1. Is there a way around this?
  2. Has anyone here faced a similar problem and if so how did they go around it?
  3. Is it possible to access the authenticated user in the boot method where the global scope is registered?

Many thanks in advance for any and all responses.

If you are using Tymon's JWT Auth package, you can get auth user like this

$authUser = \JWTAuth::parseToken()->authenticate();

Using data from Auth::user() in global scope, I need to scope by Auth::user()->account_id . However, after wasting hours trying to get it to work, I found this - https://github.com/laravel/  We can add a Global Scope right when the User is Authenticated, which is an event fired when the User is identified inside the application. Using a simple Listener, we can identify the User

You can check inside the boot method if there's an authenticated user using \Auth::check() before calling \Auth::user(). If the Auth middleware is wrapping routes or the controller itself then you can access the authenticated user anywhere using the facade \Auth::user()

Auth user in global scope, Hello. How can I access the current logged in user with auth()->user() in global scope defined in User model itself? When trying to do so, the application returns​  When a given User is authenticated, it’s normal to let him roam inside the application and retrieve records by the given ID, among other things. Take for example an application that manages Photo…

Laravel 5.6.26 introduced Auth::hasUser() to determine if the current user is already authenticated without querying the User model in your database. You can find more details at https://laravel-news.com/laravel-5-6-26

So you could do something like this:

static::addGlobalScope('ofCompany', function(Builder $builder) {
    if( auth()->hasUser() ){
        $builder->where('company_id', auth()->user()->company_id);
    }     
});

Auth::user() not working inside apply function in global scope · Issue , Laravel Version: 5.5.42 PHP Version: 7.1.16 Database Driver & Version: I user Auth::user() inside apply function of global scope and result was that my nginx server You do have use Auth; in the UserVisibilityScope file? Use Laravel Observers and Global Scopes to Create User Multi-Tenancy. Multi-tenant application are pretty common these days, where database are entries can be accessed only by users who created them. In this article, I will show the simplest way to achieve it in Laravel.

Global scoping users with data from the authenticated user crashes , Laravel Version: 5.4.15 PHP Version: 7.1.2 Database Driver & Version: MariaDb 10.1.21 Description: Creating a global scope on the User model with data (list, write and delete), but use the User module for authentication. Route middleware can be used to only allow authenticated users to access a given route. Laravel ships with an auth middleware, which is defined at Illuminate\Auth\Middleware\Authenticate. Since this middleware is already registered in your HTTP kernel, all you need to do is attach the middleware to a route definition: Route::get('profile', function { // Only authenticated users may enter })->middleware('auth');

Use Laravel Observers and Global Scopes to Create User Multi , Final goal is to allow access only to posts that you created yourself. To do that, we could add something like ->where('user_id', auth()->id()) in all  If you would like to remove a global scope for a given query, you may use the withoutGlobalScope method. The method accepts the class name of the global scope as its only argument: User::withoutGlobalScope(AgeScope::class)->get(); Or, if you defined the global scope using a Closure: User::withoutGlobalScope('age')->get();

Authentication routes - Authentication - Laravel, Route middleware can be used to allow only authenticated users to access a the $token variable which contains the password reset token to match the user to​  That’s the power of Laravel Global Scopes. way 2: Lets say, that for some reason, you do not like that simple filtering approach from ‘way 1’ and want an extra method to chain onto query. In this method, I will use approach Laravel team uses in its SoftDelete procedure – also based on scope.

Comments
  • Check this link out (laravel.com/docs/5.3/upgrade#5.3-session-in-constructors) it talks about how you can call the middleware manually inside the controller constructor, maybe you can use that to run the middleware manually...
  • Possible duplicate of Model filters based on the currently authenticated user
  • @Amade thanks for pointing me to it. From that question, I have found the solution. It links to a global scope issue on github which details a really nice solution.