2020-01-26 20:36:50 +00:00
|
|
|
defmodule Mobilizon.Web.GraphQLSocket do
|
2019-12-03 10:29:51 +00:00
|
|
|
use Phoenix.Socket
|
|
|
|
|
|
|
|
use Absinthe.Phoenix.Socket,
|
2019-12-20 12:04:34 +00:00
|
|
|
schema: Mobilizon.GraphQL.Schema
|
2019-12-03 10:29:51 +00:00
|
|
|
|
2023-02-15 18:31:23 +00:00
|
|
|
alias Mobilizon.Applications.Application, as: AuthApplication
|
|
|
|
alias Mobilizon.Applications.ApplicationToken
|
2019-12-03 10:29:51 +00:00
|
|
|
alias Mobilizon.Users.User
|
|
|
|
|
2021-09-10 09:27:59 +00:00
|
|
|
@spec connect(map, Phoenix.Socket.t()) :: {:ok, Phoenix.Socket.t()} | :error
|
2019-12-03 10:29:51 +00:00
|
|
|
def connect(%{"token" => token}, socket) do
|
|
|
|
with {:ok, authed_socket} <-
|
2020-01-26 20:36:50 +00:00
|
|
|
Guardian.Phoenix.Socket.authenticate(socket, Mobilizon.Web.Auth.Guardian, token),
|
2023-02-15 18:31:23 +00:00
|
|
|
resource <- Guardian.Phoenix.Socket.current_resource(authed_socket) do
|
|
|
|
set_context(authed_socket, resource)
|
2019-12-03 10:29:51 +00:00
|
|
|
|
|
|
|
{:ok, authed_socket}
|
|
|
|
else
|
|
|
|
{:error, _} ->
|
|
|
|
:error
|
|
|
|
end
|
|
|
|
end
|
|
|
|
|
2021-05-31 10:08:48 +00:00
|
|
|
def connect(_args, _socket), do: :error
|
|
|
|
|
2021-09-10 09:27:59 +00:00
|
|
|
@spec id(any) :: nil
|
2019-12-03 10:29:51 +00:00
|
|
|
def id(_socket), do: nil
|
2023-02-15 18:31:23 +00:00
|
|
|
|
|
|
|
@spec set_context(Phoenix.Socket.t(), User.t() | ApplicationToken.t()) :: Phoenix.Socket.t()
|
|
|
|
defp set_context(socket, %User{} = user) do
|
|
|
|
Absinthe.Phoenix.Socket.put_options(socket,
|
|
|
|
context: %{
|
|
|
|
current_user: user
|
|
|
|
}
|
|
|
|
)
|
|
|
|
end
|
|
|
|
|
|
|
|
defp set_context(
|
|
|
|
socket,
|
|
|
|
%ApplicationToken{user: %User{} = user, application: %AuthApplication{} = app} =
|
|
|
|
app_token
|
|
|
|
) do
|
|
|
|
Absinthe.Phoenix.Socket.put_options(socket,
|
|
|
|
context: %{
|
|
|
|
current_auth_app_token: app_token,
|
|
|
|
current_auth_app: app,
|
|
|
|
current_user: user
|
|
|
|
}
|
|
|
|
)
|
|
|
|
end
|
2019-12-03 10:29:51 +00:00
|
|
|
end
|