Packages
guardian
0.12.0
2.4.0
2.3.2
2.3.1
2.3.0
2.2.4
2.2.3
2.2.2
2.2.1
2.2.0
2.1.2
2.1.1
2.0.0
1.2.1
1.2.0
retired
1.1.1
1.1.0
1.0.1
1.0.0
1.0.0-beta.1
1.0.0-beta.0
0.14.6
0.14.5
0.14.4
0.14.3
retired
0.14.2
0.14.1
0.14.0
0.13.0
0.12.0
0.11.1
0.10.1
0.10.0
0.9.1
0.9.0
0.8.1
0.8.0
0.7.4
0.7.2
0.7.1
0.7.0
0.6.3
0.6.2
0.6.1
0.6.0
0.5.2
0.5.0
0.4.1
0.4.0
0.3.1
0.3.0
0.2.0
0.1.1
0.1.0
Elixir Authentication framework
Current section
Files
Jump to
Current section
Files
lib/guardian/channel.ex
defmodule Guardian.Channel do
@moduledoc """
Provides integration for channels to use Guardian tokens.
## Example
defmodule MyApp.MyChannel do
use Phoenix.Channel
use Guardian.Channel
def join(_room, %{ claims: claims, resource: resource }, socket) do
{:ok, %{ message: "Joined" }, socket}
end
def join(room, _, socket) do
{:error, :authentication_required}
end
def handle_in("ping", _payload, socket) do
user = current_resource(socket)
broadcast(socket, "pong", %{message: "pong", from: user.email})
{:noreply, socket}
end
end
Tokens will be parsed and the claims and resource assigned to the socket.
## Example
let socket = new Socket("/ws")
socket.connect()
let guardianToken = jQuery('meta[name="guardian_token"]').attr('content')
let chan = socket.chan("pings", { guardian_token: guardianToken })
Consider using Guardian.Phoenix.Socket helpers
directly and authenticating the connection rather than the channel.
"""
defmacro __using__(opts) do
key = Keyword.get(opts, :key, :default)
quote do
import Guardian.Phoenix.Socket
def join(room, params = %{"guardian_token" => jwt}, socket) do
case sign_in(socket, jwt, params, key: unquote(key)) do
{:ok, authed_socket, guardian_params} ->
join_params = params
|> Map.drop(["guardian_token"])
|> Map.merge(guardian_params)
join(room, join_params, authed_socket)
{:error, reason} -> handle_guardian_auth_failure(reason)
end
end
def handle_guardian_auth_failure(reason), do: {:error, %{error: reason}}
defoverridable [handle_guardian_auth_failure: 1]
end
end
end