Override default current user to Guardian current user with Canary

92 views Asked by At

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!

1

There are 1 answers

1
zwippie On BEST ANSWER

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