Skip to content

Authorization

David Ciulla edited this page Nov 7, 2026 · 2 revisions

Authorization

Laravex provides two complementary approaches to authorization: Gates for simple closure-based checks, and Policies for grouping authorization logic around a model. Both are implemented in Laravex.Auth.Gate and Laravex.Auth.Policy.

Introduction

Authorization in Laravex answers the question: can this user perform this action on this resource? Gates and policies do not handle authentication (see Authentication); they assume a user is already resolved.

Gates

Defining Gates

Gates are closures registered against a named ability. Register them in a service provider's boot/0, or anywhere before the first request is handled:

alias Laravex.Auth.Gate

# Arity-1 gate (resource-free)
Gate.define(:view_admin, fn user ->
  user.is_admin
end)

# Arity-2 gate (user + resource)
Gate.define(:update_post, fn user, post ->
  user.id == post.user_id
end)

Gates are stored in an ETS table (:laravex_gates) and persist for the life of the process.

Checking Gates

user = Laravex.Auth.Guard.user(request)

if Laravex.Auth.Gate.allows?(user, :update_post, post) do
  # authorised
end

if Laravex.Auth.Gate.denies?(user, :update_post, post) do
  # forbidden
end

# Raises Laravex.Http.HttpException (403) on failure
Laravex.Auth.Gate.authorize(user, :update_post, post)

# Check any/none of several abilities
Laravex.Auth.Gate.any?(user, [:update_post, :delete_post], post)
Laravex.Auth.Gate.none?(user, [:ban_user, :impersonate], nil)

# Inspect an authorization decision (returns a map with allowed?, message, code, ability)
result = Laravex.Auth.Gate.inspect(user, :update_post, post)
# => %{allowed?: true, message: nil, code: 200, ability: "update_post"}

Via the Guard

Laravex.Auth.Guard proxies directly to the Gate:

user = Laravex.Auth.Guard.user(request)

Laravex.Auth.Guard.allows?(user, :update_post, post)
Laravex.Auth.Guard.denies?(user, :view_admin)
Laravex.Auth.Guard.authorize(user, :update_post, post)  # raises on failure

User-scoped Gate

Obtain a Gate instance bound to a specific user (Laravel Gate::forUser):

gate = Laravex.Auth.Gate.for_user(user)
gate |> Laravex.Auth.Gate.UserGate.allows?(:update_post, post)
gate |> Laravex.Auth.Gate.UserGate.any?([:update_post, :delete_post], post)
gate |> Laravex.Auth.Gate.UserGate.inspect(:update_post, post)

Before and After Hooks

Intercept every Gate check with a global callback:

# `before` — return true/false to short-circuit; return nil to continue
Laravex.Auth.Gate.before(fn user, ability ->
  if user.is_super_admin, do: true, else: nil
end)

# `after_check` — receives the final result and can modify it
Laravex.Auth.Gate.after_check(fn user, ability, result, resource ->
  result  # or override with true/false
end)

Removing Gate Definitions

# Remove an ability (Laravel `Gate::forget`)
Laravex.Auth.Gate.forget(:update_post)

# Alias
Laravex.Auth.Gate.undefine(:update_post)

Policies

Policies let you group all authorization logic for a given model into a dedicated module under app/Policies/.

Creating a Policy

Create a module that follows the naming convention App.Policies.<ModelName>Policy:

# app/Policies/post_policy.ex
defmodule App.Policies.PostPolicy do

  # update?(user, post) — called for the :update or "update" ability
  def update?(user, post) do
    user.id == post.user_id
  end

  # delete?(user, post)
  def delete?(user, post) do
    user.id == post.user_id or user.is_admin
  end

  # create?(user) — resource-free arity-1 variant
  def create?(user) do
    not is_nil(user.email_verified_at)
  end
end

Laravex.Auth.Policy resolves the policy module from the resource struct:

  • %App.Models.Post{} → App.Policies.PostPolicy
  • Checks for ability?/2 → ability/2 → ability/1 (resource-free) in that order

Authorizing with Policies

Policies are consulted automatically when no matching Gate exists:

# No explicit Gate for :update — falls through to PostPolicy.update?/2
Laravex.Auth.Gate.allows?(user, :update, post)
Laravex.Auth.Gate.authorize(user, :delete, post)

can Middleware

The can middleware alias checks a Gate or Policy ability before allowing the request through:

# Single ability (no resource)
Router.group([middleware: ["can:view-admin"]], fn ->
  Router.get("/admin", &App.Http.Controllers.Admin.DashboardController.index/1)
end)

# Ability + route-bound resource key
Router.put("/posts/{post}", &App.Http.Controllers.PostController.update/1,
  middleware: ["can:update,post"]
)

The can:update,post form resolves the resource by looking up request.route_params["post"] (populated by SubstituteBindings middleware, see Middleware).

If the user is unauthenticated, a 401 is returned (JSON) or a redirect to /login is issued. If the user is authenticated but unauthorized, a 403 is returned.

Middleware Reference

Alias Behaviour
can:<ability> Checks gate/policy; 401 if unauthenticated, 403 if denied
can:<ability>,<param> Resolves route_params[param] as the resource
verified Requires email_verified_at to be set; redirects to /email/verify otherwise
password.confirm Requires recent password confirmation; session-stamped for ~3 hours

verified

Ensures the authenticated user has a verified email (email_verified_at is not nil):

Router.get("/dashboard", {DashboardController, :index},
  middleware: ["auth", "verified"])

password.confirm

Requires the user to re-enter their password before accessing sensitive sections. After confirmation, the timestamp is stored in the session and the user is not prompted again for a configurable window (default 3 hours):

Router.get("/user/delete", {SettingsController, :destroy},
  middleware: ["auth", "password.confirm"])

See Also

Clone this wiki locally