如何删除 Phoenix Session?
How to delete a Phoenix Session?
我正在检查 Phoenix Guide on Sessions。它很好地解释了我如何使用 put_session
将数据绑定到会话并稍后使用 get_session
获取值,但它没有告诉我如何删除用户的会话。
来自指南:
defmodule HelloPhoenix.PageController do
use Phoenix.Controller
def index(conn, _params) do
conn = put_session(conn, :message, "new stuff we just set in the session")
message = get_session(conn, :message)
text conn, message
end
end
我想你要找的是 configure_session:
Plug.Conn.configure_session(conn, drop: true)
在 Plug Docs 中找到它:
Clears the entire session.
This function removes every key from the session, clearing the
session.
Note that, even if clear_session/1 is used, the session is still sent
to the client. If the session should be effectively dropped,
configure_session/2 should be used with the :drop option set to true.
您可以在 SessionsController
:
中添加类似的内容
def delete(conn, _) do
conn
|> clear_session()
|> redirect(to: page_path(conn, :index))
end
并在您的 web/router.ex
中为此添加一条路线。
如果你想删除一个特定的会话,你应该使用:
conn |> fetch_session |> delete_session(:session_to_delete)
更多信息在这里:
https://github.com/elixir-lang/plug/blob/master/lib/plug/session.ex#L114:L115
只使用delete_session/2删除之前创建的session,然后重定向到登录什么的!
示例:
# In this example I use a log_out link to delete session when user click in it.
def log_out(conn, _params) do
conn
|> delete_session(:session_name)
|> redirect(to: Routes.auth_path(conn, :login))
end
重要的是 return 修改了 conn
,删除了您放入其中的密钥。
我正在检查 Phoenix Guide on Sessions。它很好地解释了我如何使用 put_session
将数据绑定到会话并稍后使用 get_session
获取值,但它没有告诉我如何删除用户的会话。
来自指南:
defmodule HelloPhoenix.PageController do
use Phoenix.Controller
def index(conn, _params) do
conn = put_session(conn, :message, "new stuff we just set in the session")
message = get_session(conn, :message)
text conn, message
end
end
我想你要找的是 configure_session:
Plug.Conn.configure_session(conn, drop: true)
在 Plug Docs 中找到它:
Clears the entire session.
This function removes every key from the session, clearing the session.
Note that, even if clear_session/1 is used, the session is still sent to the client. If the session should be effectively dropped, configure_session/2 should be used with the :drop option set to true.
您可以在 SessionsController
:
def delete(conn, _) do
conn
|> clear_session()
|> redirect(to: page_path(conn, :index))
end
并在您的 web/router.ex
中为此添加一条路线。
如果你想删除一个特定的会话,你应该使用:
conn |> fetch_session |> delete_session(:session_to_delete)
更多信息在这里:
https://github.com/elixir-lang/plug/blob/master/lib/plug/session.ex#L114:L115
只使用delete_session/2删除之前创建的session,然后重定向到登录什么的!
示例:
# In this example I use a log_out link to delete session when user click in it.
def log_out(conn, _params) do
conn
|> delete_session(:session_name)
|> redirect(to: Routes.auth_path(conn, :login))
end
重要的是 return 修改了 conn
,删除了您放入其中的密钥。