# `PgRest.Authorization`
[🔗](https://github.com/agoodway/pgrest/blob/v0.2.0/lib/pg_rest/authorization.ex#L1)

Behavior for pluggable authorization in PgRest.

Implement this behavior to add runtime permission checks to your PgRest resources.

## Usage

    defmodule MyApp.PgRestAuth do
      @behaviour PgRest.Authorization

      @impl true
      def authorize(_conn, _resource_module, :read, _context), do: :ok
      def authorize(_conn, _resource_module, _op, %{role: :admin}), do: :ok
      def authorize(_conn, _resource_module, _op, _context), do: {:error, "Forbidden"}
    end

Then configure in your router:

    forward "/api", PgRest.Plug,
      repo: MyApp.Repo,
      authorization: MyApp.PgRestAuth

`authorize_query/5` receives the base scope after `authorize/4` permits the operation.
It returns `{:ok, query}` or `{:ok, query, opts}`. PgRest intersects the query with the
base scope. `columns:` names physical columns; `limit:` caps rows per parent.
`aggregates:` and `count:` default to false; columns default to `:all`, limit to `nil`.
A query-only module can grant table operations; functions still require `authorize/4`.
Function targets are `%PgRest.Function{}`: match `schema`/`name` (and `params` for
overloads), not `module`, which is nil for introspected functions.
`context.graph` and `context.plan_enabled` are unstable planner data; callbacks
should use their own application keys and the documented identity/path fields.
Both callbacks receive `context.path` (embed output names) and `context.root?`;
a junction appends its table name to the embed path.

## Differences from PostgREST

Query policies extend database privileges/RLS: stars expose permitted columns only,
and writes use distinct read and payload policies. Filters, counts, representations
and named conflict targets or Location require a read grant as well as the write grant.
`GET /projects?select=*` under `columns: ["id"]` returns `[{"id":1}]`;
PostgREST returns every granted column.

RPC `result_scope: :none` trusts the function for rows only: query-hook denials,
column grants, count/aggregate grants and permission limits still apply without
keyed row matching. PostgREST relies on function/database privileges and RLS.

A hook's bare `{:ok, query}` denies EXPLAIN; an explicit three-tuple grants it.
EXPLAIN is an admission check on the actual authorized statement, not a second
narrowing pass. PostgREST uses privileges and db-plan-enabled instead.

# `operation`

```elixir
@type operation() :: :read | :create | :update | :delete | :execute | :explain
```

`:execute` is asked for a `PgRest.Function` before an RPC call is planned; `:explain` for a
query plan response. The others are asked for resources.

# `query_operation`

```elixir
@type query_operation() :: :read | :create | :update | :delete | :explain
```

# `query_options`

```elixir
@type query_options() :: [
  columns: :all | [String.t()],
  limit: pos_integer() | nil,
  aggregates: boolean(),
  count: boolean()
]
```

# `authorize`
*optional* 

```elixir
@callback authorize(
  conn :: Plug.Conn.t(),
  resource_module :: module() | PgRest.Function.t(),
  operation :: operation(),
  context :: map()
) :: :ok | {:error, String.t() | map()}
```

# `authorize_query`
*optional* 

```elixir
@callback authorize_query(
  Plug.Conn.t(),
  module(),
  query_operation(),
  Ecto.Query.t(),
  map()
) ::
  {:ok, Ecto.Query.t()}
  | {:ok, Ecto.Query.t(), query_options()}
  | {:error, term()}
```

# `allowed?`

```elixir
@spec allowed?(map(), operation()) :: boolean()
```

Whether the resource's `allow:` list (from its `__pgrest_config__/0`) admits `operation`.
`:explain` is always admitted: it is decided by the hook alone.

# `check`

```elixir
@spec check(
  module() | nil,
  Plug.Conn.t(),
  module() | PgRest.Function.t(),
  operation(),
  map(),
  PgRest.Authorization.State.t()
) :: :ok | {:error, PgRest.Error.t()}
```

The single authorization gate: `:ok`, or the `42501` PgRest answers with when the
resource's `allow:` list excludes `operation` (a missing grant) or `auth` (when not nil)
denies. `allow:` is checked first, so the hook never sees an operation the resource does not
expose. A `%PgRest.Function{}` has no `allow:` list; only the hook decides, and a denial names
the function.

It runs for every resource a request touches: the root and each embed, spread and
many-to-many junction (`:read`), the write's own operations, `:read` on a write's target
when its filters, count, representation or `Location` read rows, `:execute` on an RPC's
function and `:read` on the resources its result and embeds read.

Missing callbacks deny. A query-only policy delegates table operations to
`PgRest.Authorization.Apply`; functions require `authorize/4`. A query hook's
`:explain` grant must be a three-tuple and receives the effective source query.
Write row checks use the write-operation query; read policies protect targeting and output.

# `explain?`

```elixir
@spec explain?(
  module() | nil,
  Plug.Conn.t(),
  [module() | PgRest.Function.t()],
  map(),
  PgRest.Authorization.State.t()
) :: boolean()
```

Whether `:explain` is allowed (`check/5`) on every one of `targets`, resource modules and the
`PgRest.Function` of a call: the gate of the `application/vnd.pgrst.plan` media type.

# `query_hook?`

```elixir
@spec query_hook?(module() | nil) :: boolean()
```

Whether a configured policy exports the query-narrowing callback.

---

*Consult [api-reference.md](api-reference.md) for complete listing*
