PageRenderTime 55ms CodeModel.GetById 31ms RepoModel.GetById 1ms app.codeStats 0ms

/web/static/js/socket.js

https://gitlab.com/greeterspl/engine
JavaScript | 62 lines | 8 code | 6 blank | 48 comment | 0 complexity | d3c275812e31dc9e4ca1b44c4e9fca7c MD5 | raw file
  1. // NOTE: The contents of this file will only be executed if
  2. // you uncomment its entry in "web/static/js/app.js".
  3. // To use Phoenix channels, the first step is to import Socket
  4. // and connect at the socket path in "web/endpoint.ex":
  5. import {Socket} from "deps/phoenix/web/static/js/phoenix"
  6. let socket = new Socket("/socket")
  7. // When you connect, you'll often need to authenticate the client.
  8. // For example, imagine you have an authentication plug, `MyAuth`,
  9. // which authenticates the session and assigns a `:current_user`.
  10. // If the current user exists you can assign the user's token in
  11. // the connection for use in the layout.
  12. //
  13. // In your "web/router.ex":
  14. //
  15. // pipeline :browser do
  16. // ...
  17. // plug MyAuth
  18. // plug :put_user_token
  19. // end
  20. //
  21. // defp put_user_token(conn, _) do
  22. // if current_user = conn.assigns[:current_user] do
  23. // token = Phoenix.Token.sign(conn, "user socket", current_user.id)
  24. // assign(conn, :user_token, token)
  25. // else
  26. // conn
  27. // end
  28. // end
  29. //
  30. // Now you need to pass this token to JavaScript. You can do so
  31. // inside a script tag in "web/templates/layout/app.html.eex":
  32. //
  33. // <script>window.userToken = "<%= assigns[:user_token] %>";</script>
  34. //
  35. // You will need to verify the user token in the "connect/2" function
  36. // in "web/channels/user_socket.ex":
  37. //
  38. // def connect(%{"token" => token}, socket) do
  39. // # max_age: 1209600 is equivalent to two weeks in seconds
  40. // case Phoenix.Token.verify(socket, "user socket", token, max_age: 1209600) do
  41. // {:ok, user_id} ->
  42. // {:ok, assign(socket, :user, user_id)}
  43. // {:error, reason} ->
  44. // :error
  45. // end
  46. // end
  47. //
  48. // Finally, pass the token on connect as below. Or remove it
  49. // from connect if you don't care about authentication.
  50. socket.connect({token: window.userToken})
  51. // Now that you are connected, you can join channels with a topic:
  52. let channel = socket.channel("topic:subtopic", {})
  53. channel.join()
  54. .receive("ok", resp => { console.log("Joined succesffuly", resp) })
  55. .receive("error", resp => { console.log("Unabled to join", resp) })
  56. export default socket