Search code examples
elixirmetaprogrammingphoenix-frameworkecto

Is it possible for a dependency to create a database table in elixir?


I am trying to build a simple auth system in elixir/phoenix that can be used as a dependency in any phoenix application.

I have followed the steps taken in the programming-phoenix-1.4 book and set up a basic auth system easily enough.

In this book they talk about separating a users sensitive and non-sensitive information into different places in the application and database. All the non-sensitive info (username, name, etc) is put in the users table while the sensitive info (email, password, etc) is put in the credentials table.

Based on this, I wondered if it would be possible to separate out the auth logic into its own application.

This auth module will need to:

  1. create a credentials table in the database of the requiring application
  2. update said table based on info passed from the parent app
  3. contain an auth plug capable of updating the conn from the parent application (for example adding :current_user to the conn with the assign function)

Unfortunately I am falling at the first hurdle at the moment. I am not sure if it is possible to require a module that can create a database table.

I imagine that if step 1 is possible step 2 will be straightforward. Step 3 looks like it can be achieved with the Router.forward/4 function.


Solution

  • It's possible by giving the dependency the name of the repo module. An example of this is GuardianDB that creates a table to store valid tokens. The configuration for GuardianDB looks like this:

    config :guardian, Guardian.DB,
      repo: MyApp.Repo,
      # default
      schema_name: "guardian_tokens",
      # default: 60 minutes
      sweep_interval: 60
    

    you can use that library as a guide github

    As for creating plugs, Guardian, which is an authentication library for Elixir does, that too. You can find the code here