/
user_socket.ex
50 lines (44 loc) · 1.53 KB
/
user_socket.ex
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
defmodule ThexrWeb.UserSocket do
# use Phoenix.Socket
use Phoenix.LiveView.Socket
require Logger
# A Socket handler
#
# It's possible to control the websocket connection and
# assign values that can be accessed by your channel topics.
## Channels
channel "space:*", ThexrWeb.SpaceChannel
# Socket params are passed from the client and can
# be used to verify and authenticate a user. After
# verification, you can put default assigns into
# the socket that will be set for all channels, ie
#
# {:ok, assign(socket, :user_id, verified_user_id)}
#
# To deny connection, return `:error`.
#
# See `Phoenix.Token` documentation for examples in
# performing token verification on connect.
@impl true
def connect(%{"_member_token" => token}, socket, _connect_info) do
case Phoenix.Token.verify(socket, "salt", token, max_age: 1_209_600) do
{:ok, member_id} ->
{:ok, assign(socket, member_id: member_id)}
{:error, reason} ->
Logger.error("#{__MODULE__} connect error #{inspect(reason)}")
:error
end
end
# Socket id's are topics that allow you to identify all sockets for a given user:
#
# def id(socket), do: "user_socket:#{socket.assigns.user_id}"
#
# Would allow you to broadcast a "disconnect" event and terminate
# all active sockets and channels for a given user:
#
# Elixir.ThexrWeb.Endpoint.broadcast("user_socket:#{user.id}", "disconnect", %{})
#
# Returning `nil` makes this socket anonymous.
@impl true
def id(_socket), do: nil
end