Skip to content

Instantly share code, notes, and snippets.

@scrogson
Created October 30, 2014 02:00
Show Gist options
  • Save scrogson/1e46a62858534b71db34 to your computer and use it in GitHub Desktop.
Save scrogson/1e46a62858534b71db34 to your computer and use it in GitHub Desktop.
defmodule Statistik.User do
use Statistik.Model
schema "users" do
field :email, :string
field :password, :virtual
field :password_confirmation, :virtual
field :encrypted_password, :string
end
validate user,
email: present(),
password: present() when on_create?(user),
password_confirmation: present() when on_create?(user),
password: equal_to(user.password_confirmation, message: "must match password confirmation") when on_create?(user)
def authenticate!(email: email, password: password) do
Statistik.User
|> where([u], u.email == ^email)
|> where([u], u.encrypted_password == ^encrypt_password(password))
|> Repo.one
end
def encrypt_password(user = %__MODULE__{}) do
struct(user, encrypted_password: encrypt_password(user.password))
end
def encrypt_password(password) when is_binary(password) do
Statistik.Router.config(:secret_key_base)
|> Plug.Crypto.KeyGenerator.generate(password, iterations: 65536)
|> Base.encode64
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment