Skip to content

Instantly share code, notes, and snippets.

@febeling
Forked from alanpeabody/model.ex
Created December 7, 2016 15:51
Show Gist options
  • Save febeling/ba18bc59057397bec972cdd824bdfcd9 to your computer and use it in GitHub Desktop.
Save febeling/ba18bc59057397bec972cdd824bdfcd9 to your computer and use it in GitHub Desktop.
Ecto change password w/ confirmation.
defmodule User do
use Ecto.Model
schema "users" do
field :email, :string
field :hashed_password, :string
field :password, :string, virtual: true
field :password_confirmation, virtual: true
timestamps
end
before_save :hash_password
@required [:email, :password, :password_confirmation]
@optional []
def changeset(user, params) do
params
|> cast(user, @required, @optional)
|> validate_format(:email, ~r/@/)
|> validate_password_confirmation
end
defp validate_password_confirmation(%{changes: changes} = changeset) do
case changes[:password_confirmation] do
changes[:password] -> changeset
_ -> add_error(changeset, :password_confirmation, "must match password")
end
end
defp hash_password(changeset) do
#hash things
end
end
defmodule API.User do
import Plug.Conn
post "/" do
change = User.changeset(%User{}, params(conn))
if change.valid? do
send_resp(conn, 200, JSON.Encode(Repo.update(change)))
else
send_resp(conn, 422, JSON.Encode(change.errors))
end
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment