简体   繁体   中英

Override default current user to Guardian current user with Canary

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!

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM