Skip to content

Instantly share code, notes, and snippets.

Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save bartekupartek/ba85e078a6068cf1deef6c81bdd4c7bb to your computer and use it in GitHub Desktop.
Save bartekupartek/ba85e078a6068cf1deef6c81bdd4c7bb to your computer and use it in GitHub Desktop.
# web/helpers/session.ex
defmodule MySercetApp.Session do
alias MySercetApp.{Repo, User}
def authenticate(%{"email" => email, "password" => password}) do
user = Repo.get_by(User, email: String.downcase(email))
case check_password(user, password) do
true -> {:ok, user}
_ -> :error
end
end
# web/models/user.ex
defmodule MySercetApp.User do
use MySercetApp.Web, :model
@derive {Poison.Encoder, only: [:id, :username, :email]}
schema "users" do
field :username, :string, unique: true
field :email, :string, unique: true
field :encrypted_password, :string
field :password, :string, virtual: true
timestamps
end
@required_fields ~w(username email)
@optional_fields ~w(encrypted_password)
@doc """
Creates a changeset based on the `model` and `params`.
If no params are provided, an invalid changeset is returned
with no validation performed.
"""
def changeset(model, params \\ :empty) do
model
|> cast(params, @required_fields, @optional_fields)
|> validate_format(:email, ~r/@/)
|> validate_length(:password, min: 5)
|> validate_confirmation(:password, message: "Password does not match")
|> unique_constraint(:email, message: "Email already taken")
|> unique_constraint(:username, message: "Username already taken")
|> generate_encrypted_password
end
defp generate_encrypted_password(current_changeset) do
case current_changeset do
%Ecto.Changeset{valid?: true, changes: %{password: password}} ->
put_change(current_changeset, :encrypted_password, Comeonin.Bcrypt.hashpwsalt(password))
_ ->
current_changeset
end
end
end
defp check_password(user, password) do
case user do
nil -> Comeonin.Bcrypt.dummy_checkpw()
_ -> Comeonin.Bcrypt.checkpw(password, user.encrypted_password)
end
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment