Skip to content

Commit

Permalink
Refactor Schema.user_id_field/1
Browse files Browse the repository at this point in the history
  • Loading branch information
danschultzer committed Aug 5, 2018
1 parent a3ec42b commit 9a4ab3a
Show file tree
Hide file tree
Showing 3 changed files with 17 additions and 14 deletions.
10 changes: 5 additions & 5 deletions lib/pow/ecto/context.ex
Original file line number Diff line number Diff line change
Expand Up @@ -91,10 +91,10 @@ defmodule Pow.Ecto.Context do
"""
@spec authenticate(Config.t(), map()) :: user() | nil
def authenticate(config, params) do
user_mod = user_schema_mod(config)
user_id_field = Schema.user_id_field(user_mod)
login_value = params[Atom.to_string(user_id_field)]
password = params["password"]
user_mod = user_schema_mod(config)
user_id_field = user_mod.pow_user_id_field()
login_value = params[Atom.to_string(user_id_field)]
password = params["password"]

config
|> get_by([{user_id_field, login_value}])
Expand Down Expand Up @@ -161,7 +161,7 @@ defmodule Pow.Ecto.Context do
end

defp normalize_user_id_field_value(user_mod, clauses) do
user_id_field = Schema.user_id_field(user_mod)
user_id_field = user_mod.pow_user_id_field()

Enum.map clauses, fn
{^user_id_field, value} -> {user_id_field, Schema.normalize_user_id_field_value(value)}
Expand Down
16 changes: 8 additions & 8 deletions lib/pow/ecto/schema.ex
Original file line number Diff line number Diff line change
Expand Up @@ -137,14 +137,14 @@ defmodule Pow.Ecto.Schema do
end
end

@spec user_id_field :: atom()
def user_id_field, do: :email

@spec user_id_field(Config.t() | Changeset.t() | map() | atom()) :: atom()
def user_id_field(config) when is_list(config), do: Config.get(config, :user_id_field, user_id_field())
def user_id_field(%Changeset{data: data}), do: user_id_field(data.__struct__)
def user_id_field(map) when is_map(map), do: user_id_field(map.__struct__)
def user_id_field(module), do: module.pow_user_id_field()

@doc """
Get user id field key from configuration.
Defaults to `:email`.
"""
@spec user_id_field(Config.t()) :: atom()
def user_id_field(config \\ []), do: Config.get(config, :user_id_field, :email)

@doc """
Normalizes the user id field.
Expand Down
5 changes: 4 additions & 1 deletion lib/pow/ecto/schema/changeset.ex
Original file line number Diff line number Diff line change
Expand Up @@ -33,7 +33,10 @@ defmodule Pow.Ecto.Schema.Changeset do
"""
@spec user_id_field_changeset(Ecto.Schema.t() | Changeset.t(), map(), Config.t()) :: Changeset.t()
def user_id_field_changeset(user_or_changeset, params, _config) do
user_id_field = Schema.user_id_field(user_or_changeset)
user_id_field = case user_or_changeset do
%Changeset{data: %struct{}} -> struct.pow_user_id_field()
%struct{} -> struct.pow_user_id_field()
end

user_or_changeset
|> Changeset.cast(params, [user_id_field])
Expand Down

0 comments on commit 9a4ab3a

Please sign in to comment.