043206835221d71ab63509fa530ba8679a56db64
[akkoma] / lib / pleroma / web / channels / user_socket.ex
1 # Pleroma: A lightweight social networking server
2 # Copyright © 2017-2021 Pleroma Authors <https://pleroma.social/>
3 # SPDX-License-Identifier: AGPL-3.0-only
4
5 defmodule Pleroma.Web.UserSocket do
6 use Phoenix.Socket
7 alias Pleroma.User
8
9 ## Channels
10 # channel "room:*", Pleroma.Web.RoomChannel
11 channel("chat:*", Pleroma.Web.ShoutChannel)
12
13 # Socket params are passed from the client and can
14 # be used to verify and authenticate a user. After
15 # verification, you can put default assigns into
16 # the socket that will be set for all channels, ie
17 #
18 # {:ok, assign(socket, :user_id, verified_user_id)}
19 #
20 # To deny connection, return `:error`.
21 #
22 # See `Phoenix.Token` documentation for examples in
23 # performing token verification on connect.
24 def connect(%{"token" => token}, socket) do
25 with true <- Pleroma.Config.get([:shout, :enabled]),
26 {:ok, user_id} <- Phoenix.Token.verify(socket, "user socket", token, max_age: 84_600),
27 %User{} = user <- Pleroma.User.get_cached_by_id(user_id) do
28 {:ok, assign(socket, :user_name, user.nickname)}
29 else
30 _e -> :error
31 end
32 end
33
34 # Socket id's are topics that allow you to identify all sockets for a given user:
35 #
36 # def id(socket), do: "user_socket:#{socket.assigns.user_id}"
37 #
38 # Would allow you to broadcast a "disconnect" event and terminate
39 # all active sockets and channels for a given user:
40 #
41 # Pleroma.Web.Endpoint.broadcast("user_socket:#{user.id}", "disconnect", %{})
42 #
43 # Returning `nil` makes this socket anonymous.
44 def id(_socket), do: nil
45 end