Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Allow overriding checkpw/2 #383

Merged
merged 1 commit into from
Oct 11, 2018
Merged

Allow overriding checkpw/2 #383

merged 1 commit into from
Oct 11, 2018

Conversation

dipth
Copy link
Contributor

@dipth dipth commented Oct 2, 2018

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

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:

```elixir
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
Copy link
Contributor Author

dipth commented Oct 10, 2018

Any thoughts?

@smpallen99 smpallen99 merged commit 9dd7c9c into smpallen99:master Oct 11, 2018
@smpallen99
Copy link
Owner

Thanks!!

@dipth dipth deleted the patch-1 branch October 12, 2018 07:57
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

Successfully merging this pull request may close these issues.

2 participants