Hris

Hris

(Plug.Conn.AlreadySentError) the response was already sent

Using Guardian for register/login.
I am getting this error when I try to log in:

[info] Sent 401 in 819ms
[error] #PID<0.440.0> running WebPageWeb.Endpoint (cowboy_protocol) terminated
Server: localhost:4000 (http)
Request: POST /users/login_auth
** (exit) an exception was raised:
    ** (Plug.Conn.AlreadySentError) the response was already sent
        (plug) lib/plug/conn.ex:668: Plug.Conn.put_resp_header/3
        (phoenix) lib/phoenix/controller.ex:402: Phoenix.Controller.redirect/2
        (web_page) lib/web_page_web/controllers/user_controller.ex:1: WebPageWeb.UserController.action/2
        (web_page) lib/web_page_web/controllers/user_controller.ex:1: WebPageWeb.UserController.phoenix_controller_pipeline/2
        (web_page) lib/web_page_web/endpoint.ex:1: WebPageWeb.Endpoint.instrument/4
        (phoenix) lib/phoenix/router.ex:278: Phoenix.Router.__call__/1
        (web_page) lib/web_page_web/endpoint.ex:1: WebPageWeb.Endpoint.plug_builder_call/2
        (web_page) lib/plug/debugger.ex:122: WebPageWeb.Endpoint."call (overridable 3)"/2
        (web_page) lib/web_page_web/endpoint.ex:1: WebPageWeb.Endpoint.call/2
        (plug) lib/plug/adapters/cowboy/handler.ex:16: Plug.Adapters.Cowboy.Handler.upgrade/4
        (cowboy) src/cowboy_protocol.erl:442: :cowboy_protocol.execute/4

Controller:

def login(conn, _params) do
    changeset = Users.change_user(%User{})
    render(conn, "login.html", changeset: changeset)
  end

  def login_auth(conn, %{"user" => %{"email" => email, "password" => password}}) do
    Auth.authenticate_user(email, password)
    |> login_reply(conn)
  end

  defp login_reply({:error, error}, conn) do
    conn
    |> put_flash(:error, error)
    |> redirect(to: "/")
  end

  defp login_reply({:ok, user}, conn) do
    conn
    |> put_flash(:success, "Welcome back!")
    |> Guardian.Plug.sign_in(user)
    |> redirect(to: "/")
  end

Auth.ex

def authenticate_user(email, plain_text_password) do
    query = from u in User, where: u.email == ^email
    Repo.one(query)
    |> check_password(plain_text_password)
  end
 
  defp check_password(nil, _), do: {:error, "Incorrect email or password"}
 
  defp check_password(user, plain_text_password) do
    case Bcrypt.checkpw(plain_text_password, user.password_hash) do
      true -> {:ok, user}
      false -> {:error, "Incorrect email or password"}
    end
  end

Router:

defmodule WebPageWeb.Router do
  use WebPageWeb, :router

  pipeline :browser do
    plug :accepts, ["html"]
    plug :fetch_session
    plug :fetch_flash
    plug :protect_from_forgery
    plug :put_secure_browser_headers
  end

  pipeline :api do
    plug :accepts, ["json"]
  end

  pipeline :auth do
    plug WebPage.Pipeline
  end

  pipeline :ensure_auth do
    plug Guardian.Plug.EnsureAuthenticated
  end

  scope "/", WebPageWeb do
    pipe_through [:browser, :auth] # Use the default browser stack

    get "/", PageController, :index
    post("/login_auth", UserController, :login_auth)
    get("/login", UserController, :login)
    get("/logout", UserController, :logout)
    resources "/users", UserController

  end

  scope "/admin", WebPageWeb do
    pipe_through [:browser, :auth, :ensure_auth]
    post("/login_auth", UserController, :login_auth)
    get "/", PageController, :index
    get("/login", UserController, :login)
    get("/logout", UserController, :logout)
    resources "/users", UserController

  end

  # Other scopes may use custom stacks.
  # scope "/api", WebPageWeb do
  #   pipe_through :api
  # end
end

So I investigated the problem and it comes out the verifications are allright.
Parameters which I give are correct but I couldn’t figure out where the the problem comes from.

After the login it saves the user into the connection regardless the given error.

Marked As Solved

Hris

Hris

Thanks for your response, but I actually managed to resolve the problem. It was actually a problem in the library. We had to wait for the latest updates.

Also Liked

bnymn

bnymn

I have just resolved my problem. In my case, my configuration in config.exs was wrong.

It was like this before:

config :guardian, Hello.Users.Guardian,
  issuer: "hello",
  secret_key: "4T5tuL+XbJ5yrmFKP/QfpE8gaqIRaTnmeXuIfuZGKkKKzc0dgGYhdVsWTrJWEVJ2"

I have changed it into:

config :hello, Hello.Users.Guardian,
  issuer: "hello",
  secret_key: "4T5tuL+XbJ5yrmFKP/QfpE8gaqIRaTnmeXuIfuZGKkKKzc0dgGYhdVsWTrJWEVJ2"
billtong

billtong

This saves my life!

ravi11o

ravi11o

You can check out this issue( Using halt on auth_error #401)

OR
you can provide more details like apps guardian module ie. WebpageWeb.Guardian and WebPage.Pipeline and Error handler for Guardian module.

Where Next?

Popular in Questions Top

sergio
In Ruby, I can go: User.find_by(email: "foobar@email.com").update(email: "hello@email.com") How can I do something similar in Elixir? ...
New
Harrisonl
We have an ECS cluster with 4 services, where each task joins a single cluster, via discovery ECS discovery service. Currently when I de...
New
beno
I will often find my self writing things similar to: case some_value do nil -&gt; something() "" -&gt; something() _ -&gt; somethi...
New
marius95
Hello everyone, I try to use an Javascript Event Handler in my root.html.leex file. Therefore I created a function in the app.js file: ...
New
Tee
can someone please explain to me how Enum.reduce works with maps
New
belgoros
I’m not a pro in using Regex and can’t figure out why the following behaviour happens, especially if we take into account the difference ...
New
itssasanka
Hi all, Trying to get some more clarity over utc_datetime and naive_datetime for Ecto: The documentation above suggests that while ...
New
Brian
What is the proper way to load a module from a file in to IEX? In the python world, doing something like this pretty standard: from ....
New
openscript
Hello! Sorry for this astonishing simple question, but I’m really stuck. I try to set up the intellij-elixir plugin, but I don’t know ho...
New
dokuzbir
I want to highlight html closing tags when i click a html tag. That works in .html files but doesnt work for html.eex templates. How can...
New

Other popular topics Top

sen
Hi All, I set a environment variables in dev.exs , like below code. when i start server, how can i set the ${enable} value? thanks. d...
New
danschultzer
None of the current solutions worked well for me, so I went ahead and built a user management system from scratch. This project took far...
548 29603 241
New
electic
Hi, I am new to Elixir. I am trying to use the DateTime component to insert a date into MySQL however the there seems to be no way to fo...
New
shahryarjb
Hello, I have map which I want to convert it to string like this: the map: %{last_name: "tavakkoli", name: "shahryar"} the string I ne...
New
ashish173
I am using Ecto timestamps with postgres, I can see the timestamps() use the :naive_dateime but for my use case I wanted to store the ti...
New
dblack
I’ve got an issue with an app and I’ve no idea of how to troubleshoot it. I’m hoping someone here might have seen something similar. I p...
New
KronicDeth
Elixir plugin for JetBrain’s IntelliJ Platform (including Rubymine) This is a plugin that adds support for Elixir to JetBrains IntelliJ...
289 36352 110
New
komlanvi
Hi everyone, I was playing with phoenix liveView but I run into an issue. I have a form and want to validate each input text when the te...
New
axelson
This post is a wiki (feel free to hit the edit button near the bottom right of this post to add your own changes!) This post collects co...
239 48342 226
New
AstonJ
Seen any cool LiveView demos, sample apps or examples? Please post them here! :003:
New

Latest on Elixir Forum

Elixir Forum

We're in Beta

About us Mission Statement