# Authorization

Lodata supports controlling access to OData endoints via Laravel gates (opens new window), and by subclassing EntitySet and overriding the relevant methods.

# Gates

Each API request will be checked via an ability named lodata. The gate will receive the standard $user argument, and a Flat3\Lodata\Helper\Gate object.

This object contains the type of request being made, the Lodata object it is being made against, the Lodata Transaction and in the case of an operation the arguments array will be provided.

TIP

When working with Lodata requests you should always get request information via the Transaction object, in case it's a batch request that has its own context.

This should be all the information needed for a gate policy to decide whether to allow the request.

At install time, Lodata runs in a readonly mode. Change the value of the readonly property in config/lodata.php to enable data modification operations.

This example shows how you could allow access to the Users entity set only if the user is an administrator.

<?php

namespace App\Providers;

use Flat3\Lodata\EntitySet;
use Flat3\Lodata\Helper\Gate as LodataGate;
use Illuminate\Http\Request;
use Illuminate\Support\ServiceProvider;
use Illuminate\Support\Facades\Gate;

class LodataServiceProvider extends ServiceProvider
{
    /**
     * Bootstrap any application services.
     *
     * @return void
     */
    public function boot()
    {
        Gate::define('lodata', function (User $user, LodataGate $gate) {
            $resource = $gate->getResource();

            if (!$resource instanceof EntitySet) {
                return true;
            }

            if ($resource->getIdentifier()->getName() === 'Users' && !$user->isAdministrator()) {
               return false;
            }

            return true;
        });
    }
}
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34

# Overrides

For more fine-grained control over the behaviour of the EntitySet you can subclass it and override methods.

This example overrides the create method to only allow "admins" to create entities. Each of query, read, update and delete can also be overridden in this way.

class ProtectedEntitySet extends EloquentEntitySet
{
    public function create(PropertyValues $propertyValues): Entity
    {
        if (!Auth::user()->isAdmin) {
            throw new ForbiddenException('user_not_admin', 'Only an admin can create in this entity set');
        }

        return parent::create($propertyValues);
    }
}
1
2
3
4
5
6
7
8
9
10
11

# EloquentEntitySet

The EloquentEntitySet uses the model's Builder to generate queries. The builder can be modified to provide additional scopes or clauses at runtime.

This entity set adds the active scope to any builder.

class FilteredUserEntitySet extends EloquentEntitySet
{
    public function getBuilder(): Builder
    {
        return parent::getBuilder()->active();
    }
}
1
2
3
4
5
6
7