diff --git a/lib/chessh/schema/player.ex b/lib/chessh/schema/player.ex index 9c83349..dcb3548 100644 --- a/lib/chessh/schema/player.ex +++ b/lib/chessh/schema/player.ex @@ -35,11 +35,19 @@ defmodule Chessh.Player do |> cast(attrs, [:authentications]) end + def discord_changeset(player, attrs) do + player + |> cast(attrs, [:username, :discord_id]) + |> validate_username() + |> validate_discord_id() + end + def registration_changeset(player, attrs, opts \\ []) do player |> cast(attrs, [:username, :password, :discord_id]) |> validate_username() |> validate_password(opts) + |> validate_discord_id() end def password_changeset(player, attrs, opts \\ []) do @@ -67,13 +75,16 @@ defmodule Chessh.Player do end end + defp validate_discord_id(changeset) do + changeset + |> unique_constraint(:discord_id) + end + defp validate_username(changeset) do changeset |> validate_required([:username]) - |> validate_length(:username, min: 2, max: 16) - |> validate_format(:username, ~r/^[a-zA-Z0-9_\-]*$/, - message: "only letters, numbers, underscores, and hyphens allowed" - ) + |> validate_length(:username, min: 2, max: 40) + |> validate_format(:username, ~r/^.{3,32}#[0-9]{4}$/, message: "must match discord tag format") |> unique_constraint(:username) end diff --git a/lib/chessh/web/web.ex b/lib/chessh/web/web.ex index 2b465b2..8cddd32 100644 --- a/lib/chessh/web/web.ex +++ b/lib/chessh/web/web.ex @@ -270,19 +270,22 @@ defmodule Chessh.Web.Endpoint do %{"username" => username, "discriminator" => discriminator, "id" => discord_id} = Jason.decode!(String.Chars.to_string(user_details)) - %Player{id: id} = - Repo.insert!( - %Player{discord_id: discord_id, username: username <> "#" <> discriminator}, - on_conflict: [set: [discord_id: discord_id]], - conflict_target: :discord_id - ) + case Repo.get_by(Player, discord_id: discord_id) do + nil -> %Player{discord_id: discord_id} + player -> player + end + |> Player.discord_changeset(%{ + username: username <> "#" <> discriminator, + discord_id: discord_id + }) + |> Repo.insert_or_update() {200, %{ success: true, jwt: Token.generate_and_sign!(%{ - "uid" => id + "uid" => Repo.get_by(Player, discord_id: discord_id).id }) }}