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:
parent
841ccac462
commit
d288db3370
@ -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:
|
||||
|
||||
@ -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
|
||||
|
||||
@ -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>
|
||||
|
||||
Loading…
Reference in New Issue
Block a user