Entrance v0.4.1 Entrance.Auth.Bcrypt

Provides functions for hashing passwords and authenticating users using Bcrypt.

This module assumes that you have a virtual field named password, and a database backed string field named hashed_password.

Usage

Example

defmodule YourApp.Accounts.User do
  use Ecto.Schema
  import Ecto.Changeset
  import Entrance.Auth.Bcrypt, only: [hash_password: 1] # ...

  schema "users" do
    field :email, :string
    field :password, :string, virtual: true
    field :hashed_password, :string
    field :session_secret, :string

    timestamps()
  end

  def create_changeset(user, attrs) do
    user
    |> cast(attrs, [:email, :password, :hashed_password, :session_secret])
    |> validate_required([:email, :password])
    |> hash_password # ...
  end
end

To authenticate a user in your application, you can use auth/2:

user = Repo.get(User, 1)
password = "user@password"
Entrance.Auth.Bcrypt.auth(user, password)

Link to this section Summary

Functions

Compares the given password against the given user's password.

Takes a changeset and turns the virtual password field into a hashed_password change on the changeset.

Simulates password check to help prevent timing attacks. Delegates to Bcrypt.no_user_verify/0.

Link to this section Functions

Link to this function

auth(user, password)

Compares the given password against the given user's password.

user = %{hashed_password: "iHkKDjU_example"}
password = "user@password"
Entrance.Auth.Bcrypt.auth(user, password)
Link to this function

hash_password(changeset)

Takes a changeset and turns the virtual password field into a hashed_password change on the changeset.

import Entrance.Auth.Bcrypt, only: [hash_password: 1]

# ... your user schema
def create_changeset(user, attrs) do
  user
  |> cast(attrs, [:email, :password, :hashed_password, :session_secret])
  |> validate_required([:email, :password])
  |> hash_password # :)
end
Link to this function

no_user_verify()

Simulates password check to help prevent timing attacks. Delegates to Bcrypt.no_user_verify/0.