smpallen99 / coherence

Coherence is a full featured, configurable authentication system for Phoenix
MIT License
1.27k stars 224 forks source link

Allow overriding checkpw/2 #383

Closed dipth closed 5 years ago

dipth commented 5 years ago

This is useful if you for instance need to support authenticating some users via a legacy password imported from a legacy-database using another hashing-algorithm than your normal passwords.

Example:

defmodule Example.Coherence.User do
  def checkpw(password, encrypted) do
    if encrypted |> String.starts_with?("LEGACY!") do
      [_, hash, salt] = String.split(encrypted, "!")
      Example.Coherence.LegacyPassword.valid?(hash, salt, password)
    else
      super(password, encrypted)
    end
  end
end

defmodule Example.Coherence.LegacyPassword do
  @provider :sha512
  @stretches 20

  def valid?(nil, _salt, _pass), do: false
  def valid?(_hash, nil, _pass), do: false
  def valid?(hash, salt, pass) do
    hash == encrypt(pass <> salt)
  end

  defp encrypt(string) do
    Enum.reduce(1..@stretches, string, fn(_, acc) ->
      :crypto.hash(@provider, acc) |> Base.encode16() |> String.downcase()
    end)
  end
end
dipth commented 5 years ago

Any thoughts?

smpallen99 commented 5 years ago

Thanks!!