# Authorization

- [Introduction](#introduction)
- [Authenticating API tokens](#authenticating-api-tokens)
- [Refusing some users everywhere](#refusing-some-users-everywhere)
- [Deciding who may do what](#deciding-who-may-do-what)
- [Using policies](#using-policies)
- [What a refusal looks like](#what-a-refusal-looks-like)
- [Rows a list leaves out](#rows-a-list-leaves-out)
- [What the user may do with a record](#what-the-user-may-do-with-a-record)

## Introduction

Two things protect a Restify API. A middleware decides who the request comes from, and each repository's `authorize` method decides what that user may do. The MCP tools go through both, exactly as the endpoints do.

A repository refuses every request with `403` until it has an `authorize` method that allows `Action::AllowRestify` and the action itself.

## Authenticating API tokens

Restify runs the middleware you give it before every endpoint and every MCP request. The framework's way to authenticate an API is a request guard, described in its `authentication.md` guide under "Stateless authentication". Restify ships one, `restify::auth::Sanctum<User>`, which accepts the Laravel Sanctum tokens a PHP application already uses. The example app uses it in `src/lib.rs`:

```rust
use laravel::auth::Authenticate;
use restify::Restify;
use restify::auth::Sanctum;

providers.add(Sanctum::<User>::new());
providers.add(
    Restify::new()
        .authenticate(Authenticate::via::<Sanctum<User>>())
        .repository::<PostRepository>(),
);
```

Every endpoint and the MCP server now answer `401` without a valid token. [Sanctum tokens](sanctum.md) explains the guard, and [Authentication](authentication.md) the endpoints that log users in and give them tokens. Any other request guard works the same way.

Give the authentication to `authenticate`, not to `middleware`. Both run before every endpoint, in the order you add them, but only `authenticate` is skipped by a [public repository](repositories.md#public-repositories).

## Refusing some users everywhere

Restify for PHP checks a `viewRestify` gate on every request, after the authentication, and answers `401` "Unauthorized to view restify." when it refuses. Here, that gate is a middleware you add after `authenticate`. The example app refuses one user:

```rust
#[middleware]
pub async fn view_restify(request: Request, next: Next) -> laravel::Result<Response> {
    if request.authenticated().await? {
        let user: Option<User> = request.user().await?;

        if user.is_some_and(|user| user.email == "mallory@example.com") {
            return Err(laravel::abort_with(401, "Unauthorized to view restify."));
        }
    }

    Ok(next.run(request).await)
}
```

```rust
Restify::new()
    .authenticate(Authenticate::via::<Sanctum<User>>())
    .middleware(view_restify)
```

The gate also runs on a public repository's routes, where every client is a guest, so it checks `request.authenticated()` before it reads the user. PHP's default gate lets nobody in outside the `local` environment, so a PHP application always defines its own; translate that one.

## Deciding who may do what

`authorize` runs for every request, with the action and, when there is one, the model. This is the example app's `PostRepository`:

```rust
async fn authorize(action: Action, request: &Request, post: Option<&Post>) -> laravel::Result<()> {
    match (action, post) {
        (Action::AllowRestify | Action::Index | Action::Store, _) => Ok(()),
        (Action::Show, Some(post)) => request.authorize(PostPolicy::show, post).await,
        (Action::Update, Some(post)) => request.authorize(PostPolicy::update, post).await,
        (Action::Delete, Some(post)) => request.authorize(PostPolicy::delete, post).await,
        (Action::StoreBulk | Action::UpdateBulk | Action::DeleteBulk, _) => {
            request.authorize(PostPolicy::bulk, ()).await
        }
        _ => Err(laravel::abort(403)),
    }
}
```

| Action | Request | `model` is |
| --- | --- | --- |
| `Action::AllowRestify` | Every request to the repository, first | `None` |
| `Action::Index` | `GET /posts`, `posts-index-tool` | `None` |
| `Action::Show` | `GET /posts/{id}`, `posts-show-tool` | The model |
| `Action::Store` | `POST /posts`, `posts-store-tool` | `None` |
| `Action::Update` | `PUT` or `PATCH /posts/{id}`, `posts-update-tool` | The model, before the change |
| `Action::Delete` | `DELETE /posts/{id}`, `posts-delete-tool` | The model |
| `Action::StoreBulk` | `POST /posts/bulk` | `None` |
| `Action::UpdateBulk` | `POST /posts/bulk/update` | Each model, before the change |
| `Action::DeleteBulk` | `DELETE /posts/bulk/delete` | Each model |
| `Action::Attach("users")` | `POST /teams/{id}/attach/users` | The team, once for each user |
| `Action::Detach("users")` | `POST /teams/{id}/detach/users` | The team, once for each user |
| `Action::Sync("users")` | `POST /teams/{id}/sync/users` | The team, once |

`Action::AllowRestify` is whether the request may use the repository at all. Restify asks it before anything else, also before it looks for a model, so a request that fails it learns nothing of what the repository holds. A repository that doesn't allow it answers `403` to everything. The example app's tags are for admins alone:

```rust
/// Only an admin may use the repository at all, and an admin may do everything.
async fn authorize(action: Action, request: &Request, _tag: Option<&Tag>) -> laravel::Result<()> {
    match action {
        Action::AllowRestify if !is_admin(request).await? => Err(laravel::abort(403)),
        Action::AllowRestify | Action::Index | Action::Show | Action::Store | Action::Update | Action::Delete => {
            Ok(())
        }
        _ => Err(laravel::abort(403)),
    }
}
```

`Attach`, `Detach` and `Sync` name a relationship declared with `Related::many`. During those requests, `restify::relating::<User>(request)` gives the users the change is about. See [Relationships](relationships.md#who-may-attach-detach-and-sync).

The nested routes, such as `GET /posts/{id}/comments`, ask the parent's repository for `Action::Show` on the post, and also `Action::Update` for a create, an update or a delete. Then the comments repository is asked as for its own routes. See [Relationships](relationships.md#nested-routes).

Later versions add actions, so end the `match` with `_ => Err(laravel::abort(403))`: what a repository doesn't name stays refused.

Actions and getters are asked for `Action::AllowRestify` and nothing more of this method. Each one has its own `can_run`, which also refuses everything by default. See [Actions and getters](actions.md#who-may-see-and-run-one).

Return `Ok(())` to allow the action, and an error to refuse it: `Err(laravel::abort(403))`.

For show, update and delete, Restify finds the model first. A model that doesn't exist answers `404` before `authorize` runs for that action.

To read the logged-in user, call `request.user()`:

```rust
let user: User = request.user().await?.or_abort(401)?;
```

## Using policies

Keep the rules themselves in a policy, next to the model, and call it from `authorize` with `request.authorize`:

```rust
use laravel::auth::policy;

pub struct PostPolicy;

#[policy]
impl PostPolicy {
    /// An admin sees every post, an author sees their own, and everyone sees a published one.
    pub fn show(user: &User, post: &Post) -> bool {
        user.is_admin || user.id == post.user_id || post.published_at.is_some()
    }

    pub fn update(user: &User, post: &Post) -> bool {
        user.is_admin || user.id == post.user_id
    }

    pub fn delete(user: &User, post: &Post) -> bool {
        user.is_admin || (user.id == post.user_id && !post.featured)
    }

    /// Only an admin may create, change or delete many posts in one request.
    pub fn bulk(user: &User) -> bool {
        user.is_admin
    }
}
```

A policy method without a model, such as `bulk`, is asked with `()`: `request.authorize(PostPolicy::bulk, ())`.

`request.authorize` answers `403` when the policy says no, and for a guest. The framework's `authorization.md` guide covers policy responses, guests and administrators.

### A policy that reads the database

A rule often needs another model, such as PHP's `$task->project->owner_id === $user->id`. Loading that model is a query, so the method is `async` and returns `laravel::Result<bool>`. Call it from `authorize` the same way: `request.authorize` waits for it. The example app's `TaskPolicy` reads the task's milestone:

```rust
pub struct TaskPolicy;

#[policy]
impl TaskPolicy {
    /// Anyone may change a task until its milestone is past due. After that, only an admin may.
    /// It reads the milestone from the database, so it is `async`. The admin check comes first:
    /// an admin's request never loads the milestone.
    pub async fn update(user: &User, task: &Task) -> laravel::Result<bool> {
        if user.is_admin {
            return Ok(true);
        }
        let milestone = Milestone::find_or_fail(task.milestone_id).await?;

        Ok(milestone.due_on.is_none_or(|day| day >= laravel::time::today()))
    }
}
```

When you translate a PHP policy, keep the order of its checks. PHP's `||` stops at the first `true`, so `$user->isAdmin() || $task->project->owner_id === $user->id` never loads the project for an admin. Return early the same way, before the query. Otherwise each row of a list runs a query that PHP never ran, because a list asks `Action::Show` about every row.

An error from the method, such as a failed query, answers `500`, not `403`. See "Asynchronous checks" in the framework's `authorization.md`.

## What a refusal looks like

A refusal is an error with the status `403`. Restify answers it with the message Restify for PHP gives for the question it asked, whatever message the repository's error had, because PHP's policies only say yes or no:

| Question | Message |
| --- | --- |
| `Action::AllowRestify` | `Unauthorized to view repository posts. Check "allowRestify" policy.` |
| `Action::Store` | `Unauthorized to store.` |
| `Action::StoreBulk` | `Unauthorized to store bulk.` |
| `Action::Attach` | `You cannot attach model:User, to the model:Team, check your permissions.`, with the related model's name and the repository's model's name |
| `Action::Sync` | `You cannot sync key to the model:Team, check your permissions.` |
| Any other | `This action is unauthorized.` |

Where PHP's attach and sync messages name the model classes, such as `App\Models\Team`, Restify names the model, such as `Team`.

An endpoint answers with the status and the message:

```json
{ "message": "This action is unauthorized." }
```

An MCP tool answers with a result the agent can read, not a protocol error. Its text is the message:

```json
{ "isError": true, "content": [{ "type": "text", "text": "This action is unauthorized." }] }
```

An error with another status, such as `laravel::abort(404)` to hide a record, keeps its own status and message.

## Rows a list leaves out

A list asks `Action::Show` about each row of the page and leaves out the rows it refuses, as Restify for PHP does. It does this after the page is counted, so `meta.total` and `meta.to` still count those rows and a page may hold fewer rows than `per_page`. To keep rows out of the count as well, leave them out in `Repository::query`. See [Repositories](repositories.md).

## What the user may do with a record

A shown record has a `meta` object that says what the request's user may do with it. Each flag is the answer of `authorize`: `true` when it allows the action, `false` when it refuses with `403`.

```json
"meta": {
    "authorizedToShow": true,
    "authorizedToStore": true,
    "authorizedToUpdate": false,
    "authorizedToDelete": false
}
```

A listed record has it only with `?withMeta=true`. Both defaults are settings: `RESTIFY_SERIALIZE_SHOW_META` (on) and `RESTIFY_SERIALIZE_INDEX_META` (off). The answer to a create or an update follows the list's setting, as in Restify for PHP.
