johnnyicon
LiveView using basic `Map` as session and not `Plug.Conn`
Hi all, working with LiveView and the code generated by phx.gen.live. I’m also working with code generated by phx_gen_auth for my authentication.
I’m trying to use the functions defined in UserAuth from phx_gen_auth to manage authentication on a LiveView. I looked through the code of UserAuth and saw that it expects sesions to be of type Plug.Conn.
However, it seems that LiveView is using a basic Map. In particular, I looked at the parameters of the function
def mount(_params, session, socket) of a LiveView and inspected the session parameter.
Should it be using Plug.Conn?
If not, how would I convert a Map to Plug.Conn so I can use the functions defined in UserAuth?
Cheers!
Marked As Solved
voughtdq
Got it. So this code here:
def mount(_params, %{"user_token" => user_token}, socket) do
user = user_token && Accounts.get_user_by_session_token(user_token)
...
end
Is actually a direct copy from UserAuth repurposed for the live view mount. If you want to create something that is more general purpose you might do this:
def get_current_user(%{"user_token" => user_token} = _session) do
user_token && Accounts.get_user_by_session_token(user_token)
end
Then you can do this in any of your mounts:
def mount(_params, session, socket) do
user = get_current_user(session)
end
Last Post!
johnnyicon
Popular in Questions
Other popular topics
Categories:
Sub Categories:
Forums
Popular Tags
- #ecto
- #liveview
- #troubleshooting
- #learning-elixir
- #deployment
- #library
- #erlang
- #testing
- #genserver
- #mix
- #absinthe
- #remote-other
- #otp
- #plug
- #how-to-question
- #macros
- #postgres
- #channels
- #elixirconf
- #exunit
- #discussion
- #code-sync
- #javascript
- #podcasts
- #onsite
- #dialyzer
- #docker
- #authentication
- #umbrella
- #full-time-contract
- #podcasts-by-brainlid
- #ecto-query
- #elixir-ls
- #phoenix_html
- #iex
- #blog-post
- #graphql
- #genstage
- #ai
- #websockets
- #supervisor
- #elixirconf-us
- #advent-of-code
- #distillery
- #processes
- #api
- #forms
- #metaprogramming
- #security
- #hex










