Strange behavior in a session - can not store a flag in a session

Hello developer,

I have a strange phenomen and do not know how to solve it. I will a little bit protect a site ala .htaccess in elixir, and realized this in a following way:

router.ex - file:

scope "/", GeosWeb do
    pipe_through [:browser, :redirect_if_user_is_allowed_to_view]

    get "/", PageController, :get_pass
    post "/test_login", PageController, :test_login
  end

  scope "/", GeosWeb do
    pipe_through [:testing, :has_right_to_see_testing]

    get "/ru", PageController, :index
    get "/:lang/pages/:category/:pagealias", PageController, :article
  end

The idea is, that a user called this site has to write a password. It is a very trivial method analogue to .htaccess in/with apache.

The post goes to function test_login in PageController.

Here I wrote:

def test_login(conn, %{"password" => password}) do
    if password == "1x2x3x1x!" do
      conn
      |> put_session(:person_prinjat, password)
      |> redirect(to: "/ru")
      |> halt()

    else
      # Password is incorrect, show an error message
      csrf_token = Plug.CSRFProtection.get_csrf_token()
      render(conn, "GetPassword.html", csrf_token: csrf_token)
    end
  end

has_the_right_to_see_testing is a function, which compare session value with the hard coded password and look if everything is fine.

def has_right_to_see_testing(conn, _opts) do
    if get_session(conn, :person_prinjat) == "1x2x3x1x!" do
      conn
    else
      conn
      |> put_flash(:error, "You have no right to see this page")
      |> redirect(to: "/")
      |> halt()
    end
  end

As you can see, has_right_to_see_testing is the function, comparing the password with the value stored in the session. But the value in session vanishing every time and I do not know why. The consequence is, that the site is always blocked. It seems that I have anywhere a mistake, but I do not find him. Please help.

Thank you very much,
Sven

Not necessarily an answer to why your code doesn’t work, but I’d suggest just using Plug.BasicAuth — Plug v1.15.3 and not try to roll your own authentication handling.

3 Likes

Wau! Thank you, for this hint! I did not know this Plug. I will try it. Thank you very much!

regards,
Sven

@LostKobrakai

It does exactly what I want. Thank you!

Have a nice day!!!
Sven