View Source LiveGuard.Allowed protocol (Live Guard v0.1.1)

By this protocol you can implement allowed?/4 functions.

Summary

Types

t()

A user struct.

Functions

By this function you can protect the LiveView lifecycle stages.

Types

@type t() :: struct()

A user struct.

Functions

Link to this function

allowed?(user, live_view_module, stage, stage_inputs)

View Source
@spec allowed?(
  struct(),
  module(),
  :mount | :handle_params | :handle_event | :handle_info | :after_render,
  tuple()
) :: boolean()

By this function you can protect the LiveView lifecycle stages.

You can pattern match by the user, LiveView module, LiveView lifecycle stage and LiveView lifecycle stage inputs. You can put this file anywhere but /lib/my_app_web/live/abilities.ex is recommended. It must return boolean.

Example

# /lib/my_app_web/live/abilities.ex

defimpl LiveGuard.Allowed, for: User do
  @before_compile {LiveGuard, :before_compile_allowed}

  def allowed?(
        %User{role: role},
        MyModuleLive,
        :handle_event,
        {"delete_item", _params, _socket}
      )
      when role in [:viewer, :customer],
      do: false

  # other `allowed?/4` functions...
end

Note: As you can see, you don't have to define catch-all allowed?/4 function because we used @before_compile {LiveGuard, :before_compile_allowed} hook. It returns true.