1
0
mirror of https://github.com/danbee/chess synced 2025-03-04 08:39:06 +00:00

We are treating name as more like a username

Therefore it should be a unique way of identifying a user.
This commit is contained in:
Daniel Barber 2018-09-28 14:44:41 -04:00
parent bc95773c8f
commit 9349af64a0
Signed by: danbarber
GPG Key ID: 931D8112E0103DD8
3 changed files with 32 additions and 10 deletions

View File

@ -20,20 +20,23 @@ defmodule Chess.Store.User do
timestamps()
end
@profile_attrs ~w[name email]a
@registration_attrs ~w[name email password]a
@doc false
def changeset(struct, params \\ %{}) do
struct
|> cast(params, registration_attrs())
|> validate_required(registration_attrs())
|> unique_constraint(:email)
|> cast(params, @registration_attrs)
|> validate_required(@registration_attrs)
|> unique_validations()
|> hash_password()
end
def profile_changeset(struct, params \\ %{}) do
struct
|> cast(params, profile_attrs())
|> validate_required(profile_attrs())
|> unique_constraint(:email)
|> cast(params, @profile_attrs)
|> validate_required(@profile_attrs)
|> unique_validations()
end
def password_changeset(struct, params \\ %{}) do
@ -43,6 +46,12 @@ defmodule Chess.Store.User do
|> hash_password()
end
def unique_validations(struct, params \\ %{}) do
struct
|> unique_constraint(:name)
|> unique_constraint(:email)
end
def opponents(user) do
from user in "users",
where: user.id != ^user.id,
@ -58,7 +67,4 @@ defmodule Chess.Store.User do
changeset
end
end
defp registration_attrs, do: ~w[name email password]a
defp profile_attrs, do: ~w{name email}a
end

View File

@ -0,0 +1,7 @@
defmodule Chess.Repo.Migrations.AddUniqueIndexToUsersName do
use Ecto.Migration
def change do
create unique_index(:users, [:name])
end
end

View File

@ -25,7 +25,16 @@ defmodule Chess.Store.UserTest do
end
test "email must be unique" do
insert(:user, %{email: "zelda@hyrule.com"})
insert(:user, %{name: "Princess", email: "zelda@hyrule.com"})
changeset = User.changeset(%User{}, @valid_attrs)
{:error, changeset} = Repo.insert(changeset)
refute changeset.valid?
end
test "name must be unique" do
insert(:user, %{name: "Zelda", email: "princess@hyrule.kingdom"})
changeset = User.changeset(%User{}, @valid_attrs)
{:error, changeset} = Repo.insert(changeset)