Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Can I pattern match a session value in a Conn inside a function parameter?

I have a session key :identifiedas that may or may not exist for the user. I want it so that if you go to the login page while this key exists, the server redirects you to the homepage.

I could use an if to solve this, but it seems like a bad idea compared to having a pattern in another function clause, if it's possible.

def login(conn, %{"username" => username, "password" => password}) do
  if Plug.Conn.get_session(conn, :identifiedas) do
    conn
    |> Flash.put(:notice, "You are already logged in.")
    |> redirect(to: "/")
  else
    # Actually try to login. Elided from example.
  end
end

Preferrably I'd like it to be:

def login(%Conn{:something -> %{:identifiedas => _}, _fields) do
  conn
  |> Flash.put(:notice, "You are already logged in.")
  |> redirect(to: "/")
end

def login(conn, %{"username" => username, "password" => password}) do
  # Elided
end
like image 372
Havvy Avatar asked Dec 06 '14 05:12

Havvy


1 Answers

Yes. You can use this pattern:

def index(conn = %Plug.Conn{private: %{plug_session: %{identifiedas: _}}}, _params) do
  # ...
end
like image 180
Patrick Oscity Avatar answered Oct 12 '22 21:10

Patrick Oscity