# Authorizations

> Laravel Rest Api exposes a lot of information and it is crucial for your applications to secure the access to resources. Thankfully, Laravel Rest Api seamlessly integrates with Laravel, ensuring a straightforward approach to securing your API.

<warning>

Laravel Rest Api doesn't provide authentication, you can define it on your project using for example `Laravel Passport`, `Laravel Sanctum` or make your own.

</warning>

## Policies

To restrict access to viewing, creating, updating, or deleting resources, Laravel Rest Api relies on Laravel's [authorization policies](https://laravel.com/docs/authorization#creating-policies).
By default, Laravel automatically associates the appropriate authorization policies with your models.
You can also manually associate a policy in your `AppServiceProvider`. In either case, Laravel REST API will use it automatically, without requiring any additional configuration.

This concerns the following methods:

<table>
<thead>
  <tr>
    <th>
      Policy method
    </th>
    
    <th>
      Used when
    </th>
  </tr>
</thead>

<tbody>
  <tr>
    <td>
      <code>
        viewAny
      </code>
    </td>
    
    <td>
      Listing / searching resources
    </td>
  </tr>
  
  <tr>
    <td>
      <code>
        view
      </code>
    </td>
    
    <td>
      Reading a specific model
    </td>
  </tr>
  
  <tr>
    <td>
      <code>
        create
      </code>
    </td>
    
    <td>
      Creating a new model
    </td>
  </tr>
  
  <tr>
    <td>
      <code>
        update
      </code>
    </td>
    
    <td>
      Updating an existing model
    </td>
  </tr>
  
  <tr>
    <td>
      <code>
        replicate
      </code>
    </td>
    
    <td>
      Duplicating a model via mutate
    </td>
  </tr>
  
  <tr>
    <td>
      <code>
        delete
      </code>
    </td>
    
    <td>
      Deleting a model
    </td>
  </tr>
  
  <tr>
    <td>
      <code>
        restore
      </code>
    </td>
    
    <td>
      Restoring a soft-deleted model
    </td>
  </tr>
  
  <tr>
    <td>
      <code>
        forceDelete
      </code>
    </td>
    
    <td>
      Force-deleting a model
    </td>
  </tr>
</tbody>
</table>

For example, to determine which users are allowed to view a User model, you simply need to define a `view` method on the model's corresponding policy class:

```php
<?php

namespace App\Policies;

use App\Models\User;
use Illuminate\Auth\Access\HandlesAuthorization;

class UserPolicy
{
    use HandlesAuthorization;

    /**
     * Determine whether the user can view the user.
     *
     * @param  \App\Models\User  $user
     * @param  \App\Models\User  $model
     * @return mixed
     */
    public function view(User $user, User $model)
    {
        return $user->is($model);
    }
}
```

### Disable Authorizations

By default, authorizations are enabled but you can disable them in certain situations.

<note>

When you are mutating / searching distant relations, this will apply the relation resource state.

</note>

### Globally

In your `config/rest.php` file, you can directly specify to disable this feature:

```php
[
    // ...
    'authorizations' => [
        'enabled' => false, // Switch this to false
    ]
    // ...
]
```

### Resource

If you want to disable this feature for certain resources only, you can use the `DisableAuthorizations` trait on your resource file:

```php [UserResource.php]
class UserResource extends Resource
{
    use \Lomkit\Rest\Concerns\Resource\DisableAuthorizations;
    
    // ...
}
```

## Relationships

Because you may want to be able to control what models front end users are linking, Laravel Rest Api provides full control over relationship operations.

### Attaching / Detaching

When working with relationships, Laravel Rest Api uses a simple policy method naming convention: `attach{Model}` / `detach{Model}`.

To illustrate this convention, let's assume your application has a `Post` resource and a `Comment` resource. If you would like to authorize which users can add comments to a post, you should define an `attachComment` method on your post model's policy class:

```php
<?php

namespace App\Policies;

use App\Models\Comment;
use App\Models\User;
use App\Models\Post;
use Illuminate\Auth\Access\HandlesAuthorization;

class PostPolicy
{
    use HandlesAuthorization;

    /**
     * Determine whether the user can attach a comment to a post.
     *
     * @param  \App\Models\User    $user
     * @param  \App\Models\Post    $post
     * @param  \App\Models\Comment $comment
     * @return mixed
     */
    public function attachComment(User $user, Post $post, Comment $comment)
    {
        return true;
    }

    /**
     * Determine whether the user can detach a comment from a post.
     *
     * @param  \App\Models\User    $user
     * @param  \App\Models\Post    $post
     * @param  \App\Models\Comment $comment
     * @return mixed
     */
    public function detachComment(User $user, Post $post, Comment $comment)
    {
        return true;
    }
}
```

## Cache

In order to make Laravel Rest Api faster, authorizations are cached automatically.

### Cache key

By default, caches is proper to each authenticated user and resource. If you want to change this behavior, please override the `getCacheKey` method in your resource:

```php
class UserResource
{
    /**
     * Get the authorization cache key.
     *
     * @param RestRequest $request
     *
     * @return string
     */
    public function getAuthorizationCacheKey(RestRequest $request, string $identifier)
    {
        $class = Str::snake((new \ReflectionClass($this))->getShortName());

        return sprintf(
            'rest.authorization.%s.%s.%s',
            $class,
            $identifier,
            $request->user()?->getKey()
        );
    }
}
```

### Cache time to live

Cache is by default persisted for 5 minutes, if you want to change this feature:

#### Globally

In your `config/rest.php` file, you can directly specify the number of minutes for the cache:

```php
[
    // ...
    'authorizations' => [
        'cache'   => [
            'default' => 5 // Cache minutes by default
        ],
    ],
    // ...
]
```

#### Resource

If you want to adjust this in your resource, please add the `cacheFor` method in your resource:

```php
class UserResource
{
    /**
     * Determine for how much time the cache should be kept.
     *
     * @return \DateTimeInterface|\DateInterval|float|int|null
     */
    public function authorizationCacheFor()
    {
        return now()->addMinutes(5);
    }
}
```

### Disable cache

#### Globally

If you want to disable it globally, change your config in the `rest.php` file

```php
<?php

return [
    /*
    |--------------------------------------------------------------------------
    | Rest Authorizations
    |--------------------------------------------------------------------------
    |
    | This is the feature that automatically binds to policies to validate incoming requests.
    | Laravel Rest Api will validate each models searched / mutated / deleted to avoid leaks in your API.
    |
    */

    'authorizations' => [
        'cache'   => [
            'enabled' => false, // Set this to false
        ],
    ],
]
```

#### Resource

If you want to disable this feature for certain resources only, you can use the `DisableAuthorizationsCache` trait on your resource file:

```php [UserResource.php]
class UserResource extends Resource
{
    use \Lomkit\Rest\Concerns\Resource\DisableAuthorizationsCache;
    
    // ...
}
```
