Best way to define current user from API to the Context in an Umbrella?


I have an umbrella app made by Phoenix 1.3. So my ecto and business logic is in one app we’ll call Core and my phoenix API is in another app called Api.

User needs to create a new shipment on the platform.

  1. Logs into API
  2. Gets a Phoenix Token returned
  3. POST /shipments to Api which in turn calls Core.Orders.create_shipment(params)

Now I need to determine is this user even authorized to do this action? So I’m using the library bodyguard to protect the contexts in Core app. However, we don’t even know who the user is?!

My approach
I’d create my own plug that will populate conn.assigns.user with user permissions on each request coming into the API and then just have the controller pass this along.

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

  def call(conn, _opts) do
    ## conn.assigns.user only has the user_id

    user = Core.Accounts.get_user!(conn.assigns.user)
    Plug.Conn.assign(conn, :current_user, user)

Pipe it up!

pipeline :authenticated do
  plug PhoenixTokenPlug.EnsureAuthenticated,
    handler: API.AuthController
  plug API.Plug.CurrentUser

In the controller just… do:

def create(conn, params) do
  Core.Orders.create_shipment(conn.assigns.current_user, params)

So any better way to get the user that’s making the API call to the Core app in the umbrella? Or is my way pretty much the way to do it without pass all of Plug.Conn.