Commit 5e8a4a01 authored by Alex Castaño's avatar Alex Castaño

Generate gravatar icon

parent 0c0ae228
......@@ -38,6 +38,7 @@ defmodule MoodleNet.Accounts do
|> Map.put("type", "Person")
|> Map.delete(:password)
|> Map.delete("password")
|> set_default_icon()
password = attrs[:password] || attrs["password"]
......@@ -221,4 +222,13 @@ defmodule MoodleNet.Accounts do
String.ends_with?(email, "@moodle.com") ||
Repo.get(WhitelistEmail, email) != nil
end
defp set_default_icon(%{icon: _} = attrs), do: attrs
defp set_default_icon(attrs) do
if email = attrs["email"] || attrs[:email] do
Map.put(attrs, :icon, %{type: "Image", url: MoodleNet.Gravatar.url(email)})
else
attrs
end
end
end
defmodule MoodleNet.Gravatar do
@uri %URI{
scheme: "https",
host: "s.gravatar.com",
query: "d=identicon&r=g&s=80"
}
def url(email) when is_binary(email) do
%{@uri | path: path(email)} |> URI.to_string()
end
defp path(email), do: "/avatar/#{hash(email)}"
defp hash(email),
do: :crypto.hash(:md5, String.downcase(email)) |> Base.encode16(case: :lower)
end
......@@ -31,6 +31,15 @@ defmodule MoodleNet.AccountsTest do
assert {:ok, _} = Accounts.register_user(attrs)
end
test "set gravatar icon by default" do
attrs = Factory.attributes(:user, email: "alex@moodle.com")
|> Map.delete("icon")
assert {:ok, %{actor: actor}} = Accounts.register_user(attrs)
assert ["https://s.gravatar.com/avatar/7779b850ea05dbeca7fc39a910a77f21?d=identicon&r=g&s=80"] == get_in(actor, [:icon, Access.at(0), :url])
end
test "fails with invalid password values" do
attrs = Factory.attributes(:user) |> Map.delete("password")
Accounts.add_email_to_whitelist(attrs["email"])
......
defmodule MoodleNet.GravatarTest do
use MoodleNet.DataCase, async: true
test "works" do
assert "https://s.gravatar.com/avatar/7779b850ea05dbeca7fc39a910a77f21?d=identicon&r=g&s=80" == MoodleNet.Gravatar.url("alex@moodle.com")
end
end
Markdown is supported
0% or
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment