Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
437 views
in Technique[技术] by (71.8m points)

token - Making conn.assigns available in multiple Phoenix views/templates

I need a user authentication token defined in the SessionControllerto be available in layout/app.html.eex.

My SessionController defines a token and assigns it to a conn.

token = Phoenix.Token.sign(conn, "user socket", user)

assign(conn, :user_token, token)

Then when I try to use the token in app.html.eex like the following,

 <script>window.userToken = "<%= assigns[:user_token] %>"</script>

or

 <script>window.userToken = "<%= @user_token %>"</script>

I get this error: (ArgumentError) assign @user_token not available in eex template.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

conn.assigns are reset on every request. If you want to store something in SessionController and have it available in future requests, you can use put_session;

In your SessionController:

token = Phoenix.Token.sign(conn, "user socket", user)
conn
|> put_session(:user_token, token)
|> render(...)

Then, to access it in other controllers, you can use:

token = get_session(conn, :user_token)

To access it in multiple templates, you can then add a plug to the appropriate pipeline(s) in your Router:

pipeline :browser do
  ...
  plug :fetch_user_token
end

...

def fetch_user_token(conn, _) do
  conn
  |> assign(:user_token, get_session(conn, :user_token))
end

Now you can access the token in any template with @user_token (or assigns[:user_token] or assigns.user_token or @conn.assigns[:user_token] or @conn.assigns.user_token; all will give the same result here).


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...