Search code examples
elixirphoenix-frameworkguardian

Guardian let the user to get to the controller even when current_user is nil?


If user sends a token which is not expired however that specific user is no longer exist, Guardian still let user to get to the controller.

I have added {:ok, nil} in the current_user.ex and it simply kill the connection which I don't think is the correct approach as I need to give something back to the user like an error. I am not sure what should I use there?

Here is my router:

 pipeline :authed_api do
    plug :accepts, ["json"]
    plug Guardian.Plug.VerifyHeader, realm: "Bearer"
    plug Guardian.Plug.EnsureAuthenticated, handler: Web.GuardianErrorHandler 
    plug Guardian.Plug.LoadResource
    plug Web.CurrentUser, handler: Web.GuardianErrorHandler  
  end

 scope "/api/v1", Web do
    pipe_through :authed_api

    get "/logout", UserController, :logout
    resources "/users", UserController
    get "/*get", ErrorController, :handle_redirect
  end

Here is my current_user

defmodule Web.CurrentUser do
    import Plug.Conn
    import Guardian.Plug
    import Web.GuardianSerializer
    def init(opts), do: opts
    def call(conn, _opts) do
      current_token = Guardian.Plug.current_token(conn)
      case Guardian.decode_and_verify(current_token) do
        {:ok, claims} ->
          case Web.GuardianSerializer.from_token(claims["sub"]) do
            {:ok, nil} ->
              conn = Plug.Conn.halt(conn) # <-this line, I was referring to
            {:ok, user} ->
              Plug.Conn.assign(conn, :current_user, user)
            {:error, _reason} ->
              conn
          end
        {:error, _reason} ->
          conn
      end
    end
  end

Thank you in advance.


Solution

  • and it simply kill the connection

    This is because you're calling just halt on the conn. You need to send a response before halting. Here's how to send a 403 Forbidden response with the text "Forbidden":

    {:ok, nil} ->
      conn |> send_resp(403, "Forbidden") |> Plug.Conn.halt()