1
0
mirror of https://github.com/danbee/chess synced 2025-03-04 08:39:06 +00:00

Add auth token for websocket

This commit is contained in:
Daniel Barber 2018-03-09 14:38:59 -05:00
parent 841ccac462
commit d288db3370
Signed by: danbarber
GPG Key ID: 931D8112E0103DD8
3 changed files with 22 additions and 2 deletions

View File

@ -1,6 +1,8 @@
defmodule ChessWeb.UserSocket do
use Phoenix.Socket
alias Phoenix.Token
## Channels
channel "game:*", ChessWeb.GameChannel
@ -19,8 +21,13 @@ defmodule ChessWeb.UserSocket do
#
# See `Phoenix.Token` documentation for examples in
# performing token verification on connect.
def connect(_params, socket) do
{:ok, socket}
def connect(%{"token" => token}, socket) do
case Token.verify(socket, "game socket", token, max_age: 1209600) do
{:ok, user_id} ->
{:ok, assign(socket, :current_user, user_id)}
{:error, _reason} ->
:error
end
end
# Socket id's are topics that allow you to identify all sockets for a given user:

View File

@ -1,6 +1,8 @@
defmodule ChessWeb.Router do
use ChessWeb, :router
alias Phoenix.Token
pipeline :browser do
plug :accepts, ["html"]
plug :fetch_session
@ -15,6 +17,7 @@ defmodule ChessWeb.Router do
pipeline :ensure_auth do
plug Guardian.Plug.EnsureAuthenticated
plug :put_user_token
end
pipeline :api do
@ -45,4 +48,13 @@ defmodule ChessWeb.Router do
resources "/games", ChessWeb.Api.GameController, only: [:show, :update]
end
defp put_user_token(conn, _) do
if current_user = Guardian.Plug.current_resource(conn) do
token = Token.sign(conn, "game socket", current_user.id)
assign(conn, :user_token, token)
else
conn
end
end
end

View File

@ -41,6 +41,7 @@
</div>
</main>
<script>window.userToken = "<%= assigns[:user_token] %>";</script>
<script src="<%= static_path(@conn, "/js/vendor.js") %>"></script>
<script src="<%= static_path(@conn, "/js/app.js") %>"></script>
</body>