Last active
January 3, 2024 03:29
-
-
Save alanpeabody/7eab2d4b8bedf4172130 to your computer and use it in GitHub Desktop.
Ecto change password w/ confirmation.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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 |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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
Interesting part comes when
before_save
event is used... Sometimes we need:Events are evil. And why we should validate it inside model? Are there any forms or requests that are really responsible for validation?