How to make Elixir Mixins

I am trying to create mixins to log into the authentication system, so it can be applied to my models, which should be able to log in. Very similar to has_secure_password in Ruby.

Afaik does this with the help of the operator use, which is necessary for the module, and invokes the macro __using__. Therefore, I implemented my mixing as follows.

defmodule MyApp.SecurePassword do
  defmacro __using__(_options) do
    quote do
      import MyApp.SecurePassword
    end
  end

  defmacro authenticate(password) do
    # Lets return true, for testing purposes.
    true
  end
end

Then I invoke the use of "user" in my model.

defmodule MyApp.Farm do
  use MyApp.Web, :model
  use MyApp.SecurePassword

  schema "farms" do
    field :name, :string
    field :email, :string
  #.....

In my controller, I am trying to use this method.

 def create(conn, %{"session" => session_params}) do
    user = Repo.get_by(Farm, email: session_params["email"])

    if user && user.authenticate(session_params["password"]) do
      conn = put_flash(conn, :success, "You were successfully logged in")
    else
      conn = put_flash(conn, :error, "Credentials didn't match")
    end

    redirect(conn, to: session_path(conn, :new))
 end

But when I find the code, I just get an argument error, on the line where I call the authentication function.

My macro skills are pretty weak, what am I doing wrong? :)

+4
source share
1 answer

, authenticate, :

def authenticate(user, password) do
  # auth logic
end

:

import MyApp.SecurePassword
# ...
if user && authenticate(user, session_params["password"]) do
# ...

use, import - , , , .

+6

All Articles