0

I am trying to implement Canary into my application, and I have come across a problem. The docs (https://github.com/cpjk/canary#overriding-the-default-user) say that I need to have an Ecto record for the current user in conn.assigns.current_user. Since I am using Guardian, my current user is stored in Guardian.Plug.current_resource(conn). What is the best way to let canary know that this is where I store my current user?

I can't use the config :canary, current_user: :my_user_key because it isn't even in conn.assigns.

Help is appreciated!

oriont
  • 684
  • 2
  • 10
  • 25

1 Answers1

2

Following this article, you should create a Plug for that:

defmodule MyApp.Plug.CurrentUser do
  def init(opts), do: opts

  def call(conn, _opts) do
    current_user = Guardian.Plug.current_resource(conn)
    Plug.Conn.assign(conn, :current_user, current_user)
  end
end

and put it in a router pipeline:

pipeline :require_login do
  plug Guardian.Plug.EnsureAuthenticated, handler: MyApp.GuardianErrorHandler
  plug MyApp.Plug.CurrentUser
end
zwippie
  • 15,050
  • 3
  • 39
  • 54
  • I ended up doing that, but it took me a while to figure out that I had to put the plug right after the EnsureAuthenticated plug. Thanks! – oriont Apr 20 '20 at 14:53