Current section

Files

Jump to
unleash_fresha lib unleash plug.ex
Raw

lib/unleash/plug.ex

if Code.ensure_loaded?(Plug) do
defmodule Unleash.Plug do
@moduledoc """
An extra fancy `Plug` and utility functions to help when developing `Plug`
or `Phoenix`-based applications. It automatically puts together a
`t:Unleash.context/0` and stores it in the `t:Plug.Conn.t()`'s `assigns`.
To use, call `plug Unleash.Plug` in your plug pipeline. It depends on the
session, and requires being after `:fetch_session` to work. It accepts the
following options:
* `:user_id`: The key under which the user's ID is found in the session.
* `:session_id`: The key under wwhich the session ID is found in the
session.
After which, `enabled?/3` is usable.
"""
@behaviour Plug
import Plug.Conn, only: [assign: 3, get_session: 2]
require Unleash.Macros
@default_opts [
user_id: :user_id,
session_id: :session_id
]
@doc false
def init(opts) when is_list(opts), do: Keyword.merge(@default_opts, opts)
def init(_), do: @default_opts
@doc false
def call(conn, opts) do
context = construct_context(conn, opts)
assign(conn, :unleash_context, context)
end
@doc """
Given a `t:Plug.Conn.t/0`, a feature, and (optionally) a boolean, return
whether or not a feature is enabled. This requires this plug to be a part
of the plug pipeline, as it will construct an `t:Unleash.context()/0` out
of the session.
## Examples
iex> Unleash.Plug.enabled?(conn, :test)
false
iex> Unleash.Plug.enabled?(conn, :test, true)
true
"""
@spec enabled?(Plug.Conn.t(), String.t() | atom(), boolean()) :: boolean()
def enabled?(%Plug.Conn{assigns: assigns}, feature, default \\ false) do
context = Map.get(assigns, :unleash_context, %{})
Unleash.Macros.enabled?(feature, context: context, fallback: default)
end
defp construct_context(conn, opts) do
opts
|> Enum.map(fn {k, v} ->
{k, get_session(conn, v)}
end)
|> Enum.concat(remote_address: to_string(:inet.ntoa(conn.remote_ip)))
|> Map.new()
end
end
end