summaryrefslogtreecommitdiff
path: root/lib
diff options
context:
space:
mode:
Diffstat (limited to 'lib')
-rw-r--r--lib/chessh/schema/key.ex46
-rw-r--r--lib/chessh/schema/player.ex7
2 files changed, 48 insertions, 5 deletions
diff --git a/lib/chessh/schema/key.ex b/lib/chessh/schema/key.ex
new file mode 100644
index 0000000..f8c14cf
--- /dev/null
+++ b/lib/chessh/schema/key.ex
@@ -0,0 +1,46 @@
+defmodule Chessh.Key do
+ use Ecto.Schema
+ import Ecto.Changeset
+
+ schema "keys" do
+ field(:key, :string)
+ field(:name, :string)
+
+ belongs_to(:player, Chessh.Player)
+
+ timestamps()
+ end
+
+ def changeset(key, attrs) do
+ key
+ |> cast(update_encode_key(attrs, :key), [:key])
+ |> cast(attrs, [:name])
+ |> validate_required([:key, :name])
+ |> validate_format(:key, ~r/[\-\w\d]+ [^ ]+$/, message: "invalid ssh key")
+ |> validate_format(:key, ~r/^(?!ssh-dss).+/, message: "DSA keys are not supported")
+ end
+
+ defp update_encode_key(attrs, field) do
+ if Map.has_key?(attrs, field) do
+ Map.update!(attrs, field, &encode_key/1)
+ else
+ attrs
+ end
+ end
+
+ def encode_key(key) do
+ if is_tuple(key) do
+ case key do
+ {pub, [opts]} -> [{pub, [opts]}]
+ key -> [{key, [comment: '']}]
+ end
+ |> :ssh_file.encode(:openssh_key)
+ else
+ key
+ end
+ # Remove comment at end of key
+ |> String.replace(~r/ [^ ]+\@[^ ]+$/, "")
+ # Remove potential spaces / newline
+ |> String.trim()
+ end
+end
diff --git a/lib/chessh/schema/player.ex b/lib/chessh/schema/player.ex
index 7d9bb6e..d04ed3e 100644
--- a/lib/chessh/schema/player.ex
+++ b/lib/chessh/schema/player.ex
@@ -9,6 +9,8 @@ defmodule Chessh.Player do
field(:password, :string, virtual: true)
field(:hashed_password, :string)
+ has_many(:keys, Chessh.Key)
+
timestamps()
end
@@ -52,7 +54,6 @@ defmodule Chessh.Player do
message: "only letters, numbers, underscores, and hyphens allowed"
)
|> unique_constraint(:username)
- |> lowercase(:username)
end
defp validate_password(changeset, opts) do
@@ -74,8 +75,4 @@ defmodule Chessh.Player do
changeset
end
end
-
- defp lowercase(changeset, field) do
- Map.update!(changeset, field, &String.downcase/1)
- end
end